repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Compilers/Core/CodeAnalysisTest/Collections/List/IList.Generic.Tests.cs
// 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. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Collections/IList.Generic.Tests.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { /// <summary> /// Contains tests that ensure the correctness of any class that implements the generic /// IList interface /// </summary> public abstract class IList_Generic_Tests<T> : ICollection_Generic_Tests<T> where T : notnull { #region IList<T> Helper Methods /// <summary> /// Creates an instance of an IList{T} that can be used for testing. /// </summary> /// <returns>An instance of an IList{T} that can be used for testing.</returns> protected abstract IList<T> GenericIListFactory(); /// <summary> /// Creates an instance of an IList{T} that can be used for testing. /// </summary> /// <param name="count">The number of unique items that the returned IList{T} contains.</param> /// <returns>An instance of an IList{T} that can be used for testing.</returns> protected virtual IList<T> GenericIListFactory(int count) { IList<T> collection = GenericIListFactory(); AddToCollection(collection, count); return collection; } /// <summary> /// Returns a set of ModifyEnumerable delegates that modify the enumerable passed to them. /// </summary> protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) { foreach (var item in base.GetModifyEnumerables(operations)) yield return item; if (!AddRemoveClear_ThrowsNotSupported && (operations & ModifyOperation.Insert) == ModifyOperation.Insert) { yield return (IEnumerable<T> enumerable) => { IList<T> casted = ((IList<T>)enumerable); if (casted.Count > 0) { casted.Insert(0, CreateT(12)); return true; } return false; }; } if (!AddRemoveClear_ThrowsNotSupported && (operations & ModifyOperation.Overwrite) == ModifyOperation.Overwrite) { yield return (IEnumerable<T> enumerable) => { IList<T> casted = ((IList<T>)enumerable); if (casted.Count > 0) { casted[0] = CreateT(12); return true; } return false; }; } if (!AddRemoveClear_ThrowsNotSupported && (operations & ModifyOperation.Remove) == ModifyOperation.Remove) { yield return (IEnumerable<T> enumerable) => { IList<T> casted = ((IList<T>)enumerable); if (casted.Count > 0) { casted.RemoveAt(0); return true; } return false; }; } } #endregion #region ICollection<T> Helper Methods protected override bool DefaultValueWhenNotAllowed_Throws => false; protected override ICollection<T> GenericICollectionFactory() => GenericIListFactory(); protected override ICollection<T> GenericICollectionFactory(int count) => GenericIListFactory(count); protected virtual Type IList_Generic_Item_InvalidIndex_ThrowType => typeof(ArgumentOutOfRangeException); #endregion #region Item Getter [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemGet_NegativeIndex_ThrowsException(int count) { IList<T> list = GenericIListFactory(count); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[-1]); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[int.MinValue]); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemGet_IndexGreaterThanListCount_ThrowsException(int count) { IList<T> list = GenericIListFactory(count); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[count]); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[count + 1]); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemGet_ValidGetWithinListBounds(int count) { IList<T> list = GenericIListFactory(count); T result; Assert.All(Enumerable.Range(0, count), index => result = list[index]); } #endregion #region Item Setter [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_NegativeIndex_ThrowsException(int count) { if (!IsReadOnly) { IList<T> list = GenericIListFactory(count); T validAdd = CreateT(0); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[-1] = validAdd); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[int.MinValue] = validAdd); Assert.Equal(count, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_IndexGreaterThanListCount_ThrowsException(int count) { if (!IsReadOnly) { IList<T> list = GenericIListFactory(count); T validAdd = CreateT(0); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[count] = validAdd); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[count + 1] = validAdd); Assert.Equal(count, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_OnReadOnlyList(int count) { if (IsReadOnly && count > 0) { IList<T> list = GenericIListFactory(count); T before = list[count / 2]; Assert.Throws<NotSupportedException>(() => list[count / 2] = CreateT(321432)); Assert.Equal(before, list[count / 2]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_FirstItemToNonDefaultValue(int count) { if (count > 0 && !IsReadOnly) { IList<T> list = GenericIListFactory(count); T value = CreateT(123452); list[0] = value; Assert.Equal(value, list[0]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_FirstItemToDefaultValue(int count) { if (count > 0 && !IsReadOnly) { IList<T> list = GenericIListFactory(count); if (DefaultValueAllowed) { list[0] = default(T)!; Assert.Equal(default(T), list[0]); } else { Assert.Throws<ArgumentNullException>(() => list[0] = default(T)!); Assert.NotEqual(default(T), list[0]); } } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_LastItemToNonDefaultValue(int count) { if (count > 0 && !IsReadOnly) { IList<T> list = GenericIListFactory(count); T value = CreateT(123452); int lastIndex = count > 0 ? count - 1 : 0; list[lastIndex] = value; Assert.Equal(value, list[lastIndex]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_LastItemToDefaultValue(int count) { if (count > 0 && !IsReadOnly && DefaultValueAllowed) { IList<T> list = GenericIListFactory(count); int lastIndex = count > 0 ? count - 1 : 0; if (DefaultValueAllowed) { list[lastIndex] = default(T)!; Assert.Equal(default(T), list[lastIndex]); } else { Assert.Throws<ArgumentNullException>(() => list[lastIndex] = default(T)!); Assert.NotEqual(default(T), list[lastIndex]); } } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_DuplicateValues(int count) { if (count >= 2 && !IsReadOnly && DuplicateValuesAllowed) { IList<T> list = GenericIListFactory(count); T value = CreateT(123452); list[0] = value; list[1] = value; Assert.Equal(value, list[0]); Assert.Equal(value, list[1]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_InvalidValue(int count) { if (count > 0 && !IsReadOnly) { Assert.All(InvalidValues, value => { IList<T> list = GenericIListFactory(count); Assert.Throws<ArgumentException>(() => list[count / 2] = value); }); } } #endregion #region IndexOf [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_IndexOf_DefaultValueNotContainedInList(int count) { if (DefaultValueAllowed) { IList<T?> list = GenericIListFactory(count)!; T? value = default(T); if (list.Contains(value)) { if (IsReadOnly) return; list.Remove(value); } Assert.Equal(-1, list.IndexOf(value)); } else { IList<T> list = GenericIListFactory(count); Assert.Throws<ArgumentNullException>(() => list.IndexOf(default(T)!)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_IndexOf_DefaultValueContainedInList(int count) { if (count > 0 && DefaultValueAllowed) { IList<T?> list = GenericIListFactory(count)!; T? value = default(T); if (!list.Contains(value)) { if (IsReadOnly) return; list[0] = value; } Assert.Equal(0, list.IndexOf(value)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_IndexOf_ValidValueNotContainedInList(int count) { IList<T> list = GenericIListFactory(count); int seed = 54321; T value = CreateT(seed++); while (list.Contains(value)) value = CreateT(seed++); Assert.Equal(-1, list.IndexOf(value)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_IndexOf_ValueInCollectionMultipleTimes(int count) { if (count > 0 && !IsReadOnly && DuplicateValuesAllowed) { // IndexOf should always return the lowest index for which a matching element is found IList<T> list = GenericIListFactory(count); T value = CreateT(12345); list[0] = value; list[count / 2] = value; Assert.Equal(0, list.IndexOf(value)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_IndexOf_EachValueNoDuplicates(int count) { // Assumes no duplicate elements contained in the list returned by GenericIListFactory IList<T> list = GenericIListFactory(count); Assert.All(Enumerable.Range(0, count), index => { Assert.Equal(index, list.IndexOf(list[index])); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_IndexOf_InvalidValue(int count) { if (!IsReadOnly) { Assert.All(InvalidValues, value => { IList<T> list = GenericIListFactory(count); Assert.Throws<ArgumentException>(() => list.IndexOf(value)); }); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_IndexOf_ReturnsFirstMatchingValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); foreach (T duplicate in list.ToList()) // hard copies list to circumvent enumeration error list.Add(duplicate); List<T> expectedList = list.ToList(); Assert.All(Enumerable.Range(0, count), (index => Assert.Equal(index, list.IndexOf(expectedList[index])) )); } } #endregion #region Insert [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_NegativeIndex_ThrowsArgumentOutOfRangeException(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); T validAdd = CreateT(0); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, validAdd)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(int.MinValue, validAdd)); Assert.Equal(count, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_IndexGreaterThanListCount_Appends(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); T validAdd = CreateT(12350); list.Insert(count, validAdd); Assert.Equal(count + 1, list.Count); Assert.Equal(validAdd, list[count]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_ToReadOnlyList(int count) { if (IsReadOnly || AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); Assert.Throws<NotSupportedException>(() => list.Insert(count / 2, CreateT(321432))); Assert.Equal(count, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_FirstItemToNonDefaultValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); T value = CreateT(123452); list.Insert(0, value); Assert.Equal(value, list[0]); Assert.Equal(count + 1, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_FirstItemToDefaultValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported && DefaultValueAllowed) { IList<T?> list = GenericIListFactory(count)!; T? value = default(T); list.Insert(0, value); Assert.Equal(value, list[0]); Assert.Equal(count + 1, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_LastItemToNonDefaultValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); T value = CreateT(123452); int lastIndex = count > 0 ? count - 1 : 0; list.Insert(lastIndex, value); Assert.Equal(value, list[lastIndex]); Assert.Equal(count + 1, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_LastItemToDefaultValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported && DefaultValueAllowed) { IList<T?> list = GenericIListFactory(count)!; T? value = default(T); int lastIndex = count > 0 ? count - 1 : 0; list.Insert(lastIndex, value); Assert.Equal(value, list[lastIndex]); Assert.Equal(count + 1, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_DuplicateValues(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported && DuplicateValuesAllowed) { IList<T> list = GenericIListFactory(count); T value = CreateT(123452); if (AddRemoveClear_ThrowsNotSupported) { Assert.Throws<NotSupportedException>(() => list.Insert(0, value)); } else { list.Insert(0, value); list.Insert(1, value); Assert.Equal(value, list[0]); Assert.Equal(value, list[1]); Assert.Equal(count + 2, list.Count); } } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_InvalidValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { Assert.All(InvalidValues, value => { IList<T> list = GenericIListFactory(count); Assert.Throws<ArgumentException>(() => list.Insert(count / 2, value)); }); } } #endregion #region RemoveAt [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_RemoveAt_NegativeIndex_ThrowsArgumentOutOfRangeException(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); T validAdd = CreateT(0); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(int.MinValue)); Assert.Equal(count, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_RemoveAt_IndexGreaterThanListCount_ThrowsArgumentOutOfRangeException(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); T validAdd = CreateT(0); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(count)); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(count + 1)); Assert.Equal(count, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_RemoveAt_OnReadOnlyList(int count) { if (IsReadOnly || AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); Assert.Throws<NotSupportedException>(() => list.RemoveAt(count / 2)); Assert.Equal(count, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_RemoveAt_AllValidIndices(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); Assert.Equal(count, list.Count); Assert.All(Enumerable.Range(0, count).Reverse(), index => { list.RemoveAt(index); Assert.Equal(index, list.Count); }); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_RemoveAt_ZeroMultipleTimes(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); Assert.All(Enumerable.Range(0, count), index => { list.RemoveAt(0); Assert.Equal(count - index - 1, list.Count); }); } } #endregion #region Enumerator.Current // Test Enumerator.Current at end after new elements was added [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_CurrentAtEnd_AfterAdd(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> collection = GenericIListFactory(count); using (IEnumerator<T> enumerator = collection.GetEnumerator()) { while (enumerator.MoveNext()) ; // Go to end of enumerator T? current = default(T); if (Enumerator_Current_UndefinedOperation_Throws) { Assert.Throws<InvalidOperationException>(() => enumerator.Current); // enumerator.Current should fail } else { current = enumerator.Current; Assert.Equal(default(T), current); } // Test after add int seed = 3538963; for (int i = 0; i < 3; i++) { collection.Add(CreateT(seed++)); if (Enumerator_Current_UndefinedOperation_Throws) { Assert.Throws<InvalidOperationException>(() => enumerator.Current); // enumerator.Current should fail } else { current = enumerator.Current; Assert.Equal(default(T), current); } } } } } #endregion } }
// 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. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Collections/IList.Generic.Tests.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { /// <summary> /// Contains tests that ensure the correctness of any class that implements the generic /// IList interface /// </summary> public abstract class IList_Generic_Tests<T> : ICollection_Generic_Tests<T> where T : notnull { #region IList<T> Helper Methods /// <summary> /// Creates an instance of an IList{T} that can be used for testing. /// </summary> /// <returns>An instance of an IList{T} that can be used for testing.</returns> protected abstract IList<T> GenericIListFactory(); /// <summary> /// Creates an instance of an IList{T} that can be used for testing. /// </summary> /// <param name="count">The number of unique items that the returned IList{T} contains.</param> /// <returns>An instance of an IList{T} that can be used for testing.</returns> protected virtual IList<T> GenericIListFactory(int count) { IList<T> collection = GenericIListFactory(); AddToCollection(collection, count); return collection; } /// <summary> /// Returns a set of ModifyEnumerable delegates that modify the enumerable passed to them. /// </summary> protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) { foreach (var item in base.GetModifyEnumerables(operations)) yield return item; if (!AddRemoveClear_ThrowsNotSupported && (operations & ModifyOperation.Insert) == ModifyOperation.Insert) { yield return (IEnumerable<T> enumerable) => { IList<T> casted = ((IList<T>)enumerable); if (casted.Count > 0) { casted.Insert(0, CreateT(12)); return true; } return false; }; } if (!AddRemoveClear_ThrowsNotSupported && (operations & ModifyOperation.Overwrite) == ModifyOperation.Overwrite) { yield return (IEnumerable<T> enumerable) => { IList<T> casted = ((IList<T>)enumerable); if (casted.Count > 0) { casted[0] = CreateT(12); return true; } return false; }; } if (!AddRemoveClear_ThrowsNotSupported && (operations & ModifyOperation.Remove) == ModifyOperation.Remove) { yield return (IEnumerable<T> enumerable) => { IList<T> casted = ((IList<T>)enumerable); if (casted.Count > 0) { casted.RemoveAt(0); return true; } return false; }; } } #endregion #region ICollection<T> Helper Methods protected override bool DefaultValueWhenNotAllowed_Throws => false; protected override ICollection<T> GenericICollectionFactory() => GenericIListFactory(); protected override ICollection<T> GenericICollectionFactory(int count) => GenericIListFactory(count); protected virtual Type IList_Generic_Item_InvalidIndex_ThrowType => typeof(ArgumentOutOfRangeException); #endregion #region Item Getter [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemGet_NegativeIndex_ThrowsException(int count) { IList<T> list = GenericIListFactory(count); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[-1]); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[int.MinValue]); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemGet_IndexGreaterThanListCount_ThrowsException(int count) { IList<T> list = GenericIListFactory(count); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[count]); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[count + 1]); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemGet_ValidGetWithinListBounds(int count) { IList<T> list = GenericIListFactory(count); T result; Assert.All(Enumerable.Range(0, count), index => result = list[index]); } #endregion #region Item Setter [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_NegativeIndex_ThrowsException(int count) { if (!IsReadOnly) { IList<T> list = GenericIListFactory(count); T validAdd = CreateT(0); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[-1] = validAdd); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[int.MinValue] = validAdd); Assert.Equal(count, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_IndexGreaterThanListCount_ThrowsException(int count) { if (!IsReadOnly) { IList<T> list = GenericIListFactory(count); T validAdd = CreateT(0); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[count] = validAdd); Assert.Throws(IList_Generic_Item_InvalidIndex_ThrowType, () => list[count + 1] = validAdd); Assert.Equal(count, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_OnReadOnlyList(int count) { if (IsReadOnly && count > 0) { IList<T> list = GenericIListFactory(count); T before = list[count / 2]; Assert.Throws<NotSupportedException>(() => list[count / 2] = CreateT(321432)); Assert.Equal(before, list[count / 2]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_FirstItemToNonDefaultValue(int count) { if (count > 0 && !IsReadOnly) { IList<T> list = GenericIListFactory(count); T value = CreateT(123452); list[0] = value; Assert.Equal(value, list[0]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_FirstItemToDefaultValue(int count) { if (count > 0 && !IsReadOnly) { IList<T> list = GenericIListFactory(count); if (DefaultValueAllowed) { list[0] = default(T)!; Assert.Equal(default(T), list[0]); } else { Assert.Throws<ArgumentNullException>(() => list[0] = default(T)!); Assert.NotEqual(default(T), list[0]); } } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_LastItemToNonDefaultValue(int count) { if (count > 0 && !IsReadOnly) { IList<T> list = GenericIListFactory(count); T value = CreateT(123452); int lastIndex = count > 0 ? count - 1 : 0; list[lastIndex] = value; Assert.Equal(value, list[lastIndex]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_LastItemToDefaultValue(int count) { if (count > 0 && !IsReadOnly && DefaultValueAllowed) { IList<T> list = GenericIListFactory(count); int lastIndex = count > 0 ? count - 1 : 0; if (DefaultValueAllowed) { list[lastIndex] = default(T)!; Assert.Equal(default(T), list[lastIndex]); } else { Assert.Throws<ArgumentNullException>(() => list[lastIndex] = default(T)!); Assert.NotEqual(default(T), list[lastIndex]); } } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_DuplicateValues(int count) { if (count >= 2 && !IsReadOnly && DuplicateValuesAllowed) { IList<T> list = GenericIListFactory(count); T value = CreateT(123452); list[0] = value; list[1] = value; Assert.Equal(value, list[0]); Assert.Equal(value, list[1]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_ItemSet_InvalidValue(int count) { if (count > 0 && !IsReadOnly) { Assert.All(InvalidValues, value => { IList<T> list = GenericIListFactory(count); Assert.Throws<ArgumentException>(() => list[count / 2] = value); }); } } #endregion #region IndexOf [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_IndexOf_DefaultValueNotContainedInList(int count) { if (DefaultValueAllowed) { IList<T?> list = GenericIListFactory(count)!; T? value = default(T); if (list.Contains(value)) { if (IsReadOnly) return; list.Remove(value); } Assert.Equal(-1, list.IndexOf(value)); } else { IList<T> list = GenericIListFactory(count); Assert.Throws<ArgumentNullException>(() => list.IndexOf(default(T)!)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_IndexOf_DefaultValueContainedInList(int count) { if (count > 0 && DefaultValueAllowed) { IList<T?> list = GenericIListFactory(count)!; T? value = default(T); if (!list.Contains(value)) { if (IsReadOnly) return; list[0] = value; } Assert.Equal(0, list.IndexOf(value)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_IndexOf_ValidValueNotContainedInList(int count) { IList<T> list = GenericIListFactory(count); int seed = 54321; T value = CreateT(seed++); while (list.Contains(value)) value = CreateT(seed++); Assert.Equal(-1, list.IndexOf(value)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_IndexOf_ValueInCollectionMultipleTimes(int count) { if (count > 0 && !IsReadOnly && DuplicateValuesAllowed) { // IndexOf should always return the lowest index for which a matching element is found IList<T> list = GenericIListFactory(count); T value = CreateT(12345); list[0] = value; list[count / 2] = value; Assert.Equal(0, list.IndexOf(value)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_IndexOf_EachValueNoDuplicates(int count) { // Assumes no duplicate elements contained in the list returned by GenericIListFactory IList<T> list = GenericIListFactory(count); Assert.All(Enumerable.Range(0, count), index => { Assert.Equal(index, list.IndexOf(list[index])); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_IndexOf_InvalidValue(int count) { if (!IsReadOnly) { Assert.All(InvalidValues, value => { IList<T> list = GenericIListFactory(count); Assert.Throws<ArgumentException>(() => list.IndexOf(value)); }); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_IndexOf_ReturnsFirstMatchingValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); foreach (T duplicate in list.ToList()) // hard copies list to circumvent enumeration error list.Add(duplicate); List<T> expectedList = list.ToList(); Assert.All(Enumerable.Range(0, count), (index => Assert.Equal(index, list.IndexOf(expectedList[index])) )); } } #endregion #region Insert [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_NegativeIndex_ThrowsArgumentOutOfRangeException(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); T validAdd = CreateT(0); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, validAdd)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(int.MinValue, validAdd)); Assert.Equal(count, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_IndexGreaterThanListCount_Appends(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); T validAdd = CreateT(12350); list.Insert(count, validAdd); Assert.Equal(count + 1, list.Count); Assert.Equal(validAdd, list[count]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_ToReadOnlyList(int count) { if (IsReadOnly || AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); Assert.Throws<NotSupportedException>(() => list.Insert(count / 2, CreateT(321432))); Assert.Equal(count, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_FirstItemToNonDefaultValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); T value = CreateT(123452); list.Insert(0, value); Assert.Equal(value, list[0]); Assert.Equal(count + 1, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_FirstItemToDefaultValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported && DefaultValueAllowed) { IList<T?> list = GenericIListFactory(count)!; T? value = default(T); list.Insert(0, value); Assert.Equal(value, list[0]); Assert.Equal(count + 1, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_LastItemToNonDefaultValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); T value = CreateT(123452); int lastIndex = count > 0 ? count - 1 : 0; list.Insert(lastIndex, value); Assert.Equal(value, list[lastIndex]); Assert.Equal(count + 1, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_LastItemToDefaultValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported && DefaultValueAllowed) { IList<T?> list = GenericIListFactory(count)!; T? value = default(T); int lastIndex = count > 0 ? count - 1 : 0; list.Insert(lastIndex, value); Assert.Equal(value, list[lastIndex]); Assert.Equal(count + 1, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_DuplicateValues(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported && DuplicateValuesAllowed) { IList<T> list = GenericIListFactory(count); T value = CreateT(123452); if (AddRemoveClear_ThrowsNotSupported) { Assert.Throws<NotSupportedException>(() => list.Insert(0, value)); } else { list.Insert(0, value); list.Insert(1, value); Assert.Equal(value, list[0]); Assert.Equal(value, list[1]); Assert.Equal(count + 2, list.Count); } } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_Insert_InvalidValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { Assert.All(InvalidValues, value => { IList<T> list = GenericIListFactory(count); Assert.Throws<ArgumentException>(() => list.Insert(count / 2, value)); }); } } #endregion #region RemoveAt [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_RemoveAt_NegativeIndex_ThrowsArgumentOutOfRangeException(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); T validAdd = CreateT(0); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(int.MinValue)); Assert.Equal(count, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_RemoveAt_IndexGreaterThanListCount_ThrowsArgumentOutOfRangeException(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); T validAdd = CreateT(0); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(count)); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(count + 1)); Assert.Equal(count, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_RemoveAt_OnReadOnlyList(int count) { if (IsReadOnly || AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); Assert.Throws<NotSupportedException>(() => list.RemoveAt(count / 2)); Assert.Equal(count, list.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_RemoveAt_AllValidIndices(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); Assert.Equal(count, list.Count); Assert.All(Enumerable.Range(0, count).Reverse(), index => { list.RemoveAt(index); Assert.Equal(index, list.Count); }); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_RemoveAt_ZeroMultipleTimes(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> list = GenericIListFactory(count); Assert.All(Enumerable.Range(0, count), index => { list.RemoveAt(0); Assert.Equal(count - index - 1, list.Count); }); } } #endregion #region Enumerator.Current // Test Enumerator.Current at end after new elements was added [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IList_Generic_CurrentAtEnd_AfterAdd(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { IList<T> collection = GenericIListFactory(count); using (IEnumerator<T> enumerator = collection.GetEnumerator()) { while (enumerator.MoveNext()) ; // Go to end of enumerator T? current = default(T); if (Enumerator_Current_UndefinedOperation_Throws) { Assert.Throws<InvalidOperationException>(() => enumerator.Current); // enumerator.Current should fail } else { current = enumerator.Current; Assert.Equal(default(T), current); } // Test after add int seed = 3538963; for (int i = 0; i < 3; i++) { collection.Add(CreateT(seed++)); if (Enumerator_Current_UndefinedOperation_Throws) { Assert.Throws<InvalidOperationException>(() => enumerator.Current); // enumerator.Current should fail } else { current = enumerator.Current; Assert.Equal(default(T), current); } } } } } #endregion } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/VisualStudio/Core/Def/Implementation/Preview/ChangeList.cs
// 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. #nullable disable using System; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview { internal partial class ChangeList : IVsPreviewChangesList, IVsLiteTreeList { public static readonly ChangeList Empty = new(Array.Empty<AbstractChange>()); internal AbstractChange[] Changes { get; } public ChangeList(AbstractChange[] changes) => this.Changes = changes; public int GetDisplayData(uint index, VSTREEDISPLAYDATA[] pData) { pData[0].Mask = (uint)_VSTREEDISPLAYMASK.TDM_STATE | (uint)_VSTREEDISPLAYMASK.TDM_IMAGE | (uint)_VSTREEDISPLAYMASK.TDM_SELECTEDIMAGE; // Set TDS_SELECTED and TDS_GRAYTEXT pData[0].State = Changes[index].GetDisplayState(); Changes[index].GetDisplayData(pData); return VSConstants.S_OK; } public int GetExpandable(uint index, out int pfExpandable) { pfExpandable = Changes[index].IsExpandable; return VSConstants.S_OK; } public int GetExpandedList(uint index, out int pfCanRecurse, out IVsLiteTreeList pptlNode) { pfCanRecurse = Changes[index].CanRecurse; pptlNode = (IVsLiteTreeList)Changes[index].GetChildren(); return VSConstants.S_OK; } public int GetFlags(out uint pFlags) { // The interface IVsSimplePreviewChangesList doesn't include this method. // Setting flags to 0 is necessary to make the underlying treeview draw // checkboxes and make them clickable. pFlags = 0; return VSConstants.S_OK; } public int GetItemCount(out uint pCount) { pCount = (uint)Changes.Length; return VSConstants.S_OK; } public int GetListChanges(ref uint pcChanges, VSTREELISTITEMCHANGE[] prgListChanges) => VSConstants.E_FAIL; public int GetText(uint index, VSTREETEXTOPTIONS tto, out string ppszText) => Changes[index].GetText(out _, out ppszText); public int GetTipText(uint index, VSTREETOOLTIPTYPE eTipType, out string ppszText) => Changes[index].GetTipText(out _, out ppszText); public int LocateExpandedList(IVsLiteTreeList child, out uint iIndex) { for (var i = 0; i < Changes.Length; i++) { if (Changes[i].GetChildren() == child) { iIndex = (uint)i; return VSConstants.S_OK; } } iIndex = 0; return VSConstants.S_FALSE; } public int OnClose(VSTREECLOSEACTIONS[] ptca) => VSConstants.S_OK; public int OnRequestSource(uint index, object pIUnknownTextView) => Changes[index].OnRequestSource(pIUnknownTextView); public int ToggleState(uint index, out uint ptscr) { Changes[index].Toggle(); ptscr = (uint)_VSTREESTATECHANGEREFRESH.TSCR_ENTIRE; Changes[index].OnRequestSource(null); return VSConstants.S_OK; } public int UpdateCounter(out uint pCurUpdate, out uint pgrfChanges) { pCurUpdate = 0; pgrfChanges = 0; return VSConstants.S_OK; } } }
// 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. #nullable disable using System; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview { internal partial class ChangeList : IVsPreviewChangesList, IVsLiteTreeList { public static readonly ChangeList Empty = new(Array.Empty<AbstractChange>()); internal AbstractChange[] Changes { get; } public ChangeList(AbstractChange[] changes) => this.Changes = changes; public int GetDisplayData(uint index, VSTREEDISPLAYDATA[] pData) { pData[0].Mask = (uint)_VSTREEDISPLAYMASK.TDM_STATE | (uint)_VSTREEDISPLAYMASK.TDM_IMAGE | (uint)_VSTREEDISPLAYMASK.TDM_SELECTEDIMAGE; // Set TDS_SELECTED and TDS_GRAYTEXT pData[0].State = Changes[index].GetDisplayState(); Changes[index].GetDisplayData(pData); return VSConstants.S_OK; } public int GetExpandable(uint index, out int pfExpandable) { pfExpandable = Changes[index].IsExpandable; return VSConstants.S_OK; } public int GetExpandedList(uint index, out int pfCanRecurse, out IVsLiteTreeList pptlNode) { pfCanRecurse = Changes[index].CanRecurse; pptlNode = (IVsLiteTreeList)Changes[index].GetChildren(); return VSConstants.S_OK; } public int GetFlags(out uint pFlags) { // The interface IVsSimplePreviewChangesList doesn't include this method. // Setting flags to 0 is necessary to make the underlying treeview draw // checkboxes and make them clickable. pFlags = 0; return VSConstants.S_OK; } public int GetItemCount(out uint pCount) { pCount = (uint)Changes.Length; return VSConstants.S_OK; } public int GetListChanges(ref uint pcChanges, VSTREELISTITEMCHANGE[] prgListChanges) => VSConstants.E_FAIL; public int GetText(uint index, VSTREETEXTOPTIONS tto, out string ppszText) => Changes[index].GetText(out _, out ppszText); public int GetTipText(uint index, VSTREETOOLTIPTYPE eTipType, out string ppszText) => Changes[index].GetTipText(out _, out ppszText); public int LocateExpandedList(IVsLiteTreeList child, out uint iIndex) { for (var i = 0; i < Changes.Length; i++) { if (Changes[i].GetChildren() == child) { iIndex = (uint)i; return VSConstants.S_OK; } } iIndex = 0; return VSConstants.S_FALSE; } public int OnClose(VSTREECLOSEACTIONS[] ptca) => VSConstants.S_OK; public int OnRequestSource(uint index, object pIUnknownTextView) => Changes[index].OnRequestSource(pIUnknownTextView); public int ToggleState(uint index, out uint ptscr) { Changes[index].Toggle(); ptscr = (uint)_VSTREESTATECHANGEREFRESH.TSCR_ENTIRE; Changes[index].OnRequestSource(null); return VSConstants.S_OK; } public int UpdateCounter(out uint pCurUpdate, out uint pgrfChanges) { pCurUpdate = 0; pgrfChanges = 0; return VSConstants.S_OK; } } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Workspaces/CSharpTest/Formatting/FormattingTreeEditTests.cs
// 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. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting { public class FormattingTreeEditTests : CSharpFormattingTestBase { private static Document GetDocument(string code) { var ws = new AdhocWorkspace(); var project = ws.AddProject("project", LanguageNames.CSharp); return project.AddDocument("code", SourceText.From(code)); } [Fact] public async Task SpaceAfterAttribute() { var code = @" public class C { void M(int? p) { } } "; var document = GetDocument(code); var g = SyntaxGenerator.GetGenerator(document); var root = await document.GetSyntaxRootAsync(); var attr = g.Attribute("MyAttr"); var param = root.DescendantNodes().OfType<ParameterSyntax>().First(); Assert.Equal(@" public class C { void M([MyAttr] int? p) { } } ", Formatter.Format(root.ReplaceNode(param, g.AddAttributes(param, g.Attribute("MyAttr"))), document.Project.Solution.Workspace).ToFullString()); // verify change doesn't affect how attributes appear before other kinds of declarations var method = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First(); Assert.Equal(@" public class C { [MyAttr] void M(int? p) { } } ", Formatter.Format(root.ReplaceNode(method, g.AddAttributes(method, g.Attribute("MyAttr"))), document.Project.Solution.Workspace).ToFullString()); } } }
// 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. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting { public class FormattingTreeEditTests : CSharpFormattingTestBase { private static Document GetDocument(string code) { var ws = new AdhocWorkspace(); var project = ws.AddProject("project", LanguageNames.CSharp); return project.AddDocument("code", SourceText.From(code)); } [Fact] public async Task SpaceAfterAttribute() { var code = @" public class C { void M(int? p) { } } "; var document = GetDocument(code); var g = SyntaxGenerator.GetGenerator(document); var root = await document.GetSyntaxRootAsync(); var attr = g.Attribute("MyAttr"); var param = root.DescendantNodes().OfType<ParameterSyntax>().First(); Assert.Equal(@" public class C { void M([MyAttr] int? p) { } } ", Formatter.Format(root.ReplaceNode(param, g.AddAttributes(param, g.Attribute("MyAttr"))), document.Project.Solution.Workspace).ToFullString()); // verify change doesn't affect how attributes appear before other kinds of declarations var method = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First(); Assert.Equal(@" public class C { [MyAttr] void M(int? p) { } } ", Formatter.Format(root.ReplaceNode(method, g.AddAttributes(method, g.Attribute("MyAttr"))), document.Project.Solution.Workspace).ToFullString()); } } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Compilers/Core/Portable/Emit/DebugDocumentsBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Emit { internal sealed class DebugDocumentsBuilder { // This is a map from the document "name" to the document. // Document "name" is typically a file path like "C:\Abc\Def.cs". However, that is not guaranteed. // For compatibility reasons the names are treated as case-sensitive in C# and case-insensitive in VB. // Neither language trims the names, so they are both sensitive to the leading and trailing whitespaces. // NOTE: We are not considering how filesystem or debuggers do the comparisons, but how native implementations did. // Deviating from that may result in unexpected warnings or different behavior (possibly without warnings). private readonly ConcurrentDictionary<string, Cci.DebugSourceDocument> _debugDocuments; private readonly ConcurrentCache<(string, string?), string> _normalizedPathsCache; private readonly SourceReferenceResolver? _resolver; public DebugDocumentsBuilder(SourceReferenceResolver? resolver, bool isDocumentNameCaseSensitive) { _resolver = resolver; _debugDocuments = new ConcurrentDictionary<string, Cci.DebugSourceDocument>( isDocumentNameCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase); _normalizedPathsCache = new ConcurrentCache<(string, string?), string>(16); } internal int DebugDocumentCount => _debugDocuments.Count; internal void AddDebugDocument(Cci.DebugSourceDocument document) { _debugDocuments.Add(document.Location, document); } internal IReadOnlyDictionary<string, Cci.DebugSourceDocument> DebugDocuments => _debugDocuments; internal Cci.DebugSourceDocument? TryGetDebugDocument(string path, string basePath) { return TryGetDebugDocumentForNormalizedPath(NormalizeDebugDocumentPath(path, basePath)); } internal Cci.DebugSourceDocument? TryGetDebugDocumentForNormalizedPath(string normalizedPath) { Cci.DebugSourceDocument? document; _debugDocuments.TryGetValue(normalizedPath, out document); return document; } internal Cci.DebugSourceDocument GetOrAddDebugDocument(string path, string basePath, Func<string, Cci.DebugSourceDocument> factory) { return _debugDocuments.GetOrAdd(NormalizeDebugDocumentPath(path, basePath), factory); } internal string NormalizeDebugDocumentPath(string path, string? basePath) { if (_resolver == null) { return path; } var key = (path, basePath); string? normalizedPath; if (!_normalizedPathsCache.TryGetValue(key, out normalizedPath)) { normalizedPath = _resolver.NormalizePath(path, basePath) ?? path; _normalizedPathsCache.TryAdd(key, normalizedPath); } return normalizedPath; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Emit { internal sealed class DebugDocumentsBuilder { // This is a map from the document "name" to the document. // Document "name" is typically a file path like "C:\Abc\Def.cs". However, that is not guaranteed. // For compatibility reasons the names are treated as case-sensitive in C# and case-insensitive in VB. // Neither language trims the names, so they are both sensitive to the leading and trailing whitespaces. // NOTE: We are not considering how filesystem or debuggers do the comparisons, but how native implementations did. // Deviating from that may result in unexpected warnings or different behavior (possibly without warnings). private readonly ConcurrentDictionary<string, Cci.DebugSourceDocument> _debugDocuments; private readonly ConcurrentCache<(string, string?), string> _normalizedPathsCache; private readonly SourceReferenceResolver? _resolver; public DebugDocumentsBuilder(SourceReferenceResolver? resolver, bool isDocumentNameCaseSensitive) { _resolver = resolver; _debugDocuments = new ConcurrentDictionary<string, Cci.DebugSourceDocument>( isDocumentNameCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase); _normalizedPathsCache = new ConcurrentCache<(string, string?), string>(16); } internal int DebugDocumentCount => _debugDocuments.Count; internal void AddDebugDocument(Cci.DebugSourceDocument document) { _debugDocuments.Add(document.Location, document); } internal IReadOnlyDictionary<string, Cci.DebugSourceDocument> DebugDocuments => _debugDocuments; internal Cci.DebugSourceDocument? TryGetDebugDocument(string path, string basePath) { return TryGetDebugDocumentForNormalizedPath(NormalizeDebugDocumentPath(path, basePath)); } internal Cci.DebugSourceDocument? TryGetDebugDocumentForNormalizedPath(string normalizedPath) { Cci.DebugSourceDocument? document; _debugDocuments.TryGetValue(normalizedPath, out document); return document; } internal Cci.DebugSourceDocument GetOrAddDebugDocument(string path, string basePath, Func<string, Cci.DebugSourceDocument> factory) { return _debugDocuments.GetOrAdd(NormalizeDebugDocumentPath(path, basePath), factory); } internal string NormalizeDebugDocumentPath(string path, string? basePath) { if (_resolver == null) { return path; } var key = (path, basePath); string? normalizedPath; if (!_normalizedPathsCache.TryGetValue(key, out normalizedPath)) { normalizedPath = _resolver.NormalizePath(path, basePath) ?? path; _normalizedPathsCache.TryAdd(key, normalizedPath); } return normalizedPath; } } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Analyzers/CSharp/Tests/UseCollectionInitializer/UseCollectionInitializerTests.cs
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseCollectionInitializer; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCollectionInitializer { public partial class UseCollectionInitializerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseCollectionInitializerTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseCollectionInitializerDiagnosticAnalyzer(), new CSharpUseCollectionInitializerCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestOnVariableDeclarator() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); } }", @"using System.Collections.Generic; class C { void M() { var c = new List<int> { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess1() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess1_NotInCSharp5() { await TestMissingAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; } }", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestComplexIndexAccess1() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { a.b.c = [||]new List<int>(); a.b.c[1] = 2; } }", @" using System.Collections.Generic; class C { void M() { a.b.c = new List<int> { [1] = 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess2() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; c[2] = """"; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2, [2] = """" }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess3() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; c[2] = """"; c[3, 4] = 5; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2, [2] = """", [3, 4] = 5 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexFollowedByInvocation() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; c.Add(0); } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2 }; c.Add(0); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestInvocationFollowedByIndex() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(0); c[1] = 2; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { 0 }; c[1] = 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestWithInterimStatement() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); c.Add(2); throw new Exception(); c.Add(3); c.Add(4); } }", @"using System.Collections.Generic; class C { void M() { var c = new List<int> { 1, 2 }; throw new Exception(); c.Add(3); c.Add(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingBeforeCSharp3() { await TestMissingAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); } }", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp2))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingOnNonIEnumerable() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new C(); c.Add(1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingOnNonIEnumerableEvenWithAdd() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new C(); c.Add(1); } public void Add(int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestWithCreationArguments() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(1); c.Add(1); } }", @"using System.Collections.Generic; class C { void M() { var c = new List<int>(1) { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestOnAssignmentExpression() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { List<int> c = null; c = [||]new List<int>(); c.Add(1); } }", @"using System.Collections.Generic; class C { void M() { List<int> c = null; c = new List<int> { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingOnRefAdd() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(ref i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestComplexInitializer() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = [||]new List<int>(); array[0].Add(1); array[0].Add(2); } }", @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = new List<int> { 1, 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestNotOnNamedArg() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(arg: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingWithExistingInitializer() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>() { 1 }; c.Add(1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestFixAllInDocument1() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = {|FixAllInDocument:new|} List<int>(); array[0].Add(1); array[0].Add(2); array[1] = new List<int>(); array[1].Add(3); array[1].Add(4); } }", @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = new List<int> { 1, 2 }; array[1] = new List<int> { 3, 4 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestFixAllInDocument2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var list1 = {|FixAllInDocument:new|} List<int>(() => { var list2 = new List<int>(); list2.Add(2); }); list1.Add(1); } }", @"using System.Collections.Generic; class C { void M() { var list1 = new List<int>(() => { var list2 = new List<int> { 2 }; }) { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestFixAllInDocument3() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var list1 = {|FixAllInDocument:new|} List<int>(); list1.Add(() => { var list2 = new List<int>(); list2.Add(2); }); } }", @"using System.Collections.Generic; class C { void M() { var list1 = new List<int> { () => { var list2 = new List<int> { 2 }; } }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestTrivia1() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); // Goo c.Add(2); // Bar } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { 1, // Goo 2 // Bar }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestComplexInitializer2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = new [||]Dictionary<int, string>(); c.Add(1, ""x""); c.Add(2, ""y""); } }", @"using System.Collections.Generic; class C { void M() { var c = new Dictionary<int, string> { { 1, ""x"" }, { 2, ""y"" } }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(16158, "https://github.com/dotnet/roslyn/issues/16158")] public async Task TestIncorrectAddName() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; public class Goo { public static void Bar() { string item = null; var items = new List<string>(); var values = new [||]List<string>(); // Collection initialization can be simplified values.Add(item); values.AddRange(items); } }", @"using System.Collections.Generic; public class Goo { public static void Bar() { string item = null; var items = new List<string>(); var values = new List<string> { item }; // Collection initialization can be simplified values.AddRange(items); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(16241, "https://github.com/dotnet/roslyn/issues/16241")] public async Task TestNestedCollectionInitializer() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var myStringArray = new string[] { ""Test"", ""123"", ""ABC"" }; var myStringList = myStringArray?.ToList() ?? new [||]List<string>(); myStringList.Add(""Done""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")] public async Task TestMissingWhenReferencedInInitializer() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; class C { static void M() { var items = new [||]List<object>(); items[0] = items[0]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")] public async Task TestWhenReferencedInInitializer_LocalVar() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { static void M() { var items = new [||]List<object>(); items[0] = 1; items[1] = items[0]; } }", @" using System.Collections.Generic; class C { static void M() { var items = new [||]List<object> { [0] = 1 }; items[1] = items[0]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")] public async Task TestWhenReferencedInInitializer_LocalVar2() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; using System.Linq; class C { void M() { var t = [||]new List<int>(new int[] { 1, 2, 3 }); t.Add(t.Min() - 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")] public async Task TestWhenReferencedInInitializer_Assignment() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { static void M() { List<object> items = null; items = new [||]List<object>(); items[0] = 1; items[1] = items[0]; } }", @" using System.Collections.Generic; class C { static void M() { List<object> items = null; items = new [||]List<object> { [0] = 1 }; items[1] = items[0]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")] public async Task TestWhenReferencedInInitializer_Assignment2() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { List<int> t = null; t = [||]new List<int>(new int[] { 1, 2, 3 }); t.Add(t.Min() - 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")] public async Task TestFieldReference() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { private List<int> myField; void M() { myField = [||]new List<int>(); myField.Add(this.myField.Count); } }"); } [WorkItem(17853, "https://github.com/dotnet/roslyn/issues/17853")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingForDynamic() { await TestMissingInRegularAndScriptAsync( @"using System.Dynamic; class C { void Goo() { dynamic body = [||]new ExpandoObject(); body[0] = new ExpandoObject(); } }"); } [WorkItem(17953, "https://github.com/dotnet/roslyn/issues/17953")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingAcrossPreprocessorDirective() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; public class Goo { public void M() { var items = new [||]List<object>(); #if true items.Add(1); #endif } }"); } [WorkItem(17953, "https://github.com/dotnet/roslyn/issues/17953")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestAvailableInsidePreprocessorDirective() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; public class Goo { public void M() { #if true var items = new [||]List<object>(); items.Add(1); #endif } }", @" using System.Collections.Generic; public class Goo { public void M() { #if true var items = new List<object> { 1 }; #endif } }"); } [WorkItem(18242, "https://github.com/dotnet/roslyn/issues/18242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestObjectInitializerAssignmentAmbiguity() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; public class Goo { public void M() { int lastItem; var list = [||]new List<int>(); list.Add(lastItem = 5); } }", @" using System.Collections.Generic; public class Goo { public void M() { int lastItem; var list = new List<int> { (lastItem = 5) }; } }"); } [WorkItem(18242, "https://github.com/dotnet/roslyn/issues/18242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestObjectInitializerCompoundAssignment() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; public class Goo { public void M() { int lastItem = 0; var list = [||]new List<int>(); list.Add(lastItem += 5); } }", @" using System.Collections.Generic; public class Goo { public void M() { int lastItem = 0; var list = new List<int> { (lastItem += 5) }; } }"); } [WorkItem(19253, "https://github.com/dotnet/roslyn/issues/19253")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestKeepBlankLinesAfter() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class MyClass { public void Main() { var list = [||]new List<int>(); list.Add(1); int horse = 1; } }", @" using System.Collections.Generic; class MyClass { public void Main() { var list = new List<int> { 1 }; int horse = 1; } }"); } [WorkItem(23672, "https://github.com/dotnet/roslyn/issues/23672")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingWithExplicitImplementedAddMethod() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; using System.Dynamic; public class Goo { public void M() { IDictionary<string, object> obj = [||]new ExpandoObject(); obj.Add(""string"", ""v""); obj.Add(""int"", 1); obj.Add("" object"", new { X = 1, Y = 2 }); } }"); } } }
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseCollectionInitializer; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCollectionInitializer { public partial class UseCollectionInitializerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseCollectionInitializerTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseCollectionInitializerDiagnosticAnalyzer(), new CSharpUseCollectionInitializerCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestOnVariableDeclarator() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); } }", @"using System.Collections.Generic; class C { void M() { var c = new List<int> { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess1() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess1_NotInCSharp5() { await TestMissingAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; } }", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestComplexIndexAccess1() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { a.b.c = [||]new List<int>(); a.b.c[1] = 2; } }", @" using System.Collections.Generic; class C { void M() { a.b.c = new List<int> { [1] = 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess2() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; c[2] = """"; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2, [2] = """" }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess3() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; c[2] = """"; c[3, 4] = 5; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2, [2] = """", [3, 4] = 5 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexFollowedByInvocation() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; c.Add(0); } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2 }; c.Add(0); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestInvocationFollowedByIndex() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(0); c[1] = 2; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { 0 }; c[1] = 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestWithInterimStatement() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); c.Add(2); throw new Exception(); c.Add(3); c.Add(4); } }", @"using System.Collections.Generic; class C { void M() { var c = new List<int> { 1, 2 }; throw new Exception(); c.Add(3); c.Add(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingBeforeCSharp3() { await TestMissingAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); } }", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp2))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingOnNonIEnumerable() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new C(); c.Add(1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingOnNonIEnumerableEvenWithAdd() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new C(); c.Add(1); } public void Add(int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestWithCreationArguments() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(1); c.Add(1); } }", @"using System.Collections.Generic; class C { void M() { var c = new List<int>(1) { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestOnAssignmentExpression() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { List<int> c = null; c = [||]new List<int>(); c.Add(1); } }", @"using System.Collections.Generic; class C { void M() { List<int> c = null; c = new List<int> { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingOnRefAdd() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(ref i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestComplexInitializer() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = [||]new List<int>(); array[0].Add(1); array[0].Add(2); } }", @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = new List<int> { 1, 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestNotOnNamedArg() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(arg: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingWithExistingInitializer() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>() { 1 }; c.Add(1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestFixAllInDocument1() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = {|FixAllInDocument:new|} List<int>(); array[0].Add(1); array[0].Add(2); array[1] = new List<int>(); array[1].Add(3); array[1].Add(4); } }", @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = new List<int> { 1, 2 }; array[1] = new List<int> { 3, 4 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestFixAllInDocument2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var list1 = {|FixAllInDocument:new|} List<int>(() => { var list2 = new List<int>(); list2.Add(2); }); list1.Add(1); } }", @"using System.Collections.Generic; class C { void M() { var list1 = new List<int>(() => { var list2 = new List<int> { 2 }; }) { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestFixAllInDocument3() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var list1 = {|FixAllInDocument:new|} List<int>(); list1.Add(() => { var list2 = new List<int>(); list2.Add(2); }); } }", @"using System.Collections.Generic; class C { void M() { var list1 = new List<int> { () => { var list2 = new List<int> { 2 }; } }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestTrivia1() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); // Goo c.Add(2); // Bar } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { 1, // Goo 2 // Bar }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestComplexInitializer2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = new [||]Dictionary<int, string>(); c.Add(1, ""x""); c.Add(2, ""y""); } }", @"using System.Collections.Generic; class C { void M() { var c = new Dictionary<int, string> { { 1, ""x"" }, { 2, ""y"" } }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(16158, "https://github.com/dotnet/roslyn/issues/16158")] public async Task TestIncorrectAddName() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; public class Goo { public static void Bar() { string item = null; var items = new List<string>(); var values = new [||]List<string>(); // Collection initialization can be simplified values.Add(item); values.AddRange(items); } }", @"using System.Collections.Generic; public class Goo { public static void Bar() { string item = null; var items = new List<string>(); var values = new List<string> { item }; // Collection initialization can be simplified values.AddRange(items); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(16241, "https://github.com/dotnet/roslyn/issues/16241")] public async Task TestNestedCollectionInitializer() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var myStringArray = new string[] { ""Test"", ""123"", ""ABC"" }; var myStringList = myStringArray?.ToList() ?? new [||]List<string>(); myStringList.Add(""Done""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")] public async Task TestMissingWhenReferencedInInitializer() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; class C { static void M() { var items = new [||]List<object>(); items[0] = items[0]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")] public async Task TestWhenReferencedInInitializer_LocalVar() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { static void M() { var items = new [||]List<object>(); items[0] = 1; items[1] = items[0]; } }", @" using System.Collections.Generic; class C { static void M() { var items = new [||]List<object> { [0] = 1 }; items[1] = items[0]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")] public async Task TestWhenReferencedInInitializer_LocalVar2() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; using System.Linq; class C { void M() { var t = [||]new List<int>(new int[] { 1, 2, 3 }); t.Add(t.Min() - 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")] public async Task TestWhenReferencedInInitializer_Assignment() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { static void M() { List<object> items = null; items = new [||]List<object>(); items[0] = 1; items[1] = items[0]; } }", @" using System.Collections.Generic; class C { static void M() { List<object> items = null; items = new [||]List<object> { [0] = 1 }; items[1] = items[0]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")] public async Task TestWhenReferencedInInitializer_Assignment2() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { List<int> t = null; t = [||]new List<int>(new int[] { 1, 2, 3 }); t.Add(t.Min() - 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")] public async Task TestFieldReference() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { private List<int> myField; void M() { myField = [||]new List<int>(); myField.Add(this.myField.Count); } }"); } [WorkItem(17853, "https://github.com/dotnet/roslyn/issues/17853")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingForDynamic() { await TestMissingInRegularAndScriptAsync( @"using System.Dynamic; class C { void Goo() { dynamic body = [||]new ExpandoObject(); body[0] = new ExpandoObject(); } }"); } [WorkItem(17953, "https://github.com/dotnet/roslyn/issues/17953")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingAcrossPreprocessorDirective() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; public class Goo { public void M() { var items = new [||]List<object>(); #if true items.Add(1); #endif } }"); } [WorkItem(17953, "https://github.com/dotnet/roslyn/issues/17953")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestAvailableInsidePreprocessorDirective() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; public class Goo { public void M() { #if true var items = new [||]List<object>(); items.Add(1); #endif } }", @" using System.Collections.Generic; public class Goo { public void M() { #if true var items = new List<object> { 1 }; #endif } }"); } [WorkItem(18242, "https://github.com/dotnet/roslyn/issues/18242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestObjectInitializerAssignmentAmbiguity() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; public class Goo { public void M() { int lastItem; var list = [||]new List<int>(); list.Add(lastItem = 5); } }", @" using System.Collections.Generic; public class Goo { public void M() { int lastItem; var list = new List<int> { (lastItem = 5) }; } }"); } [WorkItem(18242, "https://github.com/dotnet/roslyn/issues/18242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestObjectInitializerCompoundAssignment() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; public class Goo { public void M() { int lastItem = 0; var list = [||]new List<int>(); list.Add(lastItem += 5); } }", @" using System.Collections.Generic; public class Goo { public void M() { int lastItem = 0; var list = new List<int> { (lastItem += 5) }; } }"); } [WorkItem(19253, "https://github.com/dotnet/roslyn/issues/19253")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestKeepBlankLinesAfter() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class MyClass { public void Main() { var list = [||]new List<int>(); list.Add(1); int horse = 1; } }", @" using System.Collections.Generic; class MyClass { public void Main() { var list = new List<int> { 1 }; int horse = 1; } }"); } [WorkItem(23672, "https://github.com/dotnet/roslyn/issues/23672")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingWithExplicitImplementedAddMethod() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; using System.Dynamic; public class Goo { public void M() { IDictionary<string, object> obj = [||]new ExpandoObject(); obj.Add(""string"", ""v""); obj.Add(""int"", 1); obj.Add("" object"", new { X = 1, Y = 2 }); } }"); } } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/EditorFeatures/CSharpTest2/Recommendations/DefineKeywordRecommenderTests.cs
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class DefineKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNestedPreprocessor() { await VerifyKeywordAsync( @"#if true #$$ #endif"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeUsing() { await VerifyKeywordAsync( @"#$$ using System;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeGlobalUsing() { await VerifyKeywordAsync( @"#$$ global using System;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUsing() { await VerifyAbsenceAsync( @"using System; #$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalUsing() { await VerifyAbsenceAsync( @"global using System; #$$"); } } }
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class DefineKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNestedPreprocessor() { await VerifyKeywordAsync( @"#if true #$$ #endif"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeUsing() { await VerifyKeywordAsync( @"#$$ using System;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeGlobalUsing() { await VerifyKeywordAsync( @"#$$ global using System;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUsing() { await VerifyAbsenceAsync( @"using System; #$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalUsing() { await VerifyAbsenceAsync( @"global using System; #$$"); } } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/EditorFeatures/CSharpTest2/Recommendations/OrderByKeywordRecommenderTests.cs
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class OrderByKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtEndOfPreviousClause() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNewClause() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousClause() { await VerifyKeywordAsync(AddInsideMethod( @"var v = from x in y where x > y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousContinuationClause() { await VerifyKeywordAsync(AddInsideMethod( @"var v = from x in y group x by y into g $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBetweenClauses() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y $$ from z in w")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterOrderBy() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y orderby $$")); } } }
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class OrderByKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtEndOfPreviousClause() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNewClause() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousClause() { await VerifyKeywordAsync(AddInsideMethod( @"var v = from x in y where x > y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousContinuationClause() { await VerifyKeywordAsync(AddInsideMethod( @"var v = from x in y group x by y into g $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBetweenClauses() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y $$ from z in w")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterOrderBy() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y orderby $$")); } } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Workspaces/MSBuildTest/Resources/NuGet.Config
<?xml version="1.0" encoding="utf-8"?> <configuration> <!-- Provide a default package restore source for test projects. --> <packageRestore> <add key="enabled" value="true" /> </packageRestore> <packageSources> <clear /> <add key="api.nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" /> </packageSources> </configuration>
<?xml version="1.0" encoding="utf-8"?> <configuration> <!-- Provide a default package restore source for test projects. --> <packageRestore> <add key="enabled" value="true" /> </packageRestore> <packageSources> <clear /> <add key="api.nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" /> </packageSources> </configuration>
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Workspaces/CoreTest/SolutionTests/ProjectInfoTests.cs
// 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. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class ProjectInfoTests { [Fact] public void Create_Errors_NullReferences() { var pid = ProjectId.CreateNewId(); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(id: null, version: VersionStamp.Default, name: "Goo", assemblyName: "Bar", language: "C#")); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(pid, VersionStamp.Default, name: null, assemblyName: "Bar", language: "C#")); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(pid, VersionStamp.Default, name: "Goo", assemblyName: null, language: "C#")); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(pid, VersionStamp.Default, name: "Goo", assemblyName: "Bar", language: null)); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(pid, VersionStamp.Default, name: "Goo", assemblyName: "Bar", language: "C#", documents: new DocumentInfo[] { null })); } [Fact] public void Create_Errors_DuplicateItems() { var pid = ProjectId.CreateNewId(); var documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "doc"); Assert.Throws<ArgumentException>("documents[1]", () => ProjectInfo.Create(pid, VersionStamp.Default, "proj", "assembly", "C#", documents: new[] { documentInfo, documentInfo })); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(pid, VersionStamp.Default, name: "Goo", assemblyName: "Bar", language: "C#", additionalDocuments: new DocumentInfo[] { null })); Assert.Throws<ArgumentException>("additionalDocuments[1]", () => ProjectInfo.Create(pid, VersionStamp.Default, "proj", "assembly", "C#", additionalDocuments: new[] { documentInfo, documentInfo })); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(pid, VersionStamp.Default, name: "Goo", assemblyName: "Bar", language: "C#", projectReferences: new ProjectReference[] { null })); var projectReference = new ProjectReference(ProjectId.CreateNewId()); Assert.Throws<ArgumentException>("projectReferences[1]", () => ProjectInfo.Create(pid, VersionStamp.Default, "proj", "assembly", "C#", projectReferences: new[] { projectReference, projectReference })); Assert.Throws<ArgumentNullException>("analyzerReferences[0]", () => ProjectInfo.Create(pid, VersionStamp.Default, name: "Goo", assemblyName: "Bar", language: "C#", analyzerReferences: new AnalyzerReference[] { null })); var analyzerReference = new TestAnalyzerReference(); Assert.Throws<ArgumentException>("analyzerReferences[1]", () => ProjectInfo.Create(pid, VersionStamp.Default, "proj", "assembly", "C#", analyzerReferences: new[] { analyzerReference, analyzerReference })); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(pid, VersionStamp.Default, name: "Goo", assemblyName: "Bar", language: "C#", metadataReferences: new MetadataReference[] { null })); var metadataReference = new TestMetadataReference(); Assert.Throws<ArgumentException>("metadataReferences[1]", () => ProjectInfo.Create(pid, VersionStamp.Default, "proj", "assembly", "C#", metadataReferences: new[] { metadataReference, metadataReference })); } [Fact] public void Create_Documents() { var version = VersionStamp.Default; var documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(ProjectId.CreateNewId()), "doc"); var info1 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", documents: new[] { documentInfo }); Assert.Same(documentInfo, ((ImmutableArray<DocumentInfo>)info1.Documents).Single()); var info2 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#"); Assert.True(((ImmutableArray<DocumentInfo>)info2.Documents).IsEmpty); var info3 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", documents: new DocumentInfo[0]); Assert.True(((ImmutableArray<DocumentInfo>)info3.Documents).IsEmpty); var info4 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", documents: ImmutableArray<DocumentInfo>.Empty); Assert.True(((ImmutableArray<DocumentInfo>)info4.Documents).IsEmpty); } [Fact] public void Create_AdditionalDocuments() { var version = VersionStamp.Default; var documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(ProjectId.CreateNewId()), "doc"); var info1 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", additionalDocuments: new[] { documentInfo }); Assert.Same(documentInfo, ((ImmutableArray<DocumentInfo>)info1.AdditionalDocuments).Single()); var info2 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#"); Assert.True(((ImmutableArray<DocumentInfo>)info2.AdditionalDocuments).IsEmpty); var info3 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", additionalDocuments: new DocumentInfo[0]); Assert.True(((ImmutableArray<DocumentInfo>)info3.AdditionalDocuments).IsEmpty); var info4 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", additionalDocuments: ImmutableArray<DocumentInfo>.Empty); Assert.True(((ImmutableArray<DocumentInfo>)info4.AdditionalDocuments).IsEmpty); } [Fact] public void Create_ProjectReferences() { var version = VersionStamp.Default; var projectReference = new ProjectReference(ProjectId.CreateNewId()); var info1 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", projectReferences: new[] { projectReference }); Assert.Same(projectReference, ((ImmutableArray<ProjectReference>)info1.ProjectReferences).Single()); var info2 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#"); Assert.True(((ImmutableArray<ProjectReference>)info2.ProjectReferences).IsEmpty); var info3 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", projectReferences: new ProjectReference[0]); Assert.True(((ImmutableArray<ProjectReference>)info3.ProjectReferences).IsEmpty); var info4 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", projectReferences: ImmutableArray<ProjectReference>.Empty); Assert.True(((ImmutableArray<ProjectReference>)info4.ProjectReferences).IsEmpty); } [Fact] public void Create_MetadataReferences() { var version = VersionStamp.Default; var metadataReference = new TestMetadataReference(); var info1 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", metadataReferences: new[] { metadataReference }); Assert.Same(metadataReference, ((ImmutableArray<MetadataReference>)info1.MetadataReferences).Single()); var info2 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#"); Assert.True(((ImmutableArray<MetadataReference>)info2.MetadataReferences).IsEmpty); var info3 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", metadataReferences: new MetadataReference[0]); Assert.True(((ImmutableArray<MetadataReference>)info3.MetadataReferences).IsEmpty); var info4 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", metadataReferences: ImmutableArray<MetadataReference>.Empty); Assert.True(((ImmutableArray<MetadataReference>)info4.MetadataReferences).IsEmpty); } [Fact] public void Create_AnalyzerReferences() { var version = VersionStamp.Default; var analyzerReference = new TestAnalyzerReference(); var info1 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", analyzerReferences: new[] { analyzerReference }); Assert.Same(analyzerReference, ((ImmutableArray<AnalyzerReference>)info1.AnalyzerReferences).Single()); var info2 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#"); Assert.True(((ImmutableArray<AnalyzerReference>)info2.AnalyzerReferences).IsEmpty); var info3 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", analyzerReferences: new AnalyzerReference[0]); Assert.True(((ImmutableArray<AnalyzerReference>)info3.AnalyzerReferences).IsEmpty); var info4 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", analyzerReferences: ImmutableArray<AnalyzerReference>.Empty); Assert.True(((ImmutableArray<AnalyzerReference>)info4.AnalyzerReferences).IsEmpty); } [Fact] public void DebuggerDisplayHasProjectNameAndFilePath() { var projectInfo = ProjectInfo.Create(name: "Goo", filePath: @"C:\", id: ProjectId.CreateNewId(), version: VersionStamp.Default, assemblyName: "Bar", language: "C#"); Assert.Equal(@"ProjectInfo Goo C:\", projectInfo.GetDebuggerDisplay()); } [Fact] public void DebuggerDisplayHasOnlyProjectNameWhenFilePathNotSpecified() { var projectInfo = ProjectInfo.Create(name: "Goo", id: ProjectId.CreateNewId(), version: VersionStamp.Default, assemblyName: "Bar", language: "C#"); Assert.Equal(@"ProjectInfo Goo", projectInfo.GetDebuggerDisplay()); } [Fact] public void TestProperties() { var projectId = ProjectId.CreateNewId(); var documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "doc"); var instance = ProjectInfo.Create(name: "Name", id: ProjectId.CreateNewId(), version: VersionStamp.Default, assemblyName: "AssemblyName", language: "C#"); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithVersion(value), opt => opt.Version, VersionStamp.Create()); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithName(value), opt => opt.Name, "New", defaultThrows: true); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithAssemblyName(value), opt => opt.AssemblyName, "New", defaultThrows: true); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithFilePath(value), opt => opt.FilePath, "New"); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithOutputFilePath(value), opt => opt.OutputFilePath, "New"); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithOutputRefFilePath(value), opt => opt.OutputRefFilePath, "New"); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithCompilationOutputInfo(value), opt => opt.CompilationOutputInfo, new CompilationOutputInfo("NewPath")); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithDefaultNamespace(value), opt => opt.DefaultNamespace, "New"); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithHasAllInformation(value), opt => opt.HasAllInformation, true); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithRunAnalyzers(value), opt => opt.RunAnalyzers, true); SolutionTestHelpers.TestListProperty(instance, (old, value) => old.WithDocuments(value), opt => opt.Documents, documentInfo, allowDuplicates: false); SolutionTestHelpers.TestListProperty(instance, (old, value) => old.WithAdditionalDocuments(value), opt => opt.AdditionalDocuments, documentInfo, allowDuplicates: false); SolutionTestHelpers.TestListProperty(instance, (old, value) => old.WithAnalyzerConfigDocuments(value), opt => opt.AnalyzerConfigDocuments, documentInfo, allowDuplicates: false); SolutionTestHelpers.TestListProperty(instance, (old, value) => old.WithAnalyzerReferences(value), opt => opt.AnalyzerReferences, (AnalyzerReference)new TestAnalyzerReference(), allowDuplicates: false); SolutionTestHelpers.TestListProperty(instance, (old, value) => old.WithMetadataReferences(value), opt => opt.MetadataReferences, (MetadataReference)new TestMetadataReference(), allowDuplicates: false); SolutionTestHelpers.TestListProperty(instance, (old, value) => old.WithProjectReferences(value), opt => opt.ProjectReferences, new ProjectReference(projectId), allowDuplicates: false); } } }
// 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. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class ProjectInfoTests { [Fact] public void Create_Errors_NullReferences() { var pid = ProjectId.CreateNewId(); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(id: null, version: VersionStamp.Default, name: "Goo", assemblyName: "Bar", language: "C#")); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(pid, VersionStamp.Default, name: null, assemblyName: "Bar", language: "C#")); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(pid, VersionStamp.Default, name: "Goo", assemblyName: null, language: "C#")); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(pid, VersionStamp.Default, name: "Goo", assemblyName: "Bar", language: null)); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(pid, VersionStamp.Default, name: "Goo", assemblyName: "Bar", language: "C#", documents: new DocumentInfo[] { null })); } [Fact] public void Create_Errors_DuplicateItems() { var pid = ProjectId.CreateNewId(); var documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "doc"); Assert.Throws<ArgumentException>("documents[1]", () => ProjectInfo.Create(pid, VersionStamp.Default, "proj", "assembly", "C#", documents: new[] { documentInfo, documentInfo })); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(pid, VersionStamp.Default, name: "Goo", assemblyName: "Bar", language: "C#", additionalDocuments: new DocumentInfo[] { null })); Assert.Throws<ArgumentException>("additionalDocuments[1]", () => ProjectInfo.Create(pid, VersionStamp.Default, "proj", "assembly", "C#", additionalDocuments: new[] { documentInfo, documentInfo })); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(pid, VersionStamp.Default, name: "Goo", assemblyName: "Bar", language: "C#", projectReferences: new ProjectReference[] { null })); var projectReference = new ProjectReference(ProjectId.CreateNewId()); Assert.Throws<ArgumentException>("projectReferences[1]", () => ProjectInfo.Create(pid, VersionStamp.Default, "proj", "assembly", "C#", projectReferences: new[] { projectReference, projectReference })); Assert.Throws<ArgumentNullException>("analyzerReferences[0]", () => ProjectInfo.Create(pid, VersionStamp.Default, name: "Goo", assemblyName: "Bar", language: "C#", analyzerReferences: new AnalyzerReference[] { null })); var analyzerReference = new TestAnalyzerReference(); Assert.Throws<ArgumentException>("analyzerReferences[1]", () => ProjectInfo.Create(pid, VersionStamp.Default, "proj", "assembly", "C#", analyzerReferences: new[] { analyzerReference, analyzerReference })); Assert.Throws<ArgumentNullException>(() => ProjectInfo.Create(pid, VersionStamp.Default, name: "Goo", assemblyName: "Bar", language: "C#", metadataReferences: new MetadataReference[] { null })); var metadataReference = new TestMetadataReference(); Assert.Throws<ArgumentException>("metadataReferences[1]", () => ProjectInfo.Create(pid, VersionStamp.Default, "proj", "assembly", "C#", metadataReferences: new[] { metadataReference, metadataReference })); } [Fact] public void Create_Documents() { var version = VersionStamp.Default; var documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(ProjectId.CreateNewId()), "doc"); var info1 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", documents: new[] { documentInfo }); Assert.Same(documentInfo, ((ImmutableArray<DocumentInfo>)info1.Documents).Single()); var info2 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#"); Assert.True(((ImmutableArray<DocumentInfo>)info2.Documents).IsEmpty); var info3 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", documents: new DocumentInfo[0]); Assert.True(((ImmutableArray<DocumentInfo>)info3.Documents).IsEmpty); var info4 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", documents: ImmutableArray<DocumentInfo>.Empty); Assert.True(((ImmutableArray<DocumentInfo>)info4.Documents).IsEmpty); } [Fact] public void Create_AdditionalDocuments() { var version = VersionStamp.Default; var documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(ProjectId.CreateNewId()), "doc"); var info1 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", additionalDocuments: new[] { documentInfo }); Assert.Same(documentInfo, ((ImmutableArray<DocumentInfo>)info1.AdditionalDocuments).Single()); var info2 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#"); Assert.True(((ImmutableArray<DocumentInfo>)info2.AdditionalDocuments).IsEmpty); var info3 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", additionalDocuments: new DocumentInfo[0]); Assert.True(((ImmutableArray<DocumentInfo>)info3.AdditionalDocuments).IsEmpty); var info4 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", additionalDocuments: ImmutableArray<DocumentInfo>.Empty); Assert.True(((ImmutableArray<DocumentInfo>)info4.AdditionalDocuments).IsEmpty); } [Fact] public void Create_ProjectReferences() { var version = VersionStamp.Default; var projectReference = new ProjectReference(ProjectId.CreateNewId()); var info1 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", projectReferences: new[] { projectReference }); Assert.Same(projectReference, ((ImmutableArray<ProjectReference>)info1.ProjectReferences).Single()); var info2 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#"); Assert.True(((ImmutableArray<ProjectReference>)info2.ProjectReferences).IsEmpty); var info3 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", projectReferences: new ProjectReference[0]); Assert.True(((ImmutableArray<ProjectReference>)info3.ProjectReferences).IsEmpty); var info4 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", projectReferences: ImmutableArray<ProjectReference>.Empty); Assert.True(((ImmutableArray<ProjectReference>)info4.ProjectReferences).IsEmpty); } [Fact] public void Create_MetadataReferences() { var version = VersionStamp.Default; var metadataReference = new TestMetadataReference(); var info1 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", metadataReferences: new[] { metadataReference }); Assert.Same(metadataReference, ((ImmutableArray<MetadataReference>)info1.MetadataReferences).Single()); var info2 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#"); Assert.True(((ImmutableArray<MetadataReference>)info2.MetadataReferences).IsEmpty); var info3 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", metadataReferences: new MetadataReference[0]); Assert.True(((ImmutableArray<MetadataReference>)info3.MetadataReferences).IsEmpty); var info4 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", metadataReferences: ImmutableArray<MetadataReference>.Empty); Assert.True(((ImmutableArray<MetadataReference>)info4.MetadataReferences).IsEmpty); } [Fact] public void Create_AnalyzerReferences() { var version = VersionStamp.Default; var analyzerReference = new TestAnalyzerReference(); var info1 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", analyzerReferences: new[] { analyzerReference }); Assert.Same(analyzerReference, ((ImmutableArray<AnalyzerReference>)info1.AnalyzerReferences).Single()); var info2 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#"); Assert.True(((ImmutableArray<AnalyzerReference>)info2.AnalyzerReferences).IsEmpty); var info3 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", analyzerReferences: new AnalyzerReference[0]); Assert.True(((ImmutableArray<AnalyzerReference>)info3.AnalyzerReferences).IsEmpty); var info4 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", analyzerReferences: ImmutableArray<AnalyzerReference>.Empty); Assert.True(((ImmutableArray<AnalyzerReference>)info4.AnalyzerReferences).IsEmpty); } [Fact] public void DebuggerDisplayHasProjectNameAndFilePath() { var projectInfo = ProjectInfo.Create(name: "Goo", filePath: @"C:\", id: ProjectId.CreateNewId(), version: VersionStamp.Default, assemblyName: "Bar", language: "C#"); Assert.Equal(@"ProjectInfo Goo C:\", projectInfo.GetDebuggerDisplay()); } [Fact] public void DebuggerDisplayHasOnlyProjectNameWhenFilePathNotSpecified() { var projectInfo = ProjectInfo.Create(name: "Goo", id: ProjectId.CreateNewId(), version: VersionStamp.Default, assemblyName: "Bar", language: "C#"); Assert.Equal(@"ProjectInfo Goo", projectInfo.GetDebuggerDisplay()); } [Fact] public void TestProperties() { var projectId = ProjectId.CreateNewId(); var documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "doc"); var instance = ProjectInfo.Create(name: "Name", id: ProjectId.CreateNewId(), version: VersionStamp.Default, assemblyName: "AssemblyName", language: "C#"); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithVersion(value), opt => opt.Version, VersionStamp.Create()); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithName(value), opt => opt.Name, "New", defaultThrows: true); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithAssemblyName(value), opt => opt.AssemblyName, "New", defaultThrows: true); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithFilePath(value), opt => opt.FilePath, "New"); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithOutputFilePath(value), opt => opt.OutputFilePath, "New"); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithOutputRefFilePath(value), opt => opt.OutputRefFilePath, "New"); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithCompilationOutputInfo(value), opt => opt.CompilationOutputInfo, new CompilationOutputInfo("NewPath")); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithDefaultNamespace(value), opt => opt.DefaultNamespace, "New"); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithHasAllInformation(value), opt => opt.HasAllInformation, true); SolutionTestHelpers.TestProperty(instance, (old, value) => old.WithRunAnalyzers(value), opt => opt.RunAnalyzers, true); SolutionTestHelpers.TestListProperty(instance, (old, value) => old.WithDocuments(value), opt => opt.Documents, documentInfo, allowDuplicates: false); SolutionTestHelpers.TestListProperty(instance, (old, value) => old.WithAdditionalDocuments(value), opt => opt.AdditionalDocuments, documentInfo, allowDuplicates: false); SolutionTestHelpers.TestListProperty(instance, (old, value) => old.WithAnalyzerConfigDocuments(value), opt => opt.AnalyzerConfigDocuments, documentInfo, allowDuplicates: false); SolutionTestHelpers.TestListProperty(instance, (old, value) => old.WithAnalyzerReferences(value), opt => opt.AnalyzerReferences, (AnalyzerReference)new TestAnalyzerReference(), allowDuplicates: false); SolutionTestHelpers.TestListProperty(instance, (old, value) => old.WithMetadataReferences(value), opt => opt.MetadataReferences, (MetadataReference)new TestMetadataReference(), allowDuplicates: false); SolutionTestHelpers.TestListProperty(instance, (old, value) => old.WithProjectReferences(value), opt => opt.ProjectReferences, new ProjectReference(projectId), allowDuplicates: false); } } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Workspaces/Core/Portable/Simplification/AbstractReducer.IExpressionRewriter.cs
// 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. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Simplification { internal abstract partial class AbstractReducer { internal interface IReductionRewriter : IDisposable { void Initialize(ParseOptions parseOptions, OptionSet optionSet, CancellationToken cancellationToken); SyntaxNodeOrToken VisitNodeOrToken(SyntaxNodeOrToken nodeOrTokenToReduce, SemanticModel semanticModel, bool simplifyAllDescendants); bool HasMoreWork { get; } } } }
// 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. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Simplification { internal abstract partial class AbstractReducer { internal interface IReductionRewriter : IDisposable { void Initialize(ParseOptions parseOptions, OptionSet optionSet, CancellationToken cancellationToken); SyntaxNodeOrToken VisitNodeOrToken(SyntaxNodeOrToken nodeOrTokenToReduce, SemanticModel semanticModel, bool simplifyAllDescendants); bool HasMoreWork { get; } } } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Compilers/Core/Portable/Operations/CaptureId.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.FlowAnalysis { /// <summary> /// Capture Id is an opaque identifier to represent an intermediate result from an <see cref="IFlowCaptureOperation"/>. /// </summary> public struct CaptureId : IEquatable<CaptureId> { internal CaptureId(int value) { Debug.Assert(value >= 0); Value = value; } internal int Value { get; } /// <summary> /// Compares <see cref="CaptureId"/>s. /// </summary> public bool Equals(CaptureId other) => Value == other.Value; /// <inheritdoc/> public override bool Equals(object? obj) => obj is CaptureId && Equals((CaptureId)obj); /// <inheritdoc/> public override int GetHashCode() => Value.GetHashCode(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.FlowAnalysis { /// <summary> /// Capture Id is an opaque identifier to represent an intermediate result from an <see cref="IFlowCaptureOperation"/>. /// </summary> public struct CaptureId : IEquatable<CaptureId> { internal CaptureId(int value) { Debug.Assert(value >= 0); Value = value; } internal int Value { get; } /// <summary> /// Compares <see cref="CaptureId"/>s. /// </summary> public bool Equals(CaptureId other) => Value == other.Value; /// <inheritdoc/> public override bool Equals(object? obj) => obj is CaptureId && Equals((CaptureId)obj); /// <inheritdoc/> public override int GetHashCode() => Value.GetHashCode(); } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/EditorFeatures/CSharpTest2/Recommendations/HiddenKeywordRecommenderTests.cs
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class HiddenKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#line $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# line $$"); } } }
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class HiddenKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#line $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# line $$"); } } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Compilers/Core/Portable/SourceGeneration/Nodes/CombineNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis { internal sealed class CombineNode<TInput1, TInput2> : IIncrementalGeneratorNode<(TInput1, TInput2)> { private readonly IIncrementalGeneratorNode<TInput1> _input1; private readonly IIncrementalGeneratorNode<TInput2> _input2; private readonly IEqualityComparer<(TInput1, TInput2)>? _comparer; public CombineNode(IIncrementalGeneratorNode<TInput1> input1, IIncrementalGeneratorNode<TInput2> input2, IEqualityComparer<(TInput1, TInput2)>? comparer = null) { _input1 = input1; _input2 = input2; _comparer = comparer; } public NodeStateTable<(TInput1, TInput2)> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<(TInput1, TInput2)> previousTable, CancellationToken cancellationToken) { // get both input tables var input1Table = graphState.GetLatestStateTableForNode(_input1); var input2Table = graphState.GetLatestStateTableForNode(_input2); if (input1Table.IsCached && input2Table.IsCached) { return previousTable; } var builder = previousTable.ToBuilder(); // Semantics of a join: // // When input1[i] is cached: // - cached if input2 is also cached // - modified otherwise // State of input1[i] otherwise. // get the input2 item var isInput2Cached = input2Table.IsCached; TInput2 input2 = input2Table.Single(); // append the input2 item to each item in input1 foreach (var entry1 in input1Table) { var state = (entry1.state, isInput2Cached) switch { (EntryState.Cached, true) => EntryState.Cached, (EntryState.Cached, false) => EntryState.Modified, _ => entry1.state }; var entry = (entry1.item, input2); if (state != EntryState.Modified || _comparer is null || !builder.TryModifyEntry(entry, _comparer)) { builder.AddEntry(entry, state); } } return builder.ToImmutableAndFree(); } public IIncrementalGeneratorNode<(TInput1, TInput2)> WithComparer(IEqualityComparer<(TInput1, TInput2)> comparer) => new CombineNode<TInput1, TInput2>(_input1, _input2, comparer); public void RegisterOutput(IIncrementalGeneratorOutputNode output) { // We have to call register on both branches of the join, as they may chain up to different input nodes _input1.RegisterOutput(output); _input2.RegisterOutput(output); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis { internal sealed class CombineNode<TInput1, TInput2> : IIncrementalGeneratorNode<(TInput1, TInput2)> { private readonly IIncrementalGeneratorNode<TInput1> _input1; private readonly IIncrementalGeneratorNode<TInput2> _input2; private readonly IEqualityComparer<(TInput1, TInput2)>? _comparer; public CombineNode(IIncrementalGeneratorNode<TInput1> input1, IIncrementalGeneratorNode<TInput2> input2, IEqualityComparer<(TInput1, TInput2)>? comparer = null) { _input1 = input1; _input2 = input2; _comparer = comparer; } public NodeStateTable<(TInput1, TInput2)> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<(TInput1, TInput2)> previousTable, CancellationToken cancellationToken) { // get both input tables var input1Table = graphState.GetLatestStateTableForNode(_input1); var input2Table = graphState.GetLatestStateTableForNode(_input2); if (input1Table.IsCached && input2Table.IsCached) { return previousTable; } var builder = previousTable.ToBuilder(); // Semantics of a join: // // When input1[i] is cached: // - cached if input2 is also cached // - modified otherwise // State of input1[i] otherwise. // get the input2 item var isInput2Cached = input2Table.IsCached; TInput2 input2 = input2Table.Single(); // append the input2 item to each item in input1 foreach (var entry1 in input1Table) { var state = (entry1.state, isInput2Cached) switch { (EntryState.Cached, true) => EntryState.Cached, (EntryState.Cached, false) => EntryState.Modified, _ => entry1.state }; var entry = (entry1.item, input2); if (state != EntryState.Modified || _comparer is null || !builder.TryModifyEntry(entry, _comparer)) { builder.AddEntry(entry, state); } } return builder.ToImmutableAndFree(); } public IIncrementalGeneratorNode<(TInput1, TInput2)> WithComparer(IEqualityComparer<(TInput1, TInput2)> comparer) => new CombineNode<TInput1, TInput2>(_input1, _input2, comparer); public void RegisterOutput(IIncrementalGeneratorOutputNode output) { // We have to call register on both branches of the join, as they may chain up to different input nodes _input1.RegisterOutput(output); _input2.RegisterOutput(output); } } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/EditorFeatures/Test2/PasteTracking/PasteTrackingServiceTests.vb
' 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. Namespace Microsoft.CodeAnalysis.PasteTracking <UseExportProvider> Public Class PasteTrackingServiceTests Private Const Project1Name = "Proj1" Private Const Project2Name = "Proj2" Private Const Class1Name = "Class1.cs" Private Const Class2Name = "Class2.cs" Private Const PastedCode As String = " public void Main(string[] args) { }" Private Const UnformattedPastedCode As String = " public void Main(string[] args) { }" Private ReadOnly Property SingleFileCode As XElement = <Workspace> <Project Language="C#" CommonReferences="True" AssemblyName="Proj1"> <Document FilePath="Class1.cs"> public class Class1 { $$ } </Document> </Project> </Workspace> Private ReadOnly Property MultiFileCode As XElement = <Workspace> <Project Language="C#" CommonReferences="True" AssemblyName=<%= Project1Name %>> <Document FilePath=<%= Class1Name %>> public class Class1 { $$ } </Document> <Document FilePath=<%= Class2Name %>> public class Class2 { public const string Greeting = "Hello"; $$ } </Document> </Project> <Project Language="C#" CommonReferences="True" AssemblyName=<%= Project2Name %>> <Document IsLinkFile="True" LinkAssemblyName="Proj1" LinkFilePath=<%= Class1Name %>/> </Project> </Workspace> <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Sub PasteTracking_MissingTextSpan_WhenNothingPasted() Using testState = New PasteTrackingTestState(SingleFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) testState.AssertMissingPastedTextSpan(class1Document.GetTextBuffer()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasTextSpan_AfterPaste() As Task Using testState = New PasteTrackingTestState(SingleFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim expectedTextSpan = testState.SendPaste(class1Document, PastedCode) Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasTextSpan_AfterFormattingPaste() As Task Using testState = New PasteTrackingTestState(SingleFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim expectedTextSpan = testState.SendPaste(class1Document, UnformattedPastedCode) Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasTextSpan_AfterMultiplePastes() As Task Using testState = New PasteTrackingTestState(SingleFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim firstTextSpan = testState.SendPaste(class1Document, PastedCode) Dim expectedTextSpan = testState.SendPaste(class1Document, PastedCode) Assert.NotEqual(firstTextSpan, expectedTextSpan) Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Sub PasteTracking_MissingTextSpan_AfterPasteThenEdit() Using testState = New PasteTrackingTestState(SingleFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) testState.SendPaste(class1Document, PastedCode) testState.InsertText(class1Document, "Foo") testState.AssertMissingPastedTextSpan(class1Document.GetTextBuffer()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasTextSpan_AfterPasteThenCloseThenOpenThenPaste() As Task Using testState = New PasteTrackingTestState(SingleFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) testState.SendPaste(class1Document, PastedCode) testState.CloseDocument(class1Document) testState.OpenDocument(class1Document) Dim expectedTextSpan = testState.SendPaste(class1Document, PastedCode) Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasMultipleTextSpan_AfterPasteInMultipleFiles() As Task Using testState = New PasteTrackingTestState(MultiFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim class2Document = testState.OpenDocument(Project1Name, Class2Name) Dim expectedClass1TextSpan = testState.SendPaste(class1Document, PastedCode) Dim expectedClass2TextSpan = testState.SendPaste(class2Document, PastedCode) Assert.NotEqual(expectedClass1TextSpan, expectedClass2TextSpan) Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedClass1TextSpan) Await testState.AssertHasPastedTextSpanAsync(class2Document, expectedClass2TextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasSingleTextSpan_AfterPasteInMultipleFilesThenOneClosed() As Task Using testState = New PasteTrackingTestState(MultiFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim class2Document = testState.OpenDocument(Project1Name, Class2Name) testState.SendPaste(class1Document, PastedCode) Dim expectedClass2TextSpan = testState.SendPaste(class2Document, PastedCode) Await testState.AssertHasPastedTextSpanAsync(class2Document, expectedClass2TextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasTextSpanInLinkedFile_AfterPaste() As Task Using testState = New PasteTrackingTestState(MultiFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name) Dim expectedClass1TextSpan = testState.SendPaste(class1Document, PastedCode) Await testState.AssertHasPastedTextSpanAsync(class1LinkedDocument, expectedClass1TextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasTextSpanInLinkedFile_AfterPasteThenClose() As Task Using testState = New PasteTrackingTestState(MultiFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name) Dim expectedClass1TextSpan = testState.SendPaste(class1Document, PastedCode) testState.CloseDocument(class1Document) Await testState.AssertHasPastedTextSpanAsync(class1LinkedDocument, expectedClass1TextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Sub PasteTracking_MissingTextSpan_AfterPasteThenLinkedFileEdited() Using testState = New PasteTrackingTestState(MultiFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name) testState.SendPaste(class1Document, PastedCode) testState.InsertText(class1LinkedDocument, "Foo") testState.AssertMissingPastedTextSpan(class1Document.GetTextBuffer()) testState.AssertMissingPastedTextSpan(class1LinkedDocument.GetTextBuffer()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasTextSpanForLinkedFile_AfterPasteThenCloseAllThenOpenThenPaste() As Task Using testState = New PasteTrackingTestState(MultiFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name) testState.SendPaste(class1Document, PastedCode) testState.CloseDocument(class1Document) testState.CloseDocument(class1LinkedDocument) testState.OpenDocument(class1LinkedDocument) Dim expectedTextSpan = testState.SendPaste(class1LinkedDocument, PastedCode) Await testState.AssertHasPastedTextSpanAsync(class1LinkedDocument, expectedTextSpan) End Using End Function End Class End Namespace
' 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. Namespace Microsoft.CodeAnalysis.PasteTracking <UseExportProvider> Public Class PasteTrackingServiceTests Private Const Project1Name = "Proj1" Private Const Project2Name = "Proj2" Private Const Class1Name = "Class1.cs" Private Const Class2Name = "Class2.cs" Private Const PastedCode As String = " public void Main(string[] args) { }" Private Const UnformattedPastedCode As String = " public void Main(string[] args) { }" Private ReadOnly Property SingleFileCode As XElement = <Workspace> <Project Language="C#" CommonReferences="True" AssemblyName="Proj1"> <Document FilePath="Class1.cs"> public class Class1 { $$ } </Document> </Project> </Workspace> Private ReadOnly Property MultiFileCode As XElement = <Workspace> <Project Language="C#" CommonReferences="True" AssemblyName=<%= Project1Name %>> <Document FilePath=<%= Class1Name %>> public class Class1 { $$ } </Document> <Document FilePath=<%= Class2Name %>> public class Class2 { public const string Greeting = "Hello"; $$ } </Document> </Project> <Project Language="C#" CommonReferences="True" AssemblyName=<%= Project2Name %>> <Document IsLinkFile="True" LinkAssemblyName="Proj1" LinkFilePath=<%= Class1Name %>/> </Project> </Workspace> <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Sub PasteTracking_MissingTextSpan_WhenNothingPasted() Using testState = New PasteTrackingTestState(SingleFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) testState.AssertMissingPastedTextSpan(class1Document.GetTextBuffer()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasTextSpan_AfterPaste() As Task Using testState = New PasteTrackingTestState(SingleFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim expectedTextSpan = testState.SendPaste(class1Document, PastedCode) Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasTextSpan_AfterFormattingPaste() As Task Using testState = New PasteTrackingTestState(SingleFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim expectedTextSpan = testState.SendPaste(class1Document, UnformattedPastedCode) Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasTextSpan_AfterMultiplePastes() As Task Using testState = New PasteTrackingTestState(SingleFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim firstTextSpan = testState.SendPaste(class1Document, PastedCode) Dim expectedTextSpan = testState.SendPaste(class1Document, PastedCode) Assert.NotEqual(firstTextSpan, expectedTextSpan) Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Sub PasteTracking_MissingTextSpan_AfterPasteThenEdit() Using testState = New PasteTrackingTestState(SingleFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) testState.SendPaste(class1Document, PastedCode) testState.InsertText(class1Document, "Foo") testState.AssertMissingPastedTextSpan(class1Document.GetTextBuffer()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasTextSpan_AfterPasteThenCloseThenOpenThenPaste() As Task Using testState = New PasteTrackingTestState(SingleFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) testState.SendPaste(class1Document, PastedCode) testState.CloseDocument(class1Document) testState.OpenDocument(class1Document) Dim expectedTextSpan = testState.SendPaste(class1Document, PastedCode) Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasMultipleTextSpan_AfterPasteInMultipleFiles() As Task Using testState = New PasteTrackingTestState(MultiFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim class2Document = testState.OpenDocument(Project1Name, Class2Name) Dim expectedClass1TextSpan = testState.SendPaste(class1Document, PastedCode) Dim expectedClass2TextSpan = testState.SendPaste(class2Document, PastedCode) Assert.NotEqual(expectedClass1TextSpan, expectedClass2TextSpan) Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedClass1TextSpan) Await testState.AssertHasPastedTextSpanAsync(class2Document, expectedClass2TextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasSingleTextSpan_AfterPasteInMultipleFilesThenOneClosed() As Task Using testState = New PasteTrackingTestState(MultiFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim class2Document = testState.OpenDocument(Project1Name, Class2Name) testState.SendPaste(class1Document, PastedCode) Dim expectedClass2TextSpan = testState.SendPaste(class2Document, PastedCode) Await testState.AssertHasPastedTextSpanAsync(class2Document, expectedClass2TextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasTextSpanInLinkedFile_AfterPaste() As Task Using testState = New PasteTrackingTestState(MultiFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name) Dim expectedClass1TextSpan = testState.SendPaste(class1Document, PastedCode) Await testState.AssertHasPastedTextSpanAsync(class1LinkedDocument, expectedClass1TextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasTextSpanInLinkedFile_AfterPasteThenClose() As Task Using testState = New PasteTrackingTestState(MultiFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name) Dim expectedClass1TextSpan = testState.SendPaste(class1Document, PastedCode) testState.CloseDocument(class1Document) Await testState.AssertHasPastedTextSpanAsync(class1LinkedDocument, expectedClass1TextSpan) End Using End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Sub PasteTracking_MissingTextSpan_AfterPasteThenLinkedFileEdited() Using testState = New PasteTrackingTestState(MultiFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name) testState.SendPaste(class1Document, PastedCode) testState.InsertText(class1LinkedDocument, "Foo") testState.AssertMissingPastedTextSpan(class1Document.GetTextBuffer()) testState.AssertMissingPastedTextSpan(class1LinkedDocument.GetTextBuffer()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.PasteTracking)> Public Async Function PasteTracking_HasTextSpanForLinkedFile_AfterPasteThenCloseAllThenOpenThenPaste() As Task Using testState = New PasteTrackingTestState(MultiFileCode) Dim class1Document = testState.OpenDocument(Project1Name, Class1Name) Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name) testState.SendPaste(class1Document, PastedCode) testState.CloseDocument(class1Document) testState.CloseDocument(class1LinkedDocument) testState.OpenDocument(class1LinkedDocument) Dim expectedTextSpan = testState.SendPaste(class1LinkedDocument, PastedCode) Await testState.AssertHasPastedTextSpanAsync(class1LinkedDocument, expectedTextSpan) End Using End Function End Class End Namespace
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Features/CSharp/Portable/ReverseForStatement/CSharpReverseForStatementCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ReverseForStatement { using static IntegerUtilities; [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ReverseForStatement), Shared] internal class CSharpReverseForStatementCodeRefactoringProvider : CodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpReverseForStatementCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var forStatement = await context.TryGetRelevantNodeAsync<ForStatementSyntax>().ConfigureAwait(false); if (forStatement == null) return; // We support the following cases // // for (var x = start; x < end ; x++) // for (... ; ... ; ++x) // for (... ; x <= end; ...) // for (... ; ... ; x += 1) // // for (var x = end ; x >= start; x--) // for (... ; ... ; --x) // for (... ; ... ; x -= 1) var declaration = forStatement.Declaration; if (declaration == null || declaration.Variables.Count != 1 || forStatement.Incrementors.Count != 1) { return; } var variable = declaration.Variables[0]; var after = forStatement.Incrementors[0]; if (!(forStatement.Condition is BinaryExpressionSyntax condition)) return; var (document, _, cancellationToken) = context; if (MatchesIncrementPattern(variable, condition, after, out var start, out var equals, out var end) || MatchesDecrementPattern(variable, condition, after, out end, out start)) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (IsUnsignedBoundary(semanticModel, variable, start, end, cancellationToken)) { // Don't allow reversing when you have unsigned types and are on the start/end // of the legal values for that type. i.e. `for (byte i = 0; i < 10; i++)` it's // not trivial to reverse this. return; } context.RegisterRefactoring(new MyCodeAction( c => ReverseForStatementAsync(document, forStatement, c))); } } private static bool IsUnsignedBoundary( SemanticModel semanticModel, VariableDeclaratorSyntax variable, ExpressionSyntax start, ExpressionSyntax end, CancellationToken cancellationToken) { var local = semanticModel.GetDeclaredSymbol(variable, cancellationToken) as ILocalSymbol; var startValue = semanticModel.GetConstantValue(start, cancellationToken); var endValue = semanticModel.GetConstantValue(end, cancellationToken); return local?.Type.SpecialType switch { SpecialType.System_Byte => IsUnsignedBoundary(startValue, endValue, byte.MaxValue), SpecialType.System_UInt16 => IsUnsignedBoundary(startValue, endValue, ushort.MaxValue), SpecialType.System_UInt32 => IsUnsignedBoundary(startValue, endValue, uint.MaxValue), SpecialType.System_UInt64 => IsUnsignedBoundary(startValue, endValue, ulong.MaxValue), _ => false, }; } private static bool IsUnsignedBoundary(Optional<object?> startValue, Optional<object?> endValue, ulong maxValue) => ValueEquals(startValue, 0) || ValueEquals(endValue, maxValue); private static bool ValueEquals(Optional<object?> valueOpt, ulong value) => valueOpt.HasValue && IsIntegral(valueOpt.Value) && ToUInt64(valueOpt.Value) == value; private static bool MatchesIncrementPattern( VariableDeclaratorSyntax variable, BinaryExpressionSyntax condition, ExpressionSyntax after, [NotNullWhen(true)] out ExpressionSyntax? start, out bool equals, [NotNullWhen(true)] out ExpressionSyntax? end) { equals = default; end = null; return IsIncrementInitializer(variable, out start) && IsIncrementCondition(variable, condition, out equals, out end) && IsIncrementAfter(variable, after); } private static bool MatchesDecrementPattern( VariableDeclaratorSyntax variable, BinaryExpressionSyntax condition, ExpressionSyntax after, [NotNullWhen(true)] out ExpressionSyntax? end, [NotNullWhen(true)] out ExpressionSyntax? start) { start = null; return IsDecrementInitializer(variable, out end) && IsDecrementCondition(variable, condition, out start) && IsDecrementAfter(variable, after); } private static bool IsIncrementInitializer(VariableDeclaratorSyntax variable, [NotNullWhen(true)] out ExpressionSyntax? start) { start = variable.Initializer?.Value; return start != null; } private static bool IsIncrementCondition( VariableDeclaratorSyntax variable, BinaryExpressionSyntax condition, out bool equals, [NotNullWhen(true)] out ExpressionSyntax? end) { // i < ... i <= ... if (condition.Kind() == SyntaxKind.LessThanExpression || condition.Kind() == SyntaxKind.LessThanOrEqualExpression) { end = condition.Right; equals = condition.Kind() == SyntaxKind.LessThanOrEqualExpression; return IsVariableReference(variable, condition.Left); } // ... > i ... >= i if (condition.Kind() == SyntaxKind.GreaterThanExpression || condition.Kind() == SyntaxKind.GreaterThanOrEqualExpression) { end = condition.Left; equals = condition.Kind() == SyntaxKind.GreaterThanOrEqualExpression; return IsVariableReference(variable, condition.Right); } end = null; equals = default; return false; } private static bool IsIncrementAfter( VariableDeclaratorSyntax variable, ExpressionSyntax after) { // i++ // ++i // i += 1 if (after is PostfixUnaryExpressionSyntax postfixUnary && postfixUnary.Kind() == SyntaxKind.PostIncrementExpression && IsVariableReference(variable, postfixUnary.Operand)) { return true; } if (after is PrefixUnaryExpressionSyntax prefixUnary && prefixUnary.Kind() == SyntaxKind.PreIncrementExpression && IsVariableReference(variable, prefixUnary.Operand)) { return true; } if (after is AssignmentExpressionSyntax assignment && assignment.Kind() == SyntaxKind.AddAssignmentExpression && IsVariableReference(variable, assignment.Left) && IsLiteralOne(assignment.Right)) { return true; } return false; } private static bool IsLiteralOne(ExpressionSyntax expression) => expression.WalkDownParentheses() is LiteralExpressionSyntax literal && literal.Token.Value is 1; private static bool IsDecrementInitializer( VariableDeclaratorSyntax variable, [NotNullWhen(true)] out ExpressionSyntax? end) { end = variable.Initializer?.Value; return end != null; } private static bool IsDecrementCondition( VariableDeclaratorSyntax variable, BinaryExpressionSyntax condition, [NotNullWhen(true)] out ExpressionSyntax? start) { // i >= ... if (condition.Kind() == SyntaxKind.GreaterThanOrEqualExpression) { start = condition.Right; return IsVariableReference(variable, condition.Left); } // ... <= i if (condition.Kind() == SyntaxKind.LessThanOrEqualExpression) { start = condition.Left; return IsVariableReference(variable, condition.Right); } start = null; return false; } private static bool IsDecrementAfter( VariableDeclaratorSyntax variable, ExpressionSyntax after) { // i-- // --i // i -= 1 if (after is PostfixUnaryExpressionSyntax postfixUnary && postfixUnary.Kind() == SyntaxKind.PostDecrementExpression && IsVariableReference(variable, postfixUnary.Operand)) { return true; } if (after is PrefixUnaryExpressionSyntax prefixUnary && prefixUnary.Kind() == SyntaxKind.PreDecrementExpression && IsVariableReference(variable, prefixUnary.Operand)) { return true; } if (after is AssignmentExpressionSyntax assignment && assignment.Kind() == SyntaxKind.SubtractAssignmentExpression && IsVariableReference(variable, assignment.Left) && IsLiteralOne(assignment.Right)) { return true; } return false; } private static bool IsVariableReference(VariableDeclaratorSyntax variable, ExpressionSyntax expr) => expr.WalkDownParentheses() is IdentifierNameSyntax identifier && identifier.Identifier.ValueText == variable.Identifier.ValueText; private async Task<Document> ReverseForStatementAsync( Document document, ForStatementSyntax forStatement, CancellationToken cancellationToken) { var variable = forStatement.Declaration!.Variables[0]; var condition = (BinaryExpressionSyntax)forStatement.Condition!; var after = forStatement.Incrementors[0]; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var generator = editor.Generator; if (MatchesIncrementPattern( variable, condition, after, out var start, out var equals, out var end)) { // for (var x = start ; x < end ; ...) => // for (var x = end - 1; x >= start; ...) // // for (var x = start; x <= end ; ...) => // for (var x = end ; x >= start; ...) => var newStart = equals ? end : (ExpressionSyntax)generator.SubtractExpression(end, generator.LiteralExpression(1)); editor.ReplaceNode(variable.Initializer!.Value, Reduce(newStart)); editor.ReplaceNode(condition, Reduce(Invert(variable, condition, start))); } else if (MatchesDecrementPattern(variable, condition, after, out end, out start)) { // for (var x = end; x >= start; x--) => // for (var x = start; x <= end; x--) editor.ReplaceNode(variable.Initializer!.Value, Reduce(start)); editor.ReplaceNode(condition, Reduce(Invert(variable, condition, end))); } else { throw new InvalidOperationException(); } editor.ReplaceNode(after, InvertAfter(after)); return document.WithSyntaxRoot(editor.GetChangedRoot()); } private ExpressionSyntax Reduce(ExpressionSyntax expr) { expr = expr.WalkDownParentheses(); if (expr is BinaryExpressionSyntax outerBinary) { var reducedLeft = Reduce(outerBinary.Left); var reducedRight = Reduce(outerBinary.Right); // (... + 1) - 1 => ... // (... - 1) + 1 => ... { if (reducedLeft is BinaryExpressionSyntax innerLeft && IsLiteralOne(innerLeft.Right) && IsLiteralOne(reducedRight)) { if ((outerBinary.Kind() == SyntaxKind.SubtractExpression && innerLeft.Kind() == SyntaxKind.AddExpression) || (outerBinary.Kind() == SyntaxKind.AddExpression && innerLeft.Kind() == SyntaxKind.SubtractExpression)) { return Reduce(innerLeft.Left); } } } // v <= x - 1 => v < x // x - 1 >= v => x > v { if (outerBinary.Kind() == SyntaxKind.LessThanOrEqualExpression && reducedRight is BinaryExpressionSyntax innerRight && innerRight.Kind() == SyntaxKind.SubtractExpression && IsLiteralOne(innerRight.Right)) { var newOperator = SyntaxFactory.Token(SyntaxKind.LessThanToken).WithTriviaFrom(outerBinary.OperatorToken); return Reduce(outerBinary.WithRight(innerRight.Left) .WithOperatorToken(newOperator)); } if (outerBinary.Kind() == SyntaxKind.GreaterThanOrEqualExpression && reducedLeft is BinaryExpressionSyntax innerLeft && innerLeft.Kind() == SyntaxKind.SubtractExpression && IsLiteralOne(innerLeft.Right)) { var newOperator = SyntaxFactory.Token(SyntaxKind.GreaterThanToken).WithTriviaFrom(outerBinary.OperatorToken); return Reduce(outerBinary.WithRight(innerLeft.Left) .WithOperatorToken(newOperator)); } } } return expr.WithAdditionalAnnotations(Formatter.Annotation); } private static BinaryExpressionSyntax Invert( VariableDeclaratorSyntax variable, BinaryExpressionSyntax condition, ExpressionSyntax operand) { var (left, right) = IsVariableReference(variable, condition.Left) ? (condition.Left, operand) : (operand, condition.Right); var newOperatorKind = condition.Kind() == SyntaxKind.LessThanExpression || condition.Kind() == SyntaxKind.LessThanOrEqualExpression ? SyntaxKind.GreaterThanEqualsToken : SyntaxKind.LessThanEqualsToken; var newExpressionKind = newOperatorKind == SyntaxKind.GreaterThanEqualsToken ? SyntaxKind.GreaterThanOrEqualExpression : SyntaxKind.LessThanOrEqualExpression; var newOperator = SyntaxFactory.Token(newOperatorKind).WithTriviaFrom(condition.OperatorToken); return SyntaxFactory.BinaryExpression(newExpressionKind, left, newOperator, right); } private static ExpressionSyntax InvertAfter(ExpressionSyntax after) { var opToken = after switch { PostfixUnaryExpressionSyntax postfixUnary => postfixUnary.OperatorToken, PrefixUnaryExpressionSyntax prefixUnary => prefixUnary.OperatorToken, AssignmentExpressionSyntax assignment => assignment.OperatorToken, _ => throw ExceptionUtilities.UnexpectedValue(after.Kind()) }; var newKind = opToken.Kind() switch { SyntaxKind.MinusMinusToken => SyntaxKind.PlusPlusToken, SyntaxKind.PlusPlusToken => SyntaxKind.MinusMinusToken, SyntaxKind.PlusEqualsToken => SyntaxKind.MinusEqualsToken, SyntaxKind.MinusEqualsToken => SyntaxKind.PlusEqualsToken, _ => throw ExceptionUtilities.UnexpectedValue(opToken.Kind()) }; var newOpToken = SyntaxFactory.Token(newKind).WithTriviaFrom(opToken); return after.ReplaceToken(opToken, newOpToken); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Reverse_for_statement, createChangedDocument, nameof(CSharpFeaturesResources.Reverse_for_statement)) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ReverseForStatement { using static IntegerUtilities; [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ReverseForStatement), Shared] internal class CSharpReverseForStatementCodeRefactoringProvider : CodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpReverseForStatementCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var forStatement = await context.TryGetRelevantNodeAsync<ForStatementSyntax>().ConfigureAwait(false); if (forStatement == null) return; // We support the following cases // // for (var x = start; x < end ; x++) // for (... ; ... ; ++x) // for (... ; x <= end; ...) // for (... ; ... ; x += 1) // // for (var x = end ; x >= start; x--) // for (... ; ... ; --x) // for (... ; ... ; x -= 1) var declaration = forStatement.Declaration; if (declaration == null || declaration.Variables.Count != 1 || forStatement.Incrementors.Count != 1) { return; } var variable = declaration.Variables[0]; var after = forStatement.Incrementors[0]; if (!(forStatement.Condition is BinaryExpressionSyntax condition)) return; var (document, _, cancellationToken) = context; if (MatchesIncrementPattern(variable, condition, after, out var start, out var equals, out var end) || MatchesDecrementPattern(variable, condition, after, out end, out start)) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (IsUnsignedBoundary(semanticModel, variable, start, end, cancellationToken)) { // Don't allow reversing when you have unsigned types and are on the start/end // of the legal values for that type. i.e. `for (byte i = 0; i < 10; i++)` it's // not trivial to reverse this. return; } context.RegisterRefactoring(new MyCodeAction( c => ReverseForStatementAsync(document, forStatement, c))); } } private static bool IsUnsignedBoundary( SemanticModel semanticModel, VariableDeclaratorSyntax variable, ExpressionSyntax start, ExpressionSyntax end, CancellationToken cancellationToken) { var local = semanticModel.GetDeclaredSymbol(variable, cancellationToken) as ILocalSymbol; var startValue = semanticModel.GetConstantValue(start, cancellationToken); var endValue = semanticModel.GetConstantValue(end, cancellationToken); return local?.Type.SpecialType switch { SpecialType.System_Byte => IsUnsignedBoundary(startValue, endValue, byte.MaxValue), SpecialType.System_UInt16 => IsUnsignedBoundary(startValue, endValue, ushort.MaxValue), SpecialType.System_UInt32 => IsUnsignedBoundary(startValue, endValue, uint.MaxValue), SpecialType.System_UInt64 => IsUnsignedBoundary(startValue, endValue, ulong.MaxValue), _ => false, }; } private static bool IsUnsignedBoundary(Optional<object?> startValue, Optional<object?> endValue, ulong maxValue) => ValueEquals(startValue, 0) || ValueEquals(endValue, maxValue); private static bool ValueEquals(Optional<object?> valueOpt, ulong value) => valueOpt.HasValue && IsIntegral(valueOpt.Value) && ToUInt64(valueOpt.Value) == value; private static bool MatchesIncrementPattern( VariableDeclaratorSyntax variable, BinaryExpressionSyntax condition, ExpressionSyntax after, [NotNullWhen(true)] out ExpressionSyntax? start, out bool equals, [NotNullWhen(true)] out ExpressionSyntax? end) { equals = default; end = null; return IsIncrementInitializer(variable, out start) && IsIncrementCondition(variable, condition, out equals, out end) && IsIncrementAfter(variable, after); } private static bool MatchesDecrementPattern( VariableDeclaratorSyntax variable, BinaryExpressionSyntax condition, ExpressionSyntax after, [NotNullWhen(true)] out ExpressionSyntax? end, [NotNullWhen(true)] out ExpressionSyntax? start) { start = null; return IsDecrementInitializer(variable, out end) && IsDecrementCondition(variable, condition, out start) && IsDecrementAfter(variable, after); } private static bool IsIncrementInitializer(VariableDeclaratorSyntax variable, [NotNullWhen(true)] out ExpressionSyntax? start) { start = variable.Initializer?.Value; return start != null; } private static bool IsIncrementCondition( VariableDeclaratorSyntax variable, BinaryExpressionSyntax condition, out bool equals, [NotNullWhen(true)] out ExpressionSyntax? end) { // i < ... i <= ... if (condition.Kind() == SyntaxKind.LessThanExpression || condition.Kind() == SyntaxKind.LessThanOrEqualExpression) { end = condition.Right; equals = condition.Kind() == SyntaxKind.LessThanOrEqualExpression; return IsVariableReference(variable, condition.Left); } // ... > i ... >= i if (condition.Kind() == SyntaxKind.GreaterThanExpression || condition.Kind() == SyntaxKind.GreaterThanOrEqualExpression) { end = condition.Left; equals = condition.Kind() == SyntaxKind.GreaterThanOrEqualExpression; return IsVariableReference(variable, condition.Right); } end = null; equals = default; return false; } private static bool IsIncrementAfter( VariableDeclaratorSyntax variable, ExpressionSyntax after) { // i++ // ++i // i += 1 if (after is PostfixUnaryExpressionSyntax postfixUnary && postfixUnary.Kind() == SyntaxKind.PostIncrementExpression && IsVariableReference(variable, postfixUnary.Operand)) { return true; } if (after is PrefixUnaryExpressionSyntax prefixUnary && prefixUnary.Kind() == SyntaxKind.PreIncrementExpression && IsVariableReference(variable, prefixUnary.Operand)) { return true; } if (after is AssignmentExpressionSyntax assignment && assignment.Kind() == SyntaxKind.AddAssignmentExpression && IsVariableReference(variable, assignment.Left) && IsLiteralOne(assignment.Right)) { return true; } return false; } private static bool IsLiteralOne(ExpressionSyntax expression) => expression.WalkDownParentheses() is LiteralExpressionSyntax literal && literal.Token.Value is 1; private static bool IsDecrementInitializer( VariableDeclaratorSyntax variable, [NotNullWhen(true)] out ExpressionSyntax? end) { end = variable.Initializer?.Value; return end != null; } private static bool IsDecrementCondition( VariableDeclaratorSyntax variable, BinaryExpressionSyntax condition, [NotNullWhen(true)] out ExpressionSyntax? start) { // i >= ... if (condition.Kind() == SyntaxKind.GreaterThanOrEqualExpression) { start = condition.Right; return IsVariableReference(variable, condition.Left); } // ... <= i if (condition.Kind() == SyntaxKind.LessThanOrEqualExpression) { start = condition.Left; return IsVariableReference(variable, condition.Right); } start = null; return false; } private static bool IsDecrementAfter( VariableDeclaratorSyntax variable, ExpressionSyntax after) { // i-- // --i // i -= 1 if (after is PostfixUnaryExpressionSyntax postfixUnary && postfixUnary.Kind() == SyntaxKind.PostDecrementExpression && IsVariableReference(variable, postfixUnary.Operand)) { return true; } if (after is PrefixUnaryExpressionSyntax prefixUnary && prefixUnary.Kind() == SyntaxKind.PreDecrementExpression && IsVariableReference(variable, prefixUnary.Operand)) { return true; } if (after is AssignmentExpressionSyntax assignment && assignment.Kind() == SyntaxKind.SubtractAssignmentExpression && IsVariableReference(variable, assignment.Left) && IsLiteralOne(assignment.Right)) { return true; } return false; } private static bool IsVariableReference(VariableDeclaratorSyntax variable, ExpressionSyntax expr) => expr.WalkDownParentheses() is IdentifierNameSyntax identifier && identifier.Identifier.ValueText == variable.Identifier.ValueText; private async Task<Document> ReverseForStatementAsync( Document document, ForStatementSyntax forStatement, CancellationToken cancellationToken) { var variable = forStatement.Declaration!.Variables[0]; var condition = (BinaryExpressionSyntax)forStatement.Condition!; var after = forStatement.Incrementors[0]; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var generator = editor.Generator; if (MatchesIncrementPattern( variable, condition, after, out var start, out var equals, out var end)) { // for (var x = start ; x < end ; ...) => // for (var x = end - 1; x >= start; ...) // // for (var x = start; x <= end ; ...) => // for (var x = end ; x >= start; ...) => var newStart = equals ? end : (ExpressionSyntax)generator.SubtractExpression(end, generator.LiteralExpression(1)); editor.ReplaceNode(variable.Initializer!.Value, Reduce(newStart)); editor.ReplaceNode(condition, Reduce(Invert(variable, condition, start))); } else if (MatchesDecrementPattern(variable, condition, after, out end, out start)) { // for (var x = end; x >= start; x--) => // for (var x = start; x <= end; x--) editor.ReplaceNode(variable.Initializer!.Value, Reduce(start)); editor.ReplaceNode(condition, Reduce(Invert(variable, condition, end))); } else { throw new InvalidOperationException(); } editor.ReplaceNode(after, InvertAfter(after)); return document.WithSyntaxRoot(editor.GetChangedRoot()); } private ExpressionSyntax Reduce(ExpressionSyntax expr) { expr = expr.WalkDownParentheses(); if (expr is BinaryExpressionSyntax outerBinary) { var reducedLeft = Reduce(outerBinary.Left); var reducedRight = Reduce(outerBinary.Right); // (... + 1) - 1 => ... // (... - 1) + 1 => ... { if (reducedLeft is BinaryExpressionSyntax innerLeft && IsLiteralOne(innerLeft.Right) && IsLiteralOne(reducedRight)) { if ((outerBinary.Kind() == SyntaxKind.SubtractExpression && innerLeft.Kind() == SyntaxKind.AddExpression) || (outerBinary.Kind() == SyntaxKind.AddExpression && innerLeft.Kind() == SyntaxKind.SubtractExpression)) { return Reduce(innerLeft.Left); } } } // v <= x - 1 => v < x // x - 1 >= v => x > v { if (outerBinary.Kind() == SyntaxKind.LessThanOrEqualExpression && reducedRight is BinaryExpressionSyntax innerRight && innerRight.Kind() == SyntaxKind.SubtractExpression && IsLiteralOne(innerRight.Right)) { var newOperator = SyntaxFactory.Token(SyntaxKind.LessThanToken).WithTriviaFrom(outerBinary.OperatorToken); return Reduce(outerBinary.WithRight(innerRight.Left) .WithOperatorToken(newOperator)); } if (outerBinary.Kind() == SyntaxKind.GreaterThanOrEqualExpression && reducedLeft is BinaryExpressionSyntax innerLeft && innerLeft.Kind() == SyntaxKind.SubtractExpression && IsLiteralOne(innerLeft.Right)) { var newOperator = SyntaxFactory.Token(SyntaxKind.GreaterThanToken).WithTriviaFrom(outerBinary.OperatorToken); return Reduce(outerBinary.WithRight(innerLeft.Left) .WithOperatorToken(newOperator)); } } } return expr.WithAdditionalAnnotations(Formatter.Annotation); } private static BinaryExpressionSyntax Invert( VariableDeclaratorSyntax variable, BinaryExpressionSyntax condition, ExpressionSyntax operand) { var (left, right) = IsVariableReference(variable, condition.Left) ? (condition.Left, operand) : (operand, condition.Right); var newOperatorKind = condition.Kind() == SyntaxKind.LessThanExpression || condition.Kind() == SyntaxKind.LessThanOrEqualExpression ? SyntaxKind.GreaterThanEqualsToken : SyntaxKind.LessThanEqualsToken; var newExpressionKind = newOperatorKind == SyntaxKind.GreaterThanEqualsToken ? SyntaxKind.GreaterThanOrEqualExpression : SyntaxKind.LessThanOrEqualExpression; var newOperator = SyntaxFactory.Token(newOperatorKind).WithTriviaFrom(condition.OperatorToken); return SyntaxFactory.BinaryExpression(newExpressionKind, left, newOperator, right); } private static ExpressionSyntax InvertAfter(ExpressionSyntax after) { var opToken = after switch { PostfixUnaryExpressionSyntax postfixUnary => postfixUnary.OperatorToken, PrefixUnaryExpressionSyntax prefixUnary => prefixUnary.OperatorToken, AssignmentExpressionSyntax assignment => assignment.OperatorToken, _ => throw ExceptionUtilities.UnexpectedValue(after.Kind()) }; var newKind = opToken.Kind() switch { SyntaxKind.MinusMinusToken => SyntaxKind.PlusPlusToken, SyntaxKind.PlusPlusToken => SyntaxKind.MinusMinusToken, SyntaxKind.PlusEqualsToken => SyntaxKind.MinusEqualsToken, SyntaxKind.MinusEqualsToken => SyntaxKind.PlusEqualsToken, _ => throw ExceptionUtilities.UnexpectedValue(opToken.Kind()) }; var newOpToken = SyntaxFactory.Token(newKind).WithTriviaFrom(opToken); return after.ReplaceToken(opToken, newOpToken); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Reverse_for_statement, createChangedDocument, nameof(CSharpFeaturesResources.Reverse_for_statement)) { } } } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicExtractMethodService.vb
' 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 System.Composition Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod <Export(GetType(IExtractMethodService)), ExportLanguageService(GetType(IExtractMethodService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicExtractMethodService Inherits AbstractExtractMethodService(Of VisualBasicSelectionValidator, VisualBasicMethodExtractor, VisualBasicSelectionResult) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function CreateSelectionValidator(document As SemanticDocument, textSpan As TextSpan, options As OptionSet) As VisualBasicSelectionValidator Return New VisualBasicSelectionValidator(document, textSpan, options) End Function Protected Overrides Function CreateMethodExtractor(selectionResult As VisualBasicSelectionResult, localFunction As Boolean) As VisualBasicMethodExtractor Return New VisualBasicMethodExtractor(selectionResult) End Function End Class End Namespace
' 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 System.Composition Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod <Export(GetType(IExtractMethodService)), ExportLanguageService(GetType(IExtractMethodService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicExtractMethodService Inherits AbstractExtractMethodService(Of VisualBasicSelectionValidator, VisualBasicMethodExtractor, VisualBasicSelectionResult) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function CreateSelectionValidator(document As SemanticDocument, textSpan As TextSpan, options As OptionSet) As VisualBasicSelectionValidator Return New VisualBasicSelectionValidator(document, textSpan, options) End Function Protected Overrides Function CreateMethodExtractor(selectionResult As VisualBasicSelectionResult, localFunction As Boolean) As VisualBasicMethodExtractor Return New VisualBasicMethodExtractor(selectionResult) End Function End Class End Namespace
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAsyncSpillTests.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenAsyncSpillTests : EmitMetadataTestBase { public CodeGenAsyncSpillTests() { } private CompilationVerifier CompileAndVerify(string source, string expectedOutput = null, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null) { return base.CompileAndVerify(source, expectedOutput: expectedOutput, references: references, options: options); } [Fact] public void AsyncWithTernary() { var source = @" using System; using System.Threading.Tasks; class Test { public static Task<T> F<T>(T x) { Console.WriteLine(""F("" + x + "")""); return Task.Factory.StartNew(() => { return x; }); } public static async Task<int> G(bool b1, bool b2) { int c = 0; c = c + (b1 ? 1 : await F(2)); c = c + (b2 ? await F(4) : 8); return await F(c); } public static int H(bool b1, bool b2) { Task<int> t = G(b1, b2); t.Wait(1000 * 60); return t.Result; } public static void Main() { Console.WriteLine(H(false, false)); Console.WriteLine(H(false, true)); Console.WriteLine(H(true, false)); Console.WriteLine(H(true, true)); } }"; var expected = @" F(2) F(10) 10 F(2) F(4) F(6) 6 F(9) 9 F(4) F(5) 5 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncWithAnd() { var source = @" using System; using System.Threading.Tasks; class Test { public static Task<T> F<T>(T x) { Console.WriteLine(""F("" + x + "")""); return Task.Factory.StartNew(() => { return x; }); } public static async Task<int> G(bool b1, bool b2) { bool x1 = b1 && await F(true); bool x2 = b1 && await F(false); bool x3 = b2 && await F(true); bool x4 = b2 && await F(false); int c = 0; if (x1) c += 1; if (x2) c += 2; if (x3) c += 4; if (x4) c += 8; return await F(c); } public static int H(bool b1, bool b2) { Task<int> t = G(b1, b2); t.Wait(1000 * 60); return t.Result; } public static void Main() { Console.WriteLine(H(false, true)); } }"; var expected = @" F(True) F(False) F(4) 4 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncWithOr() { var source = @" using System; using System.Threading.Tasks; class Test { public static Task<T> F<T>(T x) { Console.WriteLine(""F("" + x + "")""); return Task.Factory.StartNew(() => { return x; }); } public static async Task<int> G(bool b1, bool b2) { bool x1 = b1 || await F(true); bool x2 = b1 || await F(false); bool x3 = b2 || await F(true); bool x4 = b2 || await F(false); int c = 0; if (x1) c += 1; if (x2) c += 2; if (x3) c += 4; if (x4) c += 8; return await F(c); } public static int H(bool b1, bool b2) { Task<int> t = G(b1, b2); t.Wait(1000 * 60); return t.Result; } public static void Main() { Console.WriteLine(H(false, true)); } }"; var expected = @" F(True) F(False) F(13) 13 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncWithCoalesce() { var source = @" using System; using System.Threading.Tasks; class Test { public static Task<string> F(string x) { Console.WriteLine(""F("" + (x ?? ""null"") + "")""); return Task.Factory.StartNew(() => { return x; }); } public static async Task<string> G(string s1, string s2) { var result = await F(s1) ?? await F(s2); Console.WriteLine("" "" + (result ?? ""null"")); return result; } public static string H(string s1, string s2) { Task<string> t = G(s1, s2); t.Wait(1000 * 60); return t.Result; } public static void Main() { H(null, null); H(null, ""a""); H(""b"", null); H(""c"", ""d""); } }"; var expected = @" F(null) F(null) null F(null) F(a) a F(b) b F(c) c "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AwaitInExpr() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<int> F() { return await Task.Factory.StartNew(() => 21); } public static async Task<int> G() { int c = 0; c = (await F()) + 21; return c; } public static void Main() { Task<int> t = G(); t.Wait(1000 * 60); Console.WriteLine(t.Result); } }"; var expected = @" 42 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void SpillNestedUnary() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<int> F() { return 1; } public static async Task<int> G1() { return -(await F()); } public static async Task<int> G2() { return -(-(await F())); } public static async Task<int> G3() { return -(-(-(await F()))); } public static void WaitAndPrint(Task<int> t) { t.Wait(); Console.WriteLine(t.Result); } public static void Main() { WaitAndPrint(G1()); WaitAndPrint(G2()); WaitAndPrint(G3()); } }"; var expected = @" -1 1 -1 "; CompileAndVerify(source, expected); } [Fact] public void AsyncWithParamsAndLocals_DoubleAwait_Spilling() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<int> F(int x) { return await Task.Factory.StartNew(() => { return x; }); } public static async Task<int> G(int x) { int c = 0; c = (await F(x)) + c; c = (await F(x)) + c; return c; } public static void Main() { Task<int> t = G(21); t.Wait(1000 * 60); Console.WriteLine(t.Result); } }"; var expected = @" 42 "; // When the local 'c' gets hoisted, the statement: // c = (await F(x)) + c; // Gets rewritten to: // this.c_field = (await F(x)) + this.c_field; // // The code-gen for the assignment is something like this: // ldarg0 // load the 'this' reference to the stack // <emitted await expression> // stfld // // What we really want is to evaluate any parts of the lvalue that have side-effects (which is this case is // nothing), and then defer loading the address for the field reference until after the await expression: // <emitted await expression> // <store to tmp> // ldarg0 // <load tmp> // stfld // // So this case actually requires stack spilling, which is not yet implemented. This has the unfortunate // consequence of preventing await expressions from being assigned to hoisted locals. // CompileAndVerify(source, expectedOutput: expected); } [Fact] public void SpillCall() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Test { public static void Printer(int a, int b, int c, int d, int e) { foreach (var x in new List<int>() { a, b, c, d, e }) { Console.WriteLine(x); } } public static int Get(int x) { Console.WriteLine(""> "" + x); return x; } public static async Task<int> F(int x) { return await Task.Factory.StartNew(() => x); } public static async Task G() { Printer(Get(111), Get(222), Get(333), await F(Get(444)), Get(555)); } public static void Main() { Task t = G(); t.Wait(); } }"; var expected = @" > 111 > 222 > 333 > 444 > 555 111 222 333 444 555 "; CompileAndVerify(source, expected); } [Fact] public void SpillCall2() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Test { public static void Printer(int a, int b, int c, int d, int e) { foreach (var x in new List<int>() { a, b, c, d, e }) { Console.WriteLine(x); } } public static int Get(int x) { Console.WriteLine(""> "" + x); return x; } public static async Task<int> F(int x) { return await Task.Factory.StartNew(() => x); } public static async Task G() { Printer(Get(111), await F(Get(222)), Get(333), await F(Get(444)), Get(555)); } public static void Main() { Task t = G(); t.Wait(); } }"; var expected = @" > 111 > 222 > 333 > 444 > 555 111 222 333 444 555 "; CompileAndVerify(source, expected); } [Fact] public void SpillCall3() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Test { public static void Printer(int a, int b, int c, int d, int e, int f) { foreach (var x in new List<int>(){a, b, c, d, e, f}) { Console.WriteLine(x); } } public static async Task<int> F(int x) { return await Task.Factory.StartNew(() => x); } public static async Task G() { Printer(1, await F(2), 3, await F(await F(await F(await F(4)))), await F(5), 6); } public static void Main() { Task t = G(); t.Wait(); } }"; var expected = @" 1 2 3 4 5 6 "; CompileAndVerify(source, expected); } [Fact] public void SpillCall4() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Test { public static void Printer(int a, int b) { foreach (var x in new List<int>(){a, b}) { Console.WriteLine(x); } } public static async Task<int> F(int x) { return await Task.Factory.StartNew(() => x); } public static async Task G() { Printer(1, await F(await F(2))); } public static void Main() { Task t = G(); t.Wait(); } }"; var expected = @" 1 2 "; CompileAndVerify(source, expected); } [Fact] public void SpillSequences1() { var source = @" using System.Threading.Tasks; public class Test { public static int H(int a, int b, int c) { return a; } public static Task<int> G() { return null; } public static async Task<int> F(int[] array) { H(array[1] += 2, array[3] += await G(), 4); return 1; } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Test.<F>d__2.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"{ // Code size 273 (0x111) .maxstack 5 .locals init (int V_0, int V_1, int V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, Test.<F>d__2 V_4, System.Exception V_5) ~IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__2.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_0088 -IL_000e: nop -IL_000f: ldarg.0 IL_0010: ldarg.0 IL_0011: ldfld ""int[] Test.<F>d__2.array"" IL_0016: ldc.i4.1 IL_0017: ldelema ""int"" IL_001c: dup IL_001d: ldind.i4 IL_001e: ldc.i4.2 IL_001f: add IL_0020: dup IL_0021: stloc.2 IL_0022: stind.i4 IL_0023: ldloc.2 IL_0024: stfld ""int Test.<F>d__2.<>s__1"" IL_0029: ldarg.0 IL_002a: ldarg.0 IL_002b: ldfld ""int[] Test.<F>d__2.array"" IL_0030: stfld ""int[] Test.<F>d__2.<>s__4"" IL_0035: ldarg.0 IL_0036: ldfld ""int[] Test.<F>d__2.<>s__4"" IL_003b: ldc.i4.3 IL_003c: ldelem.i4 IL_003d: pop IL_003e: ldarg.0 IL_003f: ldarg.0 IL_0040: ldfld ""int[] Test.<F>d__2.<>s__4"" IL_0045: ldc.i4.3 IL_0046: ldelem.i4 IL_0047: stfld ""int Test.<F>d__2.<>s__2"" IL_004c: call ""System.Threading.Tasks.Task<int> Test.G()"" IL_0051: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0056: stloc.3 ~IL_0057: ldloca.s V_3 IL_0059: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_005e: brtrue.s IL_00a4 IL_0060: ldarg.0 IL_0061: ldc.i4.0 IL_0062: dup IL_0063: stloc.0 IL_0064: stfld ""int Test.<F>d__2.<>1__state"" <IL_0069: ldarg.0 IL_006a: ldloc.3 IL_006b: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_0070: ldarg.0 IL_0071: stloc.s V_4 IL_0073: ldarg.0 IL_0074: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_0079: ldloca.s V_3 IL_007b: ldloca.s V_4 IL_007d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<F>d__2>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<F>d__2)"" IL_0082: nop IL_0083: leave IL_0110 >IL_0088: ldarg.0 IL_0089: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_008e: stloc.3 IL_008f: ldarg.0 IL_0090: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_0095: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_009b: ldarg.0 IL_009c: ldc.i4.m1 IL_009d: dup IL_009e: stloc.0 IL_009f: stfld ""int Test.<F>d__2.<>1__state"" IL_00a4: ldarg.0 IL_00a5: ldloca.s V_3 IL_00a7: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00ac: stfld ""int Test.<F>d__2.<>s__3"" IL_00b1: ldarg.0 IL_00b2: ldfld ""int Test.<F>d__2.<>s__1"" IL_00b7: ldarg.0 IL_00b8: ldfld ""int[] Test.<F>d__2.<>s__4"" IL_00bd: ldc.i4.3 IL_00be: ldarg.0 IL_00bf: ldfld ""int Test.<F>d__2.<>s__2"" IL_00c4: ldarg.0 IL_00c5: ldfld ""int Test.<F>d__2.<>s__3"" IL_00ca: add IL_00cb: dup IL_00cc: stloc.2 IL_00cd: stelem.i4 IL_00ce: ldloc.2 IL_00cf: ldc.i4.4 IL_00d0: call ""int Test.H(int, int, int)"" IL_00d5: pop IL_00d6: ldarg.0 IL_00d7: ldnull IL_00d8: stfld ""int[] Test.<F>d__2.<>s__4"" -IL_00dd: ldc.i4.1 IL_00de: stloc.1 IL_00df: leave.s IL_00fb } catch System.Exception { ~IL_00e1: stloc.s V_5 IL_00e3: ldarg.0 IL_00e4: ldc.i4.s -2 IL_00e6: stfld ""int Test.<F>d__2.<>1__state"" IL_00eb: ldarg.0 IL_00ec: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_00f1: ldloc.s V_5 IL_00f3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00f8: nop IL_00f9: leave.s IL_0110 } -IL_00fb: ldarg.0 IL_00fc: ldc.i4.s -2 IL_00fe: stfld ""int Test.<F>d__2.<>1__state"" ~IL_0103: ldarg.0 IL_0104: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_0109: ldloc.1 IL_010a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_010f: nop IL_0110: ret }", sequencePoints: "Test+<F>d__2.MoveNext"); } [Fact] public void SpillSequencesRelease() { var source = @" using System.Threading.Tasks; public class Test { public static int H(int a, int b, int c) { return a; } public static Task<int> G() { return null; } public static async Task<int> F(int[] array) { H(array[1] += 2, array[3] += await G(), 4); return 1; } } "; var v = CompileAndVerify(source, options: TestOptions.ReleaseDll); v.VerifyIL("Test.<F>d__2.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 251 (0xfb) .maxstack 5 .locals init (int V_0, int V_1, int V_2, int V_3, System.Runtime.CompilerServices.TaskAwaiter<int> V_4, System.Exception V_5) ~IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__2.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_007d -IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""int[] Test.<F>d__2.array"" IL_0011: ldc.i4.1 IL_0012: ldelema ""int"" IL_0017: dup IL_0018: ldind.i4 IL_0019: ldc.i4.2 IL_001a: add IL_001b: dup IL_001c: stloc.3 IL_001d: stind.i4 IL_001e: ldloc.3 IL_001f: stfld ""int Test.<F>d__2.<>7__wrap1"" IL_0024: ldarg.0 IL_0025: ldarg.0 IL_0026: ldfld ""int[] Test.<F>d__2.array"" IL_002b: stfld ""int[] Test.<F>d__2.<>7__wrap3"" IL_0030: ldarg.0 IL_0031: ldfld ""int[] Test.<F>d__2.<>7__wrap3"" IL_0036: ldc.i4.3 IL_0037: ldelem.i4 IL_0038: pop IL_0039: ldarg.0 IL_003a: ldarg.0 IL_003b: ldfld ""int[] Test.<F>d__2.<>7__wrap3"" IL_0040: ldc.i4.3 IL_0041: ldelem.i4 IL_0042: stfld ""int Test.<F>d__2.<>7__wrap2"" IL_0047: call ""System.Threading.Tasks.Task<int> Test.G()"" IL_004c: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0051: stloc.s V_4 ~IL_0053: ldloca.s V_4 IL_0055: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_005a: brtrue.s IL_009a IL_005c: ldarg.0 IL_005d: ldc.i4.0 IL_005e: dup IL_005f: stloc.0 IL_0060: stfld ""int Test.<F>d__2.<>1__state"" <IL_0065: ldarg.0 IL_0066: ldloc.s V_4 IL_0068: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_006d: ldarg.0 IL_006e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_0073: ldloca.s V_4 IL_0075: ldarg.0 IL_0076: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<F>d__2>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<F>d__2)"" IL_007b: leave.s IL_00fa >IL_007d: ldarg.0 IL_007e: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_0083: stloc.s V_4 IL_0085: ldarg.0 IL_0086: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_008b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0091: ldarg.0 IL_0092: ldc.i4.m1 IL_0093: dup IL_0094: stloc.0 IL_0095: stfld ""int Test.<F>d__2.<>1__state"" IL_009a: ldloca.s V_4 IL_009c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00a1: stloc.2 IL_00a2: ldarg.0 IL_00a3: ldfld ""int Test.<F>d__2.<>7__wrap1"" IL_00a8: ldarg.0 IL_00a9: ldfld ""int[] Test.<F>d__2.<>7__wrap3"" IL_00ae: ldc.i4.3 IL_00af: ldarg.0 IL_00b0: ldfld ""int Test.<F>d__2.<>7__wrap2"" IL_00b5: ldloc.2 IL_00b6: add IL_00b7: dup IL_00b8: stloc.3 IL_00b9: stelem.i4 IL_00ba: ldloc.3 IL_00bb: ldc.i4.4 IL_00bc: call ""int Test.H(int, int, int)"" IL_00c1: pop IL_00c2: ldarg.0 IL_00c3: ldnull IL_00c4: stfld ""int[] Test.<F>d__2.<>7__wrap3"" -IL_00c9: ldc.i4.1 IL_00ca: stloc.1 IL_00cb: leave.s IL_00e6 } catch System.Exception { ~IL_00cd: stloc.s V_5 IL_00cf: ldarg.0 IL_00d0: ldc.i4.s -2 IL_00d2: stfld ""int Test.<F>d__2.<>1__state"" IL_00d7: ldarg.0 IL_00d8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_00dd: ldloc.s V_5 IL_00df: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00e4: leave.s IL_00fa } -IL_00e6: ldarg.0 IL_00e7: ldc.i4.s -2 IL_00e9: stfld ""int Test.<F>d__2.<>1__state"" ~IL_00ee: ldarg.0 IL_00ef: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_00f4: ldloc.1 IL_00f5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00fa: ret }", sequencePoints: "Test+<F>d__2.MoveNext"); } [Fact] public void SpillSequencesInConditionalExpression1() { var source = @" using System.Threading.Tasks; public class Test { public static int H(int a, int b, int c) { return a; } public static Task<int> G() { return null; } public static async Task<int> F(int[] array) { H(0, (1 == await G()) ? array[3] += await G() : 1, 4); return 1; } } "; CompileAndVerify(source, options: TestOptions.DebugDll); } [Fact] public void SpillSequencesInNullCoalescingOperator1() { var source = @" using System.Threading.Tasks; public class C { public static int H(int a, object b, int c) { return a; } public static object O(int a) { return null; } public static Task<int> G() { return null; } public static async Task<int> F(int[] array) { H(0, O(array[0] += await G()) ?? (array[1] += await G()), 4); return 1; } } "; CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { AssertEx.Equal(new[] { "<>1__state", "<>t__builder", "array", "<>7__wrap1", "<>7__wrap2", "<>u__1", "<>7__wrap3", "<>7__wrap4", }, module.GetFieldNames("C.<F>d__3")); }); CompileAndVerify(source, verify: Verification.Passes, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { AssertEx.Equal(new[] { "<>1__state", "<>t__builder", "array", "<>s__1", "<>s__2", "<>s__3", "<>s__4", "<>s__5", "<>s__6", "<>s__7", "<>u__1", "<>s__8" }, module.GetFieldNames("C.<F>d__3")); }); } [WorkItem(4628, "https://github.com/dotnet/roslyn/issues/4628")] [Fact] public void AsyncWithShortCircuiting001() { var source = @" using System; using System.Threading.Tasks; namespace AsyncConditionalBug { class Program { private readonly bool b=true; private async Task AsyncMethod() { Console.WriteLine(b && await Task.FromResult(false)); Console.WriteLine(b); } static void Main(string[] args) { new Program().AsyncMethod().Wait(); } } }"; var expected = @" False True "; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(4628, "https://github.com/dotnet/roslyn/issues/4628")] [Fact] public void AsyncWithShortCircuiting002() { var source = @" using System; using System.Threading.Tasks; namespace AsyncConditionalBug { class Program { private static readonly bool b=true; private async Task AsyncMethod() { Console.WriteLine(b && await Task.FromResult(false)); Console.WriteLine(b); } static void Main(string[] args) { new Program().AsyncMethod().Wait(); } } }"; var expected = @" False True "; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(4628, "https://github.com/dotnet/roslyn/issues/4628")] [Fact] public void AsyncWithShortCircuiting003() { var source = @" using System; using System.Threading.Tasks; namespace AsyncConditionalBug { class Program { private readonly string NULL = null; private async Task AsyncMethod() { Console.WriteLine(NULL ?? await Task.FromResult(""hello"")); Console.WriteLine(NULL); } static void Main(string[] args) { new Program().AsyncMethod().Wait(); } } }"; var expected = @" hello "; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(4638, "https://github.com/dotnet/roslyn/issues/4638")] [Fact] public void AsyncWithShortCircuiting004() { var source = @" using System; using System.Threading.Tasks; namespace AsyncConditionalBug { class Program { static void Main(string[] args) { try { DoSomething(Tuple.Create(1.ToString(), Guid.NewGuid())).GetAwaiter().GetResult(); } catch (Exception ex) { System.Console.Write(ex.Message); } } public static async Task DoSomething(Tuple<string, Guid> item) { if (item.Item2 != null || await IsValid(item.Item2)) { throw new Exception(""Not Valid!""); }; } private static async Task<bool> IsValid(Guid id) { return false; } } }"; var expected = @" Not Valid! "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void SpillSequencesInLogicalBinaryOperator1() { var source = @" using System.Threading.Tasks; public class Test { public static int H(int a, bool b, int c) { return a; } public static bool B(int a) { return true; } public static Task<int> G() { return null; } public static async Task<int> F(int[] array) { H(0, B(array[0] += await G()) || B(array[1] += await G()), 4); return 1; } } "; CompileAndVerify(source, options: TestOptions.DebugDll); } [Fact] public void SpillArray01() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { tests++; int[] arr = new int[await GetVal(4)]; if (arr.Length == 4) Driver.Count++; //multidimensional tests++; decimal[,] arr2 = new decimal[await GetVal(4), await GetVal(4)]; if (arr2.Rank == 2 && arr2.Length == 16) Driver.Count++; arr2 = new decimal[4, await GetVal(4)]; if (arr2.Rank == 2 && arr2.Length == 16) Driver.Count++; tests++; arr2 = new decimal[await GetVal(4), 4]; if (arr2.Rank == 2 && arr2.Length == 16) Driver.Count++; //jagged array tests++; decimal?[][] arr3 = new decimal?[await GetVal(4)][]; if (arr3.Rank == 2 && arr3.Length == 4) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray02_1() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { tests++; int[] arr = new int[await GetVal(4)]; if (arr.Length == 4) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray02_2() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { int[] arr = new int[4]; tests++; arr[0] = await GetVal(4); if (arr[0] == 4) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray02_3() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { int[] arr = new int[4]; arr[0] = 4; tests++; arr[0] += await GetVal(4); if (arr[0] == 8) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray02_4() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { int[] arr = new int[] { 8, 0, 0, 0 }; tests++; arr[1] += await (GetVal(arr[0])); if (arr[1] == 8) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray02_5() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { int[] arr = new int[] { 8, 8, 0, 0 }; tests++; arr[1] += await (GetVal(arr[await GetVal(0)])); if (arr[1] == 16) Driver.Count++; tests++; arr[await GetVal(2)]++; if (arr[2] == 1) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray02_6() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { int[] arr = new int[4]; tests++; arr[await GetVal(2)]++; if (arr[2] == 1) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray03() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { int[,] arr = new int[await GetVal(4), await GetVal(4)]; tests++; arr[0, 0] = await GetVal(4); if (arr[0, await (GetVal(0))] == 4) Driver.Count++; tests++; arr[0, 0] += await GetVal(4); if (arr[0, 0] == 8) Driver.Count++; tests++; arr[1, 1] += await (GetVal(arr[0, 0])); if (arr[1, 1] == 8) Driver.Count++; tests++; arr[1, 1] += await (GetVal(arr[0, await GetVal(0)])); if (arr[1, 1] == 16) Driver.Count++; tests++; arr[2, await GetVal(2)]++; if (arr[2, 2] == 1) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray04() { var source = @" using System.Threading; using System.Threading.Tasks; using System; struct MyStruct<T> { T t { get; set; } public T this[T index] { get { return t; } set { t = value; } } } struct TestCase { public async void Run() { try { MyStruct<int> ms = new MyStruct<int>(); var x = ms[index: await Goo()]; } finally { Driver.CompletedSignal.Set(); } } public async Task<int> Goo() { await Task.Delay(1); return 1; } } class Driver { public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); } }"; CompileAndVerify(source, ""); } [Fact] public void SpillArrayAssign() { var source = @" using System; using System.Threading.Tasks; class TestCase { static int[] arr = new int[4]; static async Task Run() { arr[0] = await Task.Factory.StartNew(() => 42); } static void Main() { Task task = Run(); task.Wait(); Console.WriteLine(arr[0]); } }"; var expected = @" 42 "; CompileAndVerify(source, expected); } [WorkItem(19609, "https://github.com/dotnet/roslyn/issues/19609")] [Fact] public void SpillArrayAssign2() { var source = @" using System.Threading.Tasks; class Program { static int[] array = new int[5]; static void Main(string[] args) { try { System.Console.WriteLine(""test not awaited""); TestNotAwaited().Wait(); } catch { System.Console.WriteLine(""exception thrown""); } System.Console.WriteLine(); try { System.Console.WriteLine(""test awaited""); TestAwaited().Wait(); } catch { System.Console.WriteLine(""exception thrown""); } } static async Task TestNotAwaited() { array[6] = Moo1(); } static async Task TestAwaited() { array[6] = await Moo(); } static int Moo1() { System.Console.WriteLine(""hello""); return 123; } static async Task<int> Moo() { System.Console.WriteLine(""hello""); return 123; } }"; var expected = @" test not awaited hello exception thrown test awaited hello exception thrown "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void SpillArrayLocal() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int[] arr = new int[2] { -1, 42 }; int tests = 0; try { tests++; int t1 = arr[await GetVal(1)]; if (t1 == 42) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArrayCompoundAssignmentLValue() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class Driver { static int[] arr; static async Task Run() { arr = new int[1]; arr[0] += await Task.Factory.StartNew(() => 42); } static void Main() { Run().Wait(); Console.WriteLine(arr[0]); } }"; var expected = @" 42 "; CompileAndVerify(source, expected); } [Fact] public void SpillArrayCompoundAssignmentLValueAwait() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class Driver { static int[] arr; static async Task Run() { arr = new int[1]; arr[await Task.Factory.StartNew(() => 0)] += await Task.Factory.StartNew(() => 42); } static void Main() { Run().Wait(); Console.WriteLine(arr[0]); } }"; var expected = @" 42 "; CompileAndVerify(source, expected); } [Fact] public void SpillArrayCompoundAssignmentLValueAwait2() { var source = @" using System; using System.Threading; using System.Threading.Tasks; struct S1 { public int x; } struct S2 { public S1 s1; } class Driver { static async Task<int> Run() { var arr = new S2[1]; arr[await Task.Factory.StartNew(() => 0)].s1.x += await Task.Factory.StartNew(() => 42); return arr[await Task.Factory.StartNew(() => 0)].s1.x; } static void Main() { var t = Run(); t.Wait(); Console.WriteLine(t.Result); } }"; var expected = @" 42 "; CompileAndVerify(source, expected); } [Fact] public void DoubleSpillArrayCompoundAssignment() { var source = @" using System; using System.Threading; using System.Threading.Tasks; struct S1 { public int x; } struct S2 { public S1 s1; } class Driver { static async Task<int> Run() { var arr = new S2[1]; arr[await Task.Factory.StartNew(() => 0)].s1.x += (arr[await Task.Factory.StartNew(() => 0)].s1.x += await Task.Factory.StartNew(() => 42)); return arr[await Task.Factory.StartNew(() => 0)].s1.x; } static void Main() { var t = Run(); t.Wait(); Console.WriteLine(t.Result); } }"; var expected = @" 42 "; CompileAndVerify(source, expected); } [Fact] public void SpillArrayInitializers1() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run() { int tests = 0; try { //jagged array tests++; int[][] arr1 = new[] { new []{await GetVal(2),await GetVal(3)}, new []{4,await GetVal(5),await GetVal(6)} }; if (arr1[0][1] == 3 && arr1[1][1] == 5 && arr1[1][2] == 6) Driver.Count++; tests++; int[][] arr2 = new[] { new []{await GetVal(2),await GetVal(3)}, await Goo() }; if (arr2[0][1] == 3 && arr2[1][1] == 2) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } public async Task<int[]> Goo() { await Task.Delay(1); return new int[] { 1, 2, 3 }; } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArrayInitializers2() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run() { int tests = 0; try { //jagged array tests++; int[,] arr1 = { {await GetVal(2),await GetVal(3)}, {await GetVal(5),await GetVal(6)} }; if (arr1[0, 1] == 3 && arr1[1, 0] == 5 && arr1[1, 1] == 6) Driver.Count++; tests++; int[,] arr2 = { {await GetVal(2),3}, {4,await GetVal(5)} }; if (arr2[0, 1] == 3 && arr2[1, 1] == 5) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArrayInitializers3() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run() { int tests = 0; try { //jagged array tests++; int[][] arr1 = new[] { new []{await GetVal(2),await Task.Run<int>(async()=>{await Task.Delay(1);return 3;})}, new []{await GetVal(5),4,await Task.Run<int>(async()=>{await Task.Delay(1);return 6;})} }; if (arr1[0][1] == 3 && arr1[1][1] == 4 && arr1[1][2] == 6) Driver.Count++; tests++; dynamic arr2 = new[] { new []{await GetVal(2),3}, await Goo() }; if (arr2[0][1] == 3 && arr2[1][1] == 2) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } public async Task<int[]> Goo() { await Task.Delay(1); return new int[] { 1, 2, 3 }; } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected, references: new[] { CSharpRef }); } [Fact] public void SpillNestedExpressionInArrayInitializer() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<int[,]> Run() { return new int[,] { {1, 2, 21 + (await Task.Factory.StartNew(() => 21)) }, }; } public static void Main() { var t = Run(); t.Wait(); foreach (var xs in t.Result) { Console.WriteLine(xs); } } }"; var expected = @" 1 2 42 "; CompileAndVerify(source, expected); } [Fact] public void SpillConditionalAccess() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Test { class C1 { public int M(int x) { return x; } } public static int Get(int x) { Console.WriteLine(""> "" + x); return x; } public static async Task<int> F(int x) { return await Task.Factory.StartNew(() => x); } public static async Task<int?> G() { var c = new C1(); return c?.M(await F(Get(42))); } public static void Main() { var t = G(); System.Console.WriteLine(t.Result); } }"; var expected = @" > 42 42"; CompileAndVerify(source, expected); } [Fact] public void AssignToAwait() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class S { public int x = -1; } class Test { static S _s = new S(); public static async Task<S> GetS() { return await Task.Factory.StartNew(() => _s); } public static async Task Run() { (await GetS()).x = 42; Console.WriteLine(_s.x); } } class Driver { static void Main() { Test.Run().Wait(); } }"; var expected = @" 42 "; CompileAndVerify(source, expected); } [Fact] public void AssignAwaitToAwait() { var source = @" using System; using System.Threading.Tasks; class S { public int x = -1; } class Test { static S _s = new S(); public static async Task<S> GetS() { return await Task.Factory.StartNew(() => _s); } public static async Task Run() { (await GetS()).x = await Task.Factory.StartNew(() => 42); Console.WriteLine(_s.x); } } class Driver { static void Main() { Test.Run().Wait(); } }"; var expected = @" 42 "; CompileAndVerify(source, expected); } [ConditionalFact(typeof(DesktopOnly))] public void SpillArglist() { var source = @" using System; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; class TestCase { static StringBuilder sb = new StringBuilder(); public async Task Run() { try { Bar(__arglist(One(), await Two())); if (sb.ToString() == ""OneTwo"") Driver.Result = 0; } finally { Driver.CompleteSignal.Set(); } } int One() { sb.Append(""One""); return 1; } async Task<int> Two() { await Task.Delay(1); sb.Append(""Two""); return 2; } void Bar(__arglist) { var ai = new ArgIterator(__arglist); while (ai.GetRemainingCount() > 0) Console.WriteLine( __refvalue(ai.GetNextArg(), int)); } } class Driver { static public AutoResetEvent CompleteSignal = new AutoResetEvent(false); public static int Result = -1; public static void Main() { TestCase tc = new TestCase(); tc.Run(); CompleteSignal.WaitOne(); Console.WriteLine(Result); } }"; var expected = @" 1 2 0 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void SpillObjectInitializer1() { var source = @" using System; using System.Collections; using System.Threading; using System.Threading.Tasks; struct TestCase : IEnumerable { int X; public async Task Run() { int test = 0; int count = 0; try { test++; var x = new TestCase { X = await Bar() }; if (x.X == 1) count++; } finally { Driver.Result = test - count; Driver.CompleteSignal.Set(); } } async Task<int> Bar() { await Task.Delay(1); return 1; } public IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } } class Driver { static public AutoResetEvent CompleteSignal = new AutoResetEvent(false); public static int Result = -1; public static void Main() { TestCase tc = new TestCase(); tc.Run(); CompleteSignal.WaitOne(); Console.WriteLine(Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void SpillWithByRefArguments01() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class BaseTestCase { public void GooRef(ref decimal d, int x, out decimal od) { od = d; d++; } public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } } class TestCase : BaseTestCase { public async void Run() { int tests = 0; try { decimal d = 1; decimal od; tests++; base.GooRef(ref d, await base.GetVal(4), out od); if (d == 2 && od == 1) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void SpillOperator_Compound1() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run() { int tests = 0; try { tests++; int[] x = new int[] { 1, 2, 3, 4 }; x[await GetVal(0)] += await GetVal(4); if (x[0] == 5) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void SpillOperator_Compound2() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run() { int tests = 0; try { tests++; int[] x = new int[] { 1, 2, 3, 4 }; x[await GetVal(0)] += await GetVal(4); if (x[0] == 5) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Async_StackSpill_Argument_Generic04() { var source = @" using System; using System.Threading.Tasks; public class mc<T> { async public System.Threading.Tasks.Task<dynamic> Goo<V>(T t, V u) { await Task.Delay(1); return u; } } class Test { static async Task<int> Goo() { dynamic mc = new mc<string>(); var rez = await mc.Goo<string>(null, await ((Func<Task<string>>)(async () => { await Task.Delay(1); return ""Test""; }))()); if (rez == ""Test"") return 0; return 1; } static void Main() { Console.WriteLine(Goo().Result); } }"; CompileAndVerify(source, "0", references: new[] { CSharpRef }); } [Fact] public void AsyncStackSpill_assign01() { var source = @" using System; using System.Threading; using System.Threading.Tasks; struct TestCase { private int val; public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run() { int tests = 0; try { tests++; int[] x = new int[] { 1, 2, 3, 4 }; val = x[await GetVal(0)] += await GetVal(4); if (x[0] == 5 && val == await GetVal(5)) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void SpillCollectionInitializer() { var source = @" using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; struct PrivateCollection : IEnumerable { public List<int> lst; //public so we can check the values public void Add(int x) { if (lst == null) lst = new List<int>(); lst.Add(x); } public IEnumerator GetEnumerator() { return lst as IEnumerator; } } class TestCase { public async Task<T> GetValue<T>(T x) { await Task.Delay(1); return x; } public async void Run() { int tests = 0; try { tests++; var myCol = new PrivateCollection() { await GetValue(1), await GetValue(2) }; if (myCol.lst[0] == 1 && myCol.lst[1] == 2) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test completes, set the flag. Driver.CompletedSignal.Set(); } } public int Goo { get; set; } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void SpillRefExpr() { var source = @" using System; using System.Threading.Tasks; class MyClass { public int Field; } class TestCase { public static int Goo(ref int x, int y) { return x + y; } public async Task<int> Run() { return Goo( ref (new MyClass() { Field = 21 }.Field), await Task.Factory.StartNew(() => 21)); } } static class Driver { static void Main() { var t = new TestCase().Run(); t.Wait(); Console.WriteLine(t.Result); } }"; CompileAndVerify(source, "42"); } [Fact] public void SpillManagedPointerAssign03() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } class PrivClass { internal struct ValueT { public int Field; } internal ValueT[] arr = new ValueT[3]; } private PrivClass myClass; public async void Run() { int tests = 0; this.myClass = new PrivClass(); try { tests++; this.myClass.arr[0].Field = await GetVal(4); if (myClass.arr[0].Field == 4) Driver.Count++; tests++; this.myClass.arr[0].Field += await GetVal(4); if (myClass.arr[0].Field == 8) Driver.Count++; tests++; this.myClass.arr[await GetVal(1)].Field += await GetVal(4); if (myClass.arr[1].Field == 4) Driver.Count++; tests++; this.myClass.arr[await GetVal(1)].Field++; if (myClass.arr[1].Field == 5) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact, WorkItem(36443, "https://github.com/dotnet/roslyn/issues/36443")] public void SpillCompoundAssignmentToNullableMemberOfLocal_01() { var source = @" using System; using System.Threading.Tasks; struct S { int? i; static async Task Main() { S s = default; Console.WriteLine(s.i += await GetInt()); } static Task<int?> GetInt() => Task.FromResult((int?)1); }"; CompileAndVerify(source, expectedOutput: "", options: TestOptions.ReleaseExe); CompileAndVerify(source, expectedOutput: "", options: TestOptions.DebugExe); } [Fact, WorkItem(36443, "https://github.com/dotnet/roslyn/issues/36443")] public void SpillCompoundAssignmentToNullableMemberOfLocal_02() { var source = @" class C { static async System.Threading.Tasks.Task Main() { await new C().M(); } int field = 1; async System.Threading.Tasks.Task M() { this.field += await M2(); System.Console.Write(this.field); } async System.Threading.Tasks.Task<int> M2() { await System.Threading.Tasks.Task.Yield(); return 42; } } "; CompileAndVerify(source, expectedOutput: "43", options: TestOptions.DebugExe); CompileAndVerify(source, expectedOutput: "43", options: TestOptions.ReleaseExe); } [Fact, WorkItem(36443, "https://github.com/dotnet/roslyn/issues/36443")] public void SpillCompoundAssignmentToNullableMemberOfLocal_03() { var source = @" class C { static async System.Threading.Tasks.Task Main() { await new C().M(); } int? field = 1; async System.Threading.Tasks.Task M() { this.field += await M2(); System.Console.Write(this.field); } async System.Threading.Tasks.Task<int?> M2() { await System.Threading.Tasks.Task.Yield(); return 42; } } "; CompileAndVerify(source, expectedOutput: "43", options: TestOptions.ReleaseExe); CompileAndVerify(source, expectedOutput: "43", options: TestOptions.DebugExe); } [Fact, WorkItem(36443, "https://github.com/dotnet/roslyn/issues/36443")] public void SpillCompoundAssignmentToNullableMemberOfLocal_04() { var source = @" using System; using System.Threading.Tasks; struct S { int? i; static async Task M(S s = default) { s = default; Console.WriteLine(s.i += await GetInt()); } static async Task Main() { M(); } static Task<int?> GetInt() => Task.FromResult((int?)1); }"; CompileAndVerify(source, expectedOutput: "", options: TestOptions.ReleaseExe); CompileAndVerify(source, expectedOutput: "", options: TestOptions.DebugExe); } [Fact] public void SpillSacrificialRead() { var source = @" using System; using System.Threading.Tasks; class C { static void F1(ref int x, int y, int z) { x += y + z; } static int F0() { Console.WriteLine(-1); return 0; } static async Task<int> F2() { int[] x = new int[1] { 21 }; x = null; F1(ref x[0], F0(), await Task.Factory.StartNew(() => 21)); return x[0]; } public static void Main() { var t = F2(); try { t.Wait(); } catch(Exception e) { Console.WriteLine(0); return; } Console.WriteLine(-1); } }"; CompileAndVerify(source, "0"); } [Fact] public void SpillRefThisStruct() { var source = @" using System; using System.Threading.Tasks; struct s1 { public int X; public async void Goo1() { Bar(ref this, await Task<int>.FromResult(42)); } public void Goo2() { Bar(ref this, 42); } public void Bar(ref s1 x, int y) { x.X = 42; } } class c1 { public int X; public async void Goo1() { Bar(this, await Task<int>.FromResult(42)); } public void Goo2() { Bar(this, 42); } public void Bar(c1 x, int y) { x.X = 42; } } class C { public static void Main() { { s1 s; s.X = -1; s.Goo1(); Console.WriteLine(s.X); } { s1 s; s.X = -1; s.Goo2(); Console.WriteLine(s.X); } { c1 c = new c1(); c.X = -1; c.Goo1(); Console.WriteLine(c.X); } { c1 c = new c1(); c.X = -1; c.Goo2(); Console.WriteLine(c.X); } } }"; var expected = @" -1 42 42 42 "; CompileAndVerify(source, expected); } [Fact] [WorkItem(13734, "https://github.com/dotnet/roslyn/issues/13734")] public void MethodGroupConversionNoSpill() { string source = @" using System.Threading.Tasks; using System; public class AsyncBug { public static void Main() { Boom().GetAwaiter().GetResult(); } public static async Task Boom() { Func<Type> f = (await Task.FromResult(1)).GetType; Console.WriteLine(f()); } } "; var v = CompileAndVerify(source, "System.Int32"); } [Fact] [WorkItem(13734, "https://github.com/dotnet/roslyn/issues/13734")] public void MethodGroupConversionWithSpill() { string source = @" using System.Threading.Tasks; using System; using System.Linq; using System.Collections.Generic; namespace AsyncBug { class Program { private class SomeClass { public bool Method(int value) { return value % 2 == 0; } } private async Task<SomeClass> Danger() { await Task.Yield(); return new SomeClass(); } private async Task<IEnumerable<bool>> Killer() { return (new int[] {1, 2, 3, 4, 5}).Select((await Danger()).Method); } static void Main(string[] args) { foreach (var b in new Program().Killer().GetAwaiter().GetResult()) { Console.WriteLine(b); } } } } "; var expected = new bool[] { false, true, false, true, false }.Aggregate("", (str, next) => str += $"{next}{Environment.NewLine}"); var v = CompileAndVerify(source, expected); } [Fact] [WorkItem(17706, "https://github.com/dotnet/roslyn/issues/17706")] public void SpillAwaitBeforeRefReordered() { string source = @" using System.Threading.Tasks; public class C { private static int i; static ref int P => ref i; static void Assign(ref int first, int second) { first = second; } public static async Task M(Task<int> t) { // OK: await goes before the ref Assign(second: await t, first: ref P); } public static void Main() { M(Task.FromResult(42)).Wait(); System.Console.WriteLine(i); } } "; var v = CompileAndVerify(source, "42"); } [Fact] [WorkItem(17706, "https://github.com/dotnet/roslyn/issues/17706")] public void SpillRefBeforeAwaitReordered() { string source = @" using System.Threading.Tasks; public class C { private static int i; static ref int P => ref i; static void Assign(int first, ref int second) { second = first; } public static async Task M(Task<int> t) { // ERROR: await goes after the ref Assign(second: ref P, first: await t); } public static void Main() { M(Task.FromResult(42)).Wait(); System.Console.WriteLine(i); } } "; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe); comp.VerifyEmitDiagnostics( // (18,28): error CS8178: 'await' cannot be used in an expression containing a call to 'C.P.get' because it returns by reference // Assign(second: ref P, first: await t); Diagnostic(ErrorCode.ERR_RefReturningCallAndAwait, "P").WithArguments("C.P.get").WithLocation(18, 28) ); } [Fact] [WorkItem(27831, "https://github.com/dotnet/roslyn/issues/27831")] public void AwaitWithInParameter_ArgModifier() { CreateCompilation(@" using System.Threading.Tasks; class Foo { async Task A(string s, Task<int> task) { C(in s, await task); } void C(in object obj, int length) {} }").VerifyDiagnostics( // (7,14): error CS1503: Argument 1: cannot convert from 'in string' to 'in object' // C(in s, await task); Diagnostic(ErrorCode.ERR_BadArgType, "s").WithArguments("1", "in string", "in object").WithLocation(7, 14)); } [Fact] [WorkItem(27831, "https://github.com/dotnet/roslyn/issues/27831")] public void AwaitWithInParameter_NoArgModifier() { CompileAndVerify(@" using System; using System.Threading.Tasks; class Foo { static async Task Main() { await A(""test"", Task.FromResult(4)); } static async Task A(string s, Task<int> task) { B(s, await task); } static void B(in object obj, int v) { Console.WriteLine(obj); Console.WriteLine(v); } }", expectedOutput: @" test 4 "); } [Fact, WorkItem(36856, "https://github.com/dotnet/roslyn/issues/36856")] public void Crash36856() { var source = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { } private static async Task Serialize() { System.Text.Json.Serialization.JsonSerializer.Parse<string>(await TestAsync()); } private static Task<byte[]> TestAsync() { return null; } } namespace System { public readonly ref struct ReadOnlySpan<T> { public static implicit operator ReadOnlySpan<T>(T[] array) { throw null; } } } namespace System.Text.Json.Serialization { public static class JsonSerializer { public static TValue Parse<TValue>(ReadOnlySpan<byte> utf8Json, JsonSerializerOptions options = null) { throw null; } } public sealed class JsonSerializerOptions { } } "; var v = CompileAndVerify(source, options: TestOptions.DebugExe); v.VerifyIL("Program.<Serialize>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 184 (0xb8) .maxstack 3 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter<byte[]> V_1, Program.<Serialize>d__1 V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Serialize>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_0047 IL_000e: nop IL_000f: call ""System.Threading.Tasks.Task<byte[]> Program.TestAsync()"" IL_0014: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<byte[]> System.Threading.Tasks.Task<byte[]>.GetAwaiter()"" IL_0019: stloc.1 IL_001a: ldloca.s V_1 IL_001c: call ""bool System.Runtime.CompilerServices.TaskAwaiter<byte[]>.IsCompleted.get"" IL_0021: brtrue.s IL_0063 IL_0023: ldarg.0 IL_0024: ldc.i4.0 IL_0025: dup IL_0026: stloc.0 IL_0027: stfld ""int Program.<Serialize>d__1.<>1__state"" IL_002c: ldarg.0 IL_002d: ldloc.1 IL_002e: stfld ""System.Runtime.CompilerServices.TaskAwaiter<byte[]> Program.<Serialize>d__1.<>u__1"" IL_0033: ldarg.0 IL_0034: stloc.2 IL_0035: ldarg.0 IL_0036: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Serialize>d__1.<>t__builder"" IL_003b: ldloca.s V_1 IL_003d: ldloca.s V_2 IL_003f: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<byte[]>, Program.<Serialize>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<byte[]>, ref Program.<Serialize>d__1)"" IL_0044: nop IL_0045: leave.s IL_00b7 IL_0047: ldarg.0 IL_0048: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<byte[]> Program.<Serialize>d__1.<>u__1"" IL_004d: stloc.1 IL_004e: ldarg.0 IL_004f: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<byte[]> Program.<Serialize>d__1.<>u__1"" IL_0054: initobj ""System.Runtime.CompilerServices.TaskAwaiter<byte[]>"" IL_005a: ldarg.0 IL_005b: ldc.i4.m1 IL_005c: dup IL_005d: stloc.0 IL_005e: stfld ""int Program.<Serialize>d__1.<>1__state"" IL_0063: ldarg.0 IL_0064: ldloca.s V_1 IL_0066: call ""byte[] System.Runtime.CompilerServices.TaskAwaiter<byte[]>.GetResult()"" IL_006b: stfld ""byte[] Program.<Serialize>d__1.<>s__1"" IL_0070: ldarg.0 IL_0071: ldfld ""byte[] Program.<Serialize>d__1.<>s__1"" IL_0076: call ""System.ReadOnlySpan<byte> System.ReadOnlySpan<byte>.op_Implicit(byte[])"" IL_007b: ldnull IL_007c: call ""string System.Text.Json.Serialization.JsonSerializer.Parse<string>(System.ReadOnlySpan<byte>, System.Text.Json.Serialization.JsonSerializerOptions)"" IL_0081: pop IL_0082: ldarg.0 IL_0083: ldnull IL_0084: stfld ""byte[] Program.<Serialize>d__1.<>s__1"" IL_0089: leave.s IL_00a3 } catch System.Exception { IL_008b: stloc.3 IL_008c: ldarg.0 IL_008d: ldc.i4.s -2 IL_008f: stfld ""int Program.<Serialize>d__1.<>1__state"" IL_0094: ldarg.0 IL_0095: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Serialize>d__1.<>t__builder"" IL_009a: ldloc.3 IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a0: nop IL_00a1: leave.s IL_00b7 } IL_00a3: ldarg.0 IL_00a4: ldc.i4.s -2 IL_00a6: stfld ""int Program.<Serialize>d__1.<>1__state"" IL_00ab: ldarg.0 IL_00ac: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Serialize>d__1.<>t__builder"" IL_00b1: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b6: nop IL_00b7: ret } ", sequencePoints: "Program.Serialize"); } [Fact, WorkItem(37461, "https://github.com/dotnet/roslyn/issues/37461")] public void ShouldNotSpillStackallocToField_01() { var source = @" using System; using System.Threading.Tasks; public class P { static async Task Main() { await Async1(F1(), G(F2(), stackalloc int[] { 40, 500, 6000 })); } static int F1() => 70000; static int F2() => 800000; static int G(int k, Span<int> span) => k + span.Length + span[0] + span[1] + span[2]; static Task Async1(int k, int i) { Console.WriteLine(k + i); return Task.Delay(1); } } "; var expectedOutput = @"876543"; var comp = CreateCompilationWithMscorlibAndSpan(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var v = CompileAndVerify( compilation: comp, expectedOutput: expectedOutput, verify: Verification.Fails // localloc is not verifiable. ); comp = CreateCompilationWithMscorlibAndSpan(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); v = CompileAndVerify( compilation: comp, expectedOutput: expectedOutput, verify: Verification.Fails // localloc is not verifiable. ); } [Fact, WorkItem(37461, "https://github.com/dotnet/roslyn/issues/37461")] public void ShouldNotSpillStackallocToField_02() { var source = @" using System; using System.Threading.Tasks; public class P { static async Task Main() { await Async1(F1(), G(F2(), stackalloc int[] { 40, await Task.FromResult(500), 6000 })); } static int F1() => 70000; static int F2() => 800000; static int G(int k, Span<int> span) => k + span.Length + span[0] + span[1] + span[2]; static Task Async1(int k, int i) { Console.WriteLine(k + i); return Task.Delay(1); } } "; var expectedOutput = @"876543"; var comp = CreateCompilationWithMscorlibAndSpan(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var v = CompileAndVerify( compilation: comp, expectedOutput: expectedOutput, verify: Verification.Fails // localloc is not verifiable. ); comp = CreateCompilationWithMscorlibAndSpan(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); v = CompileAndVerify( compilation: comp, expectedOutput: expectedOutput, verify: Verification.Fails // localloc is not verifiable. ); } [Fact, WorkItem(37461, "https://github.com/dotnet/roslyn/issues/37461")] public void ShouldNotSpillStackallocToField_03() { var source = @" using System; using System.Threading.Tasks; public class P { static async Task Main() { await Async1(F1(), G(F2(), stackalloc int[] { 1, 2, 3 }, await F3())); } static object F1() => 1; static object F2() => 1; static Task<object> F3() => Task.FromResult<object>(1); static int G(object obj, Span<int> span, object o2) => span.Length; static async Task Async1(Object obj, int i) { await Task.Delay(1); } } "; foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe }) { var comp = CreateCompilationWithMscorlibAndSpan(source, options: options); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (9,66): error CS4007: 'await' cannot be used in an expression containing the type 'System.Span<int>' // await Async1(F1(), G(F2(), stackalloc int[] { 1, 2, 3 }, await F3())); Diagnostic(ErrorCode.ERR_ByRefTypeAndAwait, "await F3()").WithArguments("System.Span<int>").WithLocation(9, 66) ); } } [Fact] public void SpillStateMachineTemps() { var source = @"using System; using System.Threading.Tasks; public class C { public static void Main() { Console.WriteLine(M1(new Q(), SF()).Result); } public static async Task<int> M1(object o, Task<bool> c) { return o switch { Q { F: { P1: true } } when await c => 1, // cached Q.F is alive Q { F: { P2: true } } => 2, _ => 3, }; } public static async Task<bool> SF() { await Task.Delay(10); return false; } } class Q { public F F => new F(true); } struct F { bool _result; public F(bool result) { _result = result; } public bool P1 => _result; public bool P2 => _result; } "; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "2"); CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: "2"); } [Fact] [WorkItem(37713, "https://github.com/dotnet/roslyn/issues/37713")] public void RefStructInAsyncStateMachineWithWhenClause() { var source = @" using System.Threading.Tasks; class Program { async Task<int> M1(object o, Task<bool> c, int r) { return o switch { Q { F: { P1: true } } when await c => r, // error: cached Q.F is alive Q { F: { P2: true } } => 2, _ => 3, }; } async Task<int> M2(object o, Task<bool> c, int r) { return o switch { Q { F: { P1: true } } when await c => r, // ok: only Q.P1 is live Q { F: { P1: true } } => 2, _ => 3, }; } async Task<int> M3(object o, bool c, Task<int> r) { return o switch { Q { F: { P1: true } } when c => await r, // ok: nothing alive at await Q { F: { P2: true } } => 2, _ => 3, }; } async Task<int> M4(object o, Task<bool> c, int r) { return o switch { Q { F: { P1: true } } when await c => r, // ok: no switch state is alive _ => 3, }; } } public class Q { public S F => throw null!; } public ref struct S { public bool P1 => true; public bool P2 => true; } "; CreateCompilation(source, options: TestOptions.DebugDll).VerifyDiagnostics().VerifyEmitDiagnostics( // (9,17): error CS4013: Instance of type 'S' cannot be used inside a nested function, query expression, iterator block or async method // Q { F: { P1: true } } when await c => r, // error: cached Q.F is alive Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "F").WithArguments("S").WithLocation(9, 17) ); CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics().VerifyEmitDiagnostics( // (9,17): error CS4013: Instance of type 'S' cannot be used inside a nested function, query expression, iterator block or async method // Q { F: { P1: true } } when await c => r, // error: cached Q.F is alive Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "F").WithArguments("S").WithLocation(9, 17) ); } [Fact] [WorkItem(37783, "https://github.com/dotnet/roslyn/issues/37783")] public void ExpressionLambdaWithObjectInitializer() { var source = @"using System; using System.Linq.Expressions; using System.Threading.Tasks; class Program { public static async Task Main() { int value = 42; Console.WriteLine(await M(() => new Box<int>() { Value = value })); } static Task<int> M(Expression<Func<Box<int>>> e) { return Task.FromResult(e.Compile()().Value); } } class Box<T> { public T Value; } "; CompileAndVerify(source, expectedOutput: "42", options: TestOptions.DebugExe); CompileAndVerify(source, expectedOutput: "42", options: TestOptions.ReleaseExe); } [Fact] [WorkItem(38309, "https://github.com/dotnet/roslyn/issues/38309")] public void ExpressionLambdaWithUserDefinedControlFlow() { var source = @"using System; using System.Linq.Expressions; using System.Threading.Tasks; namespace RoslynFailFastReproduction { static class Program { static async Task Main(string[] args) { await MainAsync(args); } static async Task MainAsync(string[] args) { Expression<Func<AltBoolean, AltBoolean>> expr = x => x && x; var result = await Task.FromResult(true); Console.WriteLine(result); } class AltBoolean { public static AltBoolean operator &(AltBoolean x, AltBoolean y) => default; public static bool operator true(AltBoolean x) => default; public static bool operator false(AltBoolean x) => default; } } } "; CompileAndVerify(source, expectedOutput: "True", options: TestOptions.DebugExe); CompileAndVerify(source, expectedOutput: "True", options: TestOptions.ReleaseExe); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_ClassFieldAccessOnProperty() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a) { a.B.x = await Write(""RHS""); } static async Task Main(string[] args) { await TestPropertyAccessThrows(); await TestFieldAccessThrows(); await TestPropertyAccessSucceeds(); } static async Task TestPropertyAccessThrows() { Console.WriteLine(nameof(TestPropertyAccessThrows)); A a = null; Console.WriteLine(""Before Assignment""); try { await Assign(a); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestFieldAccessThrows() { Console.WriteLine(nameof(TestFieldAccessThrows)); var a = new A(); Console.WriteLine(""Before Assignment""); try { await Assign(a); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestPropertyAccessSucceeds() { Console.WriteLine(nameof(TestPropertyAccessSucceeds)); var a = new A{ B = new B() }; Console.WriteLine(""Before Assignment a.B.x is: "" + a.B.x); await Assign(a); Console.WriteLine(""After Assignment a.B.x is: "" + a.B.x); } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public B B { get; set; } } class B { public int x; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestPropertyAccessThrows Before Assignment Caught NullReferenceException TestFieldAccessThrows Before Assignment RHS Caught NullReferenceException TestPropertyAccessSucceeds Before Assignment a.B.x is: 0 RHS After Assignment a.B.x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 184 (0xb8) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0054 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A Program.<Assign>d__0.a"" IL_0011: callvirt ""B A.B.get"" IL_0016: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_001b: ldstr ""RHS"" IL_0020: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0025: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_002a: stloc.2 IL_002b: ldloca.s V_2 IL_002d: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0032: brtrue.s IL_0070 IL_0034: ldarg.0 IL_0035: ldc.i4.0 IL_0036: dup IL_0037: stloc.0 IL_0038: stfld ""int Program.<Assign>d__0.<>1__state"" IL_003d: ldarg.0 IL_003e: ldloc.2 IL_003f: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0044: ldarg.0 IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_004a: ldloca.s V_2 IL_004c: ldarg.0 IL_004d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_0052: leave.s IL_00b7 IL_0054: ldarg.0 IL_0055: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_005a: stloc.2 IL_005b: ldarg.0 IL_005c: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0061: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0067: ldarg.0 IL_0068: ldc.i4.m1 IL_0069: dup IL_006a: stloc.0 IL_006b: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0070: ldloca.s V_2 IL_0072: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0077: stloc.1 IL_0078: ldarg.0 IL_0079: ldfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_007e: ldloc.1 IL_007f: stfld ""int B.x"" IL_0084: ldarg.0 IL_0085: ldnull IL_0086: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_008b: leave.s IL_00a4 } catch System.Exception { IL_008d: stloc.3 IL_008e: ldarg.0 IL_008f: ldc.i4.s -2 IL_0091: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0096: ldarg.0 IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_009c: ldloc.3 IL_009d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a2: leave.s IL_00b7 } IL_00a4: ldarg.0 IL_00a5: ldc.i4.s -2 IL_00a7: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00ac: ldarg.0 IL_00ad: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00b2: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b7: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_ClassFieldAccessOnArray() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A[] arr) { arr[0].x = await Write(""RHS""); } static async Task Main(string[] args) { await TestIndexerThrows(); await TestAssignmentThrows(); await TestIndexerSucceeds(); await TestReassignsArrayAndIndexerDuringAwait(); await TestReassignsTargetDuringAwait(); } static async Task TestIndexerThrows() { Console.WriteLine(nameof(TestIndexerThrows)); var arr = new A[0]; Console.WriteLine(""Before Assignment""); try { await Assign(arr); } catch (IndexOutOfRangeException) { Console.WriteLine(""Caught IndexOutOfRangeException""); } } static async Task TestAssignmentThrows() { Console.WriteLine(nameof(TestAssignmentThrows)); var arr = new A[1]; Console.WriteLine(""Before Assignment""); try { await Assign(arr); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestIndexerSucceeds() { Console.WriteLine(nameof(TestIndexerSucceeds)); var arr = new A[1]{ new A() }; Console.WriteLine(""Before Assignment arr[0].x is: "" + arr[0].x); await Assign(arr); Console.WriteLine(""After Assignment arr[0].x is: "" + arr[0].x); } static async Task TestReassignsArrayAndIndexerDuringAwait() { Console.WriteLine(nameof(TestReassignsArrayAndIndexerDuringAwait)); var a = new A(); var arr = new A[1]{ a }; var index = 0; Console.WriteLine(""Before Assignment arr.Length is: "" + arr.Length); Console.WriteLine(""Before Assignment a.x is: "" + a.x); arr[index].x = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment arr.Length is: "" + arr.Length); Console.WriteLine(""After Assignment a.x is: "" + a.x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); arr = new A[0]; index = 1; Console.WriteLine(s); return 42; } } static async Task TestReassignsTargetDuringAwait() { Console.WriteLine(nameof(TestReassignsTargetDuringAwait)); var a = new A(); var arr = new A[1]{ a }; Console.WriteLine(""Before Assignment arr[0].x is: "" + arr[0].x); Console.WriteLine(""Before Assignment arr[0].y is: "" + arr[0].y); Console.WriteLine(""Before Assignment a.x is: "" + a.x); arr[0].x = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment arr[0].x is: "" + arr[0].x); Console.WriteLine(""After Assignment arr[0].y is: "" + arr[0].y); Console.WriteLine(""After Assignment a.x is: "" + a.x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); arr[0] = new A{ y = true }; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public int x; public bool y; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestIndexerThrows Before Assignment Caught IndexOutOfRangeException TestAssignmentThrows Before Assignment RHS Caught NullReferenceException TestIndexerSucceeds Before Assignment arr[0].x is: 0 RHS After Assignment arr[0].x is: 42 TestReassignsArrayAndIndexerDuringAwait Before Assignment arr.Length is: 1 Before Assignment a.x is: 0 RHS After Assignment arr.Length is: 0 After Assignment a.x is: 42 TestReassignsTargetDuringAwait Before Assignment arr[0].x is: 0 Before Assignment arr[0].y is: False Before Assignment a.x is: 0 RHS After Assignment arr[0].x is: 0 After Assignment arr[0].y is: True After Assignment a.x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 181 (0xb5) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0051 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A[] Program.<Assign>d__0.arr"" IL_0011: ldc.i4.0 IL_0012: ldelem.ref IL_0013: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0018: ldstr ""RHS"" IL_001d: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0022: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0027: stloc.2 IL_0028: ldloca.s V_2 IL_002a: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002f: brtrue.s IL_006d IL_0031: ldarg.0 IL_0032: ldc.i4.0 IL_0033: dup IL_0034: stloc.0 IL_0035: stfld ""int Program.<Assign>d__0.<>1__state"" IL_003a: ldarg.0 IL_003b: ldloc.2 IL_003c: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0041: ldarg.0 IL_0042: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0047: ldloca.s V_2 IL_0049: ldarg.0 IL_004a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_004f: leave.s IL_00b4 IL_0051: ldarg.0 IL_0052: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0057: stloc.2 IL_0058: ldarg.0 IL_0059: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_005e: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0064: ldarg.0 IL_0065: ldc.i4.m1 IL_0066: dup IL_0067: stloc.0 IL_0068: stfld ""int Program.<Assign>d__0.<>1__state"" IL_006d: ldloca.s V_2 IL_006f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0074: stloc.1 IL_0075: ldarg.0 IL_0076: ldfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_007b: ldloc.1 IL_007c: stfld ""int A.x"" IL_0081: ldarg.0 IL_0082: ldnull IL_0083: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0088: leave.s IL_00a1 } catch System.Exception { IL_008a: stloc.3 IL_008b: ldarg.0 IL_008c: ldc.i4.s -2 IL_008e: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0093: ldarg.0 IL_0094: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0099: ldloc.3 IL_009a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_009f: leave.s IL_00b4 } IL_00a1: ldarg.0 IL_00a2: ldc.i4.s -2 IL_00a4: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00a9: ldarg.0 IL_00aa: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00af: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b4: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_StructFieldAccessOnArray() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A[] arr) { arr[0].x = await Write(""RHS""); } static async Task Main(string[] args) { await TestIndexerThrows(); await TestIndexerSucceeds(); await TestReassignsArrayAndIndexerDuringAwait(); await TestReassignsTargetDuringAwait(); } static async Task TestIndexerThrows() { Console.WriteLine(nameof(TestIndexerThrows)); var arr = new A[0]; Console.WriteLine(""Before Assignment""); try { await Assign(arr); } catch (IndexOutOfRangeException) { Console.WriteLine(""Caught IndexOutOfRangeException""); } } static async Task TestIndexerSucceeds() { Console.WriteLine(nameof(TestIndexerSucceeds)); var arr = new A[1]; Console.WriteLine(""Before Assignment arr[0].x is: "" + arr[0].x); await Assign(arr); Console.WriteLine(""After Assignment arr[0].x is: "" + arr[0].x); } static async Task TestReassignsArrayAndIndexerDuringAwait() { Console.WriteLine(nameof(TestReassignsArrayAndIndexerDuringAwait)); var arr = new A[1]; var arrCopy = arr; var index = 0; Console.WriteLine(""Before Assignment arr.Length is: "" + arr.Length); Console.WriteLine(""Before Assignment arrCopy[0].x is: "" + arrCopy[0].x); arr[index].x = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment arr.Length is: "" + arr.Length); Console.WriteLine(""After Assignment arrCopy[0].x is: "" + arrCopy[0].x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); arr = new A[0]; index = 1; Console.WriteLine(s); return 42; } } static async Task TestReassignsTargetDuringAwait() { Console.WriteLine(nameof(TestReassignsTargetDuringAwait)); var arr = new A[1]; Console.WriteLine(""Before Assignment arr[0].x is: "" + arr[0].x); Console.WriteLine(""Before Assignment arr[0].y is: "" + arr[0].y); arr[0].x = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment arr[0].x is: "" + arr[0].x); Console.WriteLine(""Before Assignment arr[0].y is: "" + arr[0].y); async Task<int> WriteAndReassign(string s) { await Task.Yield(); arr[0] = new A{y = true }; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } struct A { public int x; public bool y; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestIndexerThrows Before Assignment Caught IndexOutOfRangeException TestIndexerSucceeds Before Assignment arr[0].x is: 0 RHS After Assignment arr[0].x is: 42 TestReassignsArrayAndIndexerDuringAwait Before Assignment arr.Length is: 1 Before Assignment arrCopy[0].x is: 0 RHS After Assignment arr.Length is: 0 After Assignment arrCopy[0].x is: 42 TestReassignsTargetDuringAwait Before Assignment arr[0].x is: 0 Before Assignment arr[0].y is: False RHS After Assignment arr[0].x is: 42 Before Assignment arr[0].y is: True") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 198 (0xc6) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_005c IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A[] Program.<Assign>d__0.arr"" IL_0011: stfld ""A[] Program.<Assign>d__0.<>7__wrap1"" IL_0016: ldarg.0 IL_0017: ldfld ""A[] Program.<Assign>d__0.<>7__wrap1"" IL_001c: ldc.i4.0 IL_001d: ldelema ""A"" IL_0022: pop IL_0023: ldstr ""RHS"" IL_0028: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_002d: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0032: stloc.2 IL_0033: ldloca.s V_2 IL_0035: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_003a: brtrue.s IL_0078 IL_003c: ldarg.0 IL_003d: ldc.i4.0 IL_003e: dup IL_003f: stloc.0 IL_0040: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0045: ldarg.0 IL_0046: ldloc.2 IL_0047: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_004c: ldarg.0 IL_004d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0052: ldloca.s V_2 IL_0054: ldarg.0 IL_0055: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_005a: leave.s IL_00c5 IL_005c: ldarg.0 IL_005d: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0062: stloc.2 IL_0063: ldarg.0 IL_0064: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0069: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_006f: ldarg.0 IL_0070: ldc.i4.m1 IL_0071: dup IL_0072: stloc.0 IL_0073: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0078: ldloca.s V_2 IL_007a: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_007f: stloc.1 IL_0080: ldarg.0 IL_0081: ldfld ""A[] Program.<Assign>d__0.<>7__wrap1"" IL_0086: ldc.i4.0 IL_0087: ldelema ""A"" IL_008c: ldloc.1 IL_008d: stfld ""int A.x"" IL_0092: ldarg.0 IL_0093: ldnull IL_0094: stfld ""A[] Program.<Assign>d__0.<>7__wrap1"" IL_0099: leave.s IL_00b2 } catch System.Exception { IL_009b: stloc.3 IL_009c: ldarg.0 IL_009d: ldc.i4.s -2 IL_009f: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00a4: ldarg.0 IL_00a5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00aa: ldloc.3 IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00b0: leave.s IL_00c5 } IL_00b2: ldarg.0 IL_00b3: ldc.i4.s -2 IL_00b5: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00ba: ldarg.0 IL_00bb: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00c0: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00c5: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_AssignmentToArray() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(int[] arr) { arr[0] = await Write(""RHS""); } static async Task Main(string[] args) { await TestIndexerThrows(); await TestIndexerSucceeds(); await TestReassignsArrayAndIndexerDuringAwait(); } static async Task TestIndexerThrows() { Console.WriteLine(nameof(TestIndexerThrows)); var arr = new int[0]; Console.WriteLine(""Before Assignment""); try { await Assign(arr); } catch (IndexOutOfRangeException) { Console.WriteLine(""Caught IndexOutOfRangeException""); } } static async Task TestIndexerSucceeds() { Console.WriteLine(nameof(TestIndexerSucceeds)); var arr = new int[1]; Console.WriteLine(""Before Assignment arr[0] is: "" + arr[0]); await Assign(arr); Console.WriteLine(""After Assignment arr[0] is: "" + arr[0]); } static async Task TestReassignsArrayAndIndexerDuringAwait() { Console.WriteLine(nameof(TestReassignsArrayAndIndexerDuringAwait)); var arr = new int[1]; var arrCopy = arr; var index = 0; Console.WriteLine(""Before Assignment arr.Length is: "" + arr.Length); Console.WriteLine(""Before Assignment arrCopy[0] is: "" + arrCopy[0]); arr[index] = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment arr.Length is: "" + arr.Length); Console.WriteLine(""After Assignment arrCopy[0] is: "" + arrCopy[0]); async Task<int> WriteAndReassign(string s) { await Task.Yield(); arr = new int[0]; index = 1; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestIndexerThrows Before Assignment RHS Caught IndexOutOfRangeException TestIndexerSucceeds Before Assignment arr[0] is: 0 RHS After Assignment arr[0] is: 42 TestReassignsArrayAndIndexerDuringAwait Before Assignment arr.Length is: 1 Before Assignment arrCopy[0] is: 0 RHS After Assignment arr.Length is: 0 After Assignment arrCopy[0] is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 176 (0xb0) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_004f IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""int[] Program.<Assign>d__0.arr"" IL_0011: stfld ""int[] Program.<Assign>d__0.<>7__wrap1"" IL_0016: ldstr ""RHS"" IL_001b: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0020: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0025: stloc.2 IL_0026: ldloca.s V_2 IL_0028: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002d: brtrue.s IL_006b IL_002f: ldarg.0 IL_0030: ldc.i4.0 IL_0031: dup IL_0032: stloc.0 IL_0033: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0038: ldarg.0 IL_0039: ldloc.2 IL_003a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_003f: ldarg.0 IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0045: ldloca.s V_2 IL_0047: ldarg.0 IL_0048: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_004d: leave.s IL_00af IL_004f: ldarg.0 IL_0050: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0055: stloc.2 IL_0056: ldarg.0 IL_0057: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_005c: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0062: ldarg.0 IL_0063: ldc.i4.m1 IL_0064: dup IL_0065: stloc.0 IL_0066: stfld ""int Program.<Assign>d__0.<>1__state"" IL_006b: ldloca.s V_2 IL_006d: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0072: stloc.1 IL_0073: ldarg.0 IL_0074: ldfld ""int[] Program.<Assign>d__0.<>7__wrap1"" IL_0079: ldc.i4.0 IL_007a: ldloc.1 IL_007b: stelem.i4 IL_007c: ldarg.0 IL_007d: ldnull IL_007e: stfld ""int[] Program.<Assign>d__0.<>7__wrap1"" IL_0083: leave.s IL_009c } catch System.Exception { IL_0085: stloc.3 IL_0086: ldarg.0 IL_0087: ldc.i4.s -2 IL_0089: stfld ""int Program.<Assign>d__0.<>1__state"" IL_008e: ldarg.0 IL_008f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0094: ldloc.3 IL_0095: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_009a: leave.s IL_00af } IL_009c: ldarg.0 IL_009d: ldc.i4.s -2 IL_009f: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00a4: ldarg.0 IL_00a5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00aa: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00af: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_StructFieldAccessOnStructFieldAccessOnClassField() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a) { a.b.c.x = await Write(""RHS""); } static async Task Main(string[] args) { await TestAIsNull(); await TestAIsNotNull(); await ReassignADuringAssignment(); } static async Task TestAIsNull() { Console.WriteLine(nameof(TestAIsNull)); A a = null; Console.WriteLine(""Before Assignment""); try { await Assign(a); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNotNull() { Console.WriteLine(nameof(TestAIsNotNull)); var a = new A(); Console.WriteLine(""Before Assignment a.b.c.x is: "" + a.b.c.x); await Assign(a); Console.WriteLine(""After Assignment a.b.c.x is: "" + a.b.c.x); } static async Task ReassignADuringAssignment() { Console.WriteLine(nameof(ReassignADuringAssignment)); var a = new A(); var aCopy = a; Console.WriteLine(""Before Assignment a is null == "" + (a is null)); Console.WriteLine(""Before Assignment aCopy.b.c.x is: "" + aCopy.b.c.x); a.b.c.x = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment a is null == "" + (a is null)); Console.WriteLine(""After Assignment aCopy.b.c.x is: "" + aCopy.b.c.x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); a = null; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public B b; } struct B { public C c; } struct C { public int x; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestAIsNull Before Assignment Caught NullReferenceException TestAIsNotNull Before Assignment a.b.c.x is: 0 RHS After Assignment a.b.c.x is: 42 ReassignADuringAssignment Before Assignment a is null == False Before Assignment aCopy.b.c.x is: 0 RHS After Assignment a is null == True After Assignment aCopy.b.c.x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 201 (0xc9) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_005b IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A Program.<Assign>d__0.a"" IL_0011: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0016: ldarg.0 IL_0017: ldfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_001c: ldfld ""B A.b"" IL_0021: pop IL_0022: ldstr ""RHS"" IL_0027: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_002c: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0031: stloc.2 IL_0032: ldloca.s V_2 IL_0034: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0039: brtrue.s IL_0077 IL_003b: ldarg.0 IL_003c: ldc.i4.0 IL_003d: dup IL_003e: stloc.0 IL_003f: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0044: ldarg.0 IL_0045: ldloc.2 IL_0046: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_004b: ldarg.0 IL_004c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0051: ldloca.s V_2 IL_0053: ldarg.0 IL_0054: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_0059: leave.s IL_00c8 IL_005b: ldarg.0 IL_005c: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0061: stloc.2 IL_0062: ldarg.0 IL_0063: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0068: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_006e: ldarg.0 IL_006f: ldc.i4.m1 IL_0070: dup IL_0071: stloc.0 IL_0072: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0077: ldloca.s V_2 IL_0079: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_007e: stloc.1 IL_007f: ldarg.0 IL_0080: ldfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0085: ldflda ""B A.b"" IL_008a: ldflda ""C B.c"" IL_008f: ldloc.1 IL_0090: stfld ""int C.x"" IL_0095: ldarg.0 IL_0096: ldnull IL_0097: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_009c: leave.s IL_00b5 } catch System.Exception { IL_009e: stloc.3 IL_009f: ldarg.0 IL_00a0: ldc.i4.s -2 IL_00a2: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00a7: ldarg.0 IL_00a8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00ad: ldloc.3 IL_00ae: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00b3: leave.s IL_00c8 } IL_00b5: ldarg.0 IL_00b6: ldc.i4.s -2 IL_00b8: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00bd: ldarg.0 IL_00be: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00c3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00c8: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_ClassPropertyAssignmentOnClassProperty() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a) { a.b.x = await Write(""RHS""); } static async Task Main(string[] args) { await TestAIsNull(); await TestAIsNotNull(); await ReassignADuringAssignment(); } static async Task TestAIsNull() { Console.WriteLine(nameof(TestAIsNull)); A a = null; Console.WriteLine(""Before Assignment""); try { await Assign(a); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNotNull() { Console.WriteLine(nameof(TestAIsNotNull)); var a = new A{ _b = new B() }; Console.WriteLine(""Before Assignment a._b._x is: "" + a._b._x); await Assign(a); Console.WriteLine(""After Assignment a._b._x is: "" + a._b._x); } static async Task ReassignADuringAssignment() { Console.WriteLine(nameof(ReassignADuringAssignment)); var a = new A{ _b = new B() }; var aCopy = a; Console.WriteLine(""Before Assignment a is null == "" + (a is null)); Console.WriteLine(""Before Assignment aCopy._b._x is: "" + aCopy._b._x); a.b.x = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment a is null == "" + (a is null)); Console.WriteLine(""After Assignment aCopy._b._x is: "" + aCopy._b._x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); a = null; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public B _b; public B b { get { Console.WriteLine(""GetB""); return _b; } set { Console.WriteLine(""SetB""); _b = value; }} } class B { public int _x; public int x { get { Console.WriteLine(""GetX""); return _x; } set { Console.WriteLine(""SetX""); _x = value; } } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestAIsNull Before Assignment Caught NullReferenceException TestAIsNotNull Before Assignment a._b._x is: 0 GetB RHS SetX After Assignment a._b._x is: 42 ReassignADuringAssignment Before Assignment a is null == False Before Assignment aCopy._b._x is: 0 GetB RHS SetX After Assignment a is null == True After Assignment aCopy._b._x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 184 (0xb8) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0054 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A Program.<Assign>d__0.a"" IL_0011: callvirt ""B A.b.get"" IL_0016: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_001b: ldstr ""RHS"" IL_0020: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0025: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_002a: stloc.2 IL_002b: ldloca.s V_2 IL_002d: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0032: brtrue.s IL_0070 IL_0034: ldarg.0 IL_0035: ldc.i4.0 IL_0036: dup IL_0037: stloc.0 IL_0038: stfld ""int Program.<Assign>d__0.<>1__state"" IL_003d: ldarg.0 IL_003e: ldloc.2 IL_003f: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0044: ldarg.0 IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_004a: ldloca.s V_2 IL_004c: ldarg.0 IL_004d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_0052: leave.s IL_00b7 IL_0054: ldarg.0 IL_0055: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_005a: stloc.2 IL_005b: ldarg.0 IL_005c: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0061: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0067: ldarg.0 IL_0068: ldc.i4.m1 IL_0069: dup IL_006a: stloc.0 IL_006b: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0070: ldloca.s V_2 IL_0072: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0077: stloc.1 IL_0078: ldarg.0 IL_0079: ldfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_007e: ldloc.1 IL_007f: callvirt ""void B.x.set"" IL_0084: ldarg.0 IL_0085: ldnull IL_0086: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_008b: leave.s IL_00a4 } catch System.Exception { IL_008d: stloc.3 IL_008e: ldarg.0 IL_008f: ldc.i4.s -2 IL_0091: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0096: ldarg.0 IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_009c: ldloc.3 IL_009d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a2: leave.s IL_00b7 } IL_00a4: ldarg.0 IL_00a5: ldc.i4.s -2 IL_00a7: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00ac: ldarg.0 IL_00ad: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00b2: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b7: ret }"); } [WorkItem(19609, "https://github.com/dotnet/roslyn/issues/19609")] [Fact] public void KeepLtrSemantics_FieldAccessOnClass() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a) { a.x = await Write(""RHS""); } static async Task Main(string[] args) { await TestAIsNull(); await TestAIsNotNull(); await ReassignADuringAssignment(); } static async Task TestAIsNull() { Console.WriteLine(nameof(TestAIsNull)); A a = null; Console.WriteLine(""Before Assignment""); try { await Assign(a); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNotNull() { Console.WriteLine(nameof(TestAIsNotNull)); var a = new A(); Console.WriteLine(""Before Assignment a.x is: "" + a.x); await Assign(a); Console.WriteLine(""After Assignment a.x is: "" + a.x); } static async Task ReassignADuringAssignment() { Console.WriteLine(nameof(ReassignADuringAssignment)); var a = new A(); var aCopy = a; Console.WriteLine(""Before Assignment a is null == "" + (a is null)); Console.WriteLine(""Before Assignment aCopy.x is: "" + aCopy.x); a.x = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment a is null == "" + (a is null)); Console.WriteLine(""After Assignment aCopy.x is: "" + aCopy.x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); a = null; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public int x; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestAIsNull Before Assignment RHS Caught NullReferenceException TestAIsNotNull Before Assignment a.x is: 0 RHS After Assignment a.x is: 42 ReassignADuringAssignment Before Assignment a is null == False Before Assignment aCopy.x is: 0 RHS After Assignment a is null == True After Assignment aCopy.x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 179 (0xb3) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_004f IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A Program.<Assign>d__0.a"" IL_0011: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0016: ldstr ""RHS"" IL_001b: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0020: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0025: stloc.2 IL_0026: ldloca.s V_2 IL_0028: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002d: brtrue.s IL_006b IL_002f: ldarg.0 IL_0030: ldc.i4.0 IL_0031: dup IL_0032: stloc.0 IL_0033: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0038: ldarg.0 IL_0039: ldloc.2 IL_003a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_003f: ldarg.0 IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0045: ldloca.s V_2 IL_0047: ldarg.0 IL_0048: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_004d: leave.s IL_00b2 IL_004f: ldarg.0 IL_0050: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0055: stloc.2 IL_0056: ldarg.0 IL_0057: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_005c: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0062: ldarg.0 IL_0063: ldc.i4.m1 IL_0064: dup IL_0065: stloc.0 IL_0066: stfld ""int Program.<Assign>d__0.<>1__state"" IL_006b: ldloca.s V_2 IL_006d: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0072: stloc.1 IL_0073: ldarg.0 IL_0074: ldfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0079: ldloc.1 IL_007a: stfld ""int A.x"" IL_007f: ldarg.0 IL_0080: ldnull IL_0081: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0086: leave.s IL_009f } catch System.Exception { IL_0088: stloc.3 IL_0089: ldarg.0 IL_008a: ldc.i4.s -2 IL_008c: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0091: ldarg.0 IL_0092: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0097: ldloc.3 IL_0098: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_009d: leave.s IL_00b2 } IL_009f: ldarg.0 IL_00a0: ldc.i4.s -2 IL_00a2: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00a7: ldarg.0 IL_00a8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00ad: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b2: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_CompoundAssignment() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a) { a.x += await Write(""RHS""); } static async Task Main(string[] args) { await TestAIsNull(); await TestAIsNotNull(); await ReassignADuringAssignment(); await ReassignXDuringAssignment(); } static async Task TestAIsNull() { Console.WriteLine(nameof(TestAIsNull)); A a = null; Console.WriteLine(""Before Assignment""); try { await Assign(a); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNotNull() { Console.WriteLine(nameof(TestAIsNotNull)); var a = new A(){ x = 1 }; Console.WriteLine(""Before Assignment a.x is: "" + a.x); await Assign(a); Console.WriteLine(""After Assignment a.x is: "" + a.x); } static async Task ReassignADuringAssignment() { Console.WriteLine(nameof(ReassignADuringAssignment)); var a = new A(){ x = 1 }; var aCopy = a; Console.WriteLine(""Before Assignment a is null == "" + (a is null)); Console.WriteLine(""Before Assignment aCopy.x is: "" + aCopy.x); a.x += await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment a is null == "" + (a is null)); Console.WriteLine(""After Assignment aCopy.x is: "" + aCopy.x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); a = null; Console.WriteLine(s); return 42; } } static async Task ReassignXDuringAssignment() { Console.WriteLine(nameof(ReassignXDuringAssignment)); var a = new A(){ x = 1 }; Console.WriteLine(""Before Assignment a.x is: "" + a.x); a.x += await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment a.x is: "" + a.x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); a.x = 100; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public int x; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestAIsNull Before Assignment Caught NullReferenceException TestAIsNotNull Before Assignment a.x is: 1 RHS After Assignment a.x is: 43 ReassignADuringAssignment Before Assignment a is null == False Before Assignment aCopy.x is: 1 RHS After Assignment a is null == True After Assignment aCopy.x is: 43 ReassignXDuringAssignment Before Assignment a.x is: 1 RHS After Assignment a.x is: 43") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 202 (0xca) .maxstack 3 .locals init (int V_0, A V_1, int V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_005d IL_000a: ldarg.0 IL_000b: ldfld ""A Program.<Assign>d__0.a"" IL_0010: stloc.1 IL_0011: ldarg.0 IL_0012: ldloc.1 IL_0013: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0018: ldarg.0 IL_0019: ldloc.1 IL_001a: ldfld ""int A.x"" IL_001f: stfld ""int Program.<Assign>d__0.<>7__wrap2"" IL_0024: ldstr ""RHS"" IL_0029: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_002e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0033: stloc.3 IL_0034: ldloca.s V_3 IL_0036: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_003b: brtrue.s IL_0079 IL_003d: ldarg.0 IL_003e: ldc.i4.0 IL_003f: dup IL_0040: stloc.0 IL_0041: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0046: ldarg.0 IL_0047: ldloc.3 IL_0048: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_004d: ldarg.0 IL_004e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0053: ldloca.s V_3 IL_0055: ldarg.0 IL_0056: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_005b: leave.s IL_00c9 IL_005d: ldarg.0 IL_005e: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0063: stloc.3 IL_0064: ldarg.0 IL_0065: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_006a: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0070: ldarg.0 IL_0071: ldc.i4.m1 IL_0072: dup IL_0073: stloc.0 IL_0074: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0079: ldloca.s V_3 IL_007b: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0080: stloc.2 IL_0081: ldarg.0 IL_0082: ldfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0087: ldarg.0 IL_0088: ldfld ""int Program.<Assign>d__0.<>7__wrap2"" IL_008d: ldloc.2 IL_008e: add IL_008f: stfld ""int A.x"" IL_0094: ldarg.0 IL_0095: ldnull IL_0096: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_009b: leave.s IL_00b6 } catch System.Exception { IL_009d: stloc.s V_4 IL_009f: ldarg.0 IL_00a0: ldc.i4.s -2 IL_00a2: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00a7: ldarg.0 IL_00a8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00ad: ldloc.s V_4 IL_00af: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00b4: leave.s IL_00c9 } IL_00b6: ldarg.0 IL_00b7: ldc.i4.s -2 IL_00b9: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00be: ldarg.0 IL_00bf: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00c4: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00c9: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_CompoundAssignmentProperties() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a) { a.x += await Write(""RHS""); } static async Task Main(string[] args) { await TestAIsNull(); await TestAIsNotNull(); await ReassignADuringAssignment(); await ReassignXDuringAssignment(); } static async Task TestAIsNull() { Console.WriteLine(nameof(TestAIsNull)); A a = null; Console.WriteLine(""Before Assignment""); try { await Assign(a); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNotNull() { Console.WriteLine(nameof(TestAIsNotNull)); var a = new A(){ _x = 1 }; Console.WriteLine(""Before Assignment a._x is: "" + a._x); await Assign(a); Console.WriteLine(""After Assignment a._x is: "" + a._x); } static async Task ReassignADuringAssignment() { Console.WriteLine(nameof(ReassignADuringAssignment)); var a = new A(){ _x = 1 }; var aCopy = a; Console.WriteLine(""Before Assignment a is null == "" + (a is null)); Console.WriteLine(""Before Assignment aCopy._x is: "" + aCopy._x); a.x += await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment a is null == "" + (a is null)); Console.WriteLine(""After Assignment aCopy._x is: "" + aCopy._x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); a = null; Console.WriteLine(s); return 42; } } static async Task ReassignXDuringAssignment() { Console.WriteLine(nameof(ReassignXDuringAssignment)); var a = new A(){ _x = 1 }; Console.WriteLine(""Before Assignment a._x is: "" + a._x); a.x += await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment a._x is: "" + a._x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); a._x = 100; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public int _x; public int x { get { Console.WriteLine(""GetX""); return _x; } set { Console.WriteLine(""SetX""); _x = value; } } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestAIsNull Before Assignment Caught NullReferenceException TestAIsNotNull Before Assignment a._x is: 1 GetX RHS SetX After Assignment a._x is: 43 ReassignADuringAssignment Before Assignment a is null == False Before Assignment aCopy._x is: 1 GetX RHS SetX After Assignment a is null == True After Assignment aCopy._x is: 43 ReassignXDuringAssignment Before Assignment a._x is: 1 GetX RHS SetX After Assignment a._x is: 43") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 202 (0xca) .maxstack 3 .locals init (int V_0, A V_1, int V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_005d IL_000a: ldarg.0 IL_000b: ldfld ""A Program.<Assign>d__0.a"" IL_0010: stloc.1 IL_0011: ldarg.0 IL_0012: ldloc.1 IL_0013: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0018: ldarg.0 IL_0019: ldloc.1 IL_001a: callvirt ""int A.x.get"" IL_001f: stfld ""int Program.<Assign>d__0.<>7__wrap2"" IL_0024: ldstr ""RHS"" IL_0029: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_002e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0033: stloc.3 IL_0034: ldloca.s V_3 IL_0036: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_003b: brtrue.s IL_0079 IL_003d: ldarg.0 IL_003e: ldc.i4.0 IL_003f: dup IL_0040: stloc.0 IL_0041: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0046: ldarg.0 IL_0047: ldloc.3 IL_0048: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_004d: ldarg.0 IL_004e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0053: ldloca.s V_3 IL_0055: ldarg.0 IL_0056: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_005b: leave.s IL_00c9 IL_005d: ldarg.0 IL_005e: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0063: stloc.3 IL_0064: ldarg.0 IL_0065: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_006a: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0070: ldarg.0 IL_0071: ldc.i4.m1 IL_0072: dup IL_0073: stloc.0 IL_0074: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0079: ldloca.s V_3 IL_007b: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0080: stloc.2 IL_0081: ldarg.0 IL_0082: ldfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0087: ldarg.0 IL_0088: ldfld ""int Program.<Assign>d__0.<>7__wrap2"" IL_008d: ldloc.2 IL_008e: add IL_008f: callvirt ""void A.x.set"" IL_0094: ldarg.0 IL_0095: ldnull IL_0096: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_009b: leave.s IL_00b6 } catch System.Exception { IL_009d: stloc.s V_4 IL_009f: ldarg.0 IL_00a0: ldc.i4.s -2 IL_00a2: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00a7: ldarg.0 IL_00a8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00ad: ldloc.s V_4 IL_00af: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00b4: leave.s IL_00c9 } IL_00b6: ldarg.0 IL_00b7: ldc.i4.s -2 IL_00b9: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00be: ldarg.0 IL_00bf: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00c4: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00c9: ret }"); } [WorkItem(19609, "https://github.com/dotnet/roslyn/issues/19609")] [Fact] public void KeepLtrSemantics_AssignmentToAssignment() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a, B b) { a.b.x = b.x = await Write(""RHS""); } static async Task Main(string[] args) { await TestAIsNullBIsNull(); await TestAIsNullBIsNotNull(); await TestAIsNotNullBIsNull(); await TestADotBIsNullBIsNotNull(); await TestADotBIsNotNullBIsNotNull(); } static async Task TestAIsNullBIsNull() { Console.WriteLine(nameof(TestAIsNullBIsNull)); A a = null; B b = null; Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNullBIsNotNull() { Console.WriteLine(nameof(TestAIsNullBIsNotNull)); A a = null; B b = new B(); Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNotNullBIsNull() { Console.WriteLine(nameof(TestAIsNotNullBIsNull)); A a = new A{ b = new B() }; B b = null; Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestADotBIsNullBIsNotNull() { Console.WriteLine(nameof(TestADotBIsNullBIsNotNull)); A a = new A(); B b = new B(); Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestADotBIsNotNullBIsNotNull() { Console.WriteLine(nameof(TestADotBIsNotNullBIsNotNull)); A a = new A{ b = new B() }; B b = new B(); Console.WriteLine(""Before Assignment a.b.x is: "" + a.b.x); Console.WriteLine(""Before Assignment b.x is: "" + b.x); await Assign(a, b); Console.WriteLine(""After Assignment a.b.x is: "" + a.b.x); Console.WriteLine(""After Assignment b.x is: "" + b.x); } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public B b; } class B { public int x; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestAIsNullBIsNull Before Assignment Caught NullReferenceException TestAIsNullBIsNotNull Before Assignment Caught NullReferenceException TestAIsNotNullBIsNull Before Assignment RHS Caught NullReferenceException TestADotBIsNullBIsNotNull Before Assignment RHS Caught NullReferenceException TestADotBIsNotNullBIsNotNull Before Assignment a.b.x is: 0 Before Assignment b.x is: 0 RHS After Assignment a.b.x is: 42 After Assignment b.x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 219 (0xdb) .maxstack 4 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, int V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0060 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A Program.<Assign>d__0.a"" IL_0011: ldfld ""B A.b"" IL_0016: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_001b: ldarg.0 IL_001c: ldarg.0 IL_001d: ldfld ""B Program.<Assign>d__0.b"" IL_0022: stfld ""B Program.<Assign>d__0.<>7__wrap2"" IL_0027: ldstr ""RHS"" IL_002c: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0031: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0036: stloc.2 IL_0037: ldloca.s V_2 IL_0039: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_003e: brtrue.s IL_007c IL_0040: ldarg.0 IL_0041: ldc.i4.0 IL_0042: dup IL_0043: stloc.0 IL_0044: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0049: ldarg.0 IL_004a: ldloc.2 IL_004b: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0050: ldarg.0 IL_0051: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0056: ldloca.s V_2 IL_0058: ldarg.0 IL_0059: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_005e: leave.s IL_00da IL_0060: ldarg.0 IL_0061: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0066: stloc.2 IL_0067: ldarg.0 IL_0068: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_006d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0073: ldarg.0 IL_0074: ldc.i4.m1 IL_0075: dup IL_0076: stloc.0 IL_0077: stfld ""int Program.<Assign>d__0.<>1__state"" IL_007c: ldloca.s V_2 IL_007e: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0083: stloc.1 IL_0084: ldarg.0 IL_0085: ldfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_008a: ldarg.0 IL_008b: ldfld ""B Program.<Assign>d__0.<>7__wrap2"" IL_0090: ldloc.1 IL_0091: dup IL_0092: stloc.3 IL_0093: stfld ""int B.x"" IL_0098: ldloc.3 IL_0099: stfld ""int B.x"" IL_009e: ldarg.0 IL_009f: ldnull IL_00a0: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_00a5: ldarg.0 IL_00a6: ldnull IL_00a7: stfld ""B Program.<Assign>d__0.<>7__wrap2"" IL_00ac: leave.s IL_00c7 } catch System.Exception { IL_00ae: stloc.s V_4 IL_00b0: ldarg.0 IL_00b1: ldc.i4.s -2 IL_00b3: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00b8: ldarg.0 IL_00b9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00be: ldloc.s V_4 IL_00c0: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00c5: leave.s IL_00da } IL_00c7: ldarg.0 IL_00c8: ldc.i4.s -2 IL_00ca: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00cf: ldarg.0 IL_00d0: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00da: ret }"); } [WorkItem(19609, "https://github.com/dotnet/roslyn/issues/19609")] [Fact] public void KeepLtrSemantics_AssignmentToAssignmentProperties() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a, B b) { a.b.x = b.x = await Write(""RHS""); } static async Task Main(string[] args) { await TestAIsNullBIsNull(); await TestAIsNullBIsNotNull(); await TestAIsNotNullBIsNull(); await TestADotBIsNullBIsNotNull(); await TestADotBIsNotNullBIsNotNull(); } static async Task TestAIsNullBIsNull() { Console.WriteLine(nameof(TestAIsNullBIsNull)); A a = null; B b = null; Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNullBIsNotNull() { Console.WriteLine(nameof(TestAIsNullBIsNotNull)); A a = null; B b = new B(); Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNotNullBIsNull() { Console.WriteLine(nameof(TestAIsNotNullBIsNull)); A a = new A{ _b = new B() }; B b = null; Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestADotBIsNullBIsNotNull() { Console.WriteLine(nameof(TestADotBIsNullBIsNotNull)); A a = new A(); B b = new B(); Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestADotBIsNotNullBIsNotNull() { Console.WriteLine(nameof(TestADotBIsNotNullBIsNotNull)); A a = new A{ _b = new B() }; B b = new B(); Console.WriteLine(""Before Assignment a._b._x is: "" + a._b._x); Console.WriteLine(""Before Assignment b._x is: "" + b._x); await Assign(a, b); Console.WriteLine(""After Assignment a._b._x is: "" + a._b._x); Console.WriteLine(""After Assignment b._x is: "" + b._x); } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public B _b; public B b { get { Console.WriteLine(""GetB""); return _b; } set { Console.WriteLine(""SetB""); _b = value; }} } class B { public int _x; public int x { get { Console.WriteLine(""GetX""); return _x; } set { Console.WriteLine(""SetX""); _x = value; } } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestAIsNullBIsNull Before Assignment Caught NullReferenceException TestAIsNullBIsNotNull Before Assignment Caught NullReferenceException TestAIsNotNullBIsNull Before Assignment GetB RHS Caught NullReferenceException TestADotBIsNullBIsNotNull Before Assignment GetB RHS SetX Caught NullReferenceException TestADotBIsNotNullBIsNotNull Before Assignment a._b._x is: 0 Before Assignment b._x is: 0 GetB RHS SetX SetX After Assignment a._b._x is: 42 After Assignment b._x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 219 (0xdb) .maxstack 3 .locals init (int V_0, int V_1, int V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0060 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A Program.<Assign>d__0.a"" IL_0011: callvirt ""B A.b.get"" IL_0016: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_001b: ldarg.0 IL_001c: ldarg.0 IL_001d: ldfld ""B Program.<Assign>d__0.b"" IL_0022: stfld ""B Program.<Assign>d__0.<>7__wrap2"" IL_0027: ldstr ""RHS"" IL_002c: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0031: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0036: stloc.3 IL_0037: ldloca.s V_3 IL_0039: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_003e: brtrue.s IL_007c IL_0040: ldarg.0 IL_0041: ldc.i4.0 IL_0042: dup IL_0043: stloc.0 IL_0044: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0049: ldarg.0 IL_004a: ldloc.3 IL_004b: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0050: ldarg.0 IL_0051: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0056: ldloca.s V_3 IL_0058: ldarg.0 IL_0059: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_005e: leave.s IL_00da IL_0060: ldarg.0 IL_0061: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0066: stloc.3 IL_0067: ldarg.0 IL_0068: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_006d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0073: ldarg.0 IL_0074: ldc.i4.m1 IL_0075: dup IL_0076: stloc.0 IL_0077: stfld ""int Program.<Assign>d__0.<>1__state"" IL_007c: ldloca.s V_3 IL_007e: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0083: stloc.1 IL_0084: ldarg.0 IL_0085: ldfld ""B Program.<Assign>d__0.<>7__wrap2"" IL_008a: ldloc.1 IL_008b: dup IL_008c: stloc.2 IL_008d: callvirt ""void B.x.set"" IL_0092: ldarg.0 IL_0093: ldfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_0098: ldloc.2 IL_0099: callvirt ""void B.x.set"" IL_009e: ldarg.0 IL_009f: ldnull IL_00a0: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_00a5: ldarg.0 IL_00a6: ldnull IL_00a7: stfld ""B Program.<Assign>d__0.<>7__wrap2"" IL_00ac: leave.s IL_00c7 } catch System.Exception { IL_00ae: stloc.s V_4 IL_00b0: ldarg.0 IL_00b1: ldc.i4.s -2 IL_00b3: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00b8: ldarg.0 IL_00b9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00be: ldloc.s V_4 IL_00c0: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00c5: leave.s IL_00da } IL_00c7: ldarg.0 IL_00c8: ldc.i4.s -2 IL_00ca: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00cf: ldarg.0 IL_00d0: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00da: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void AssignmentToFieldOfStaticFieldOfStruct() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign() { A.b.x = await Write(""RHS""); } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } static async Task Main(string[] args) { Console.WriteLine(""Before Assignment A.b.x is: "" + A.b.x); await Assign(); Console.WriteLine(""After Assignment A.b.x is: "" + A.b.x); } } struct A { public static B b; } struct B { public int x; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"Before Assignment A.b.x is: 0 RHS After Assignment A.b.x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 159 (0x9f) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0043 IL_000a: ldstr ""RHS"" IL_000f: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0014: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0021: brtrue.s IL_005f IL_0023: ldarg.0 IL_0024: ldc.i4.0 IL_0025: dup IL_0026: stloc.0 IL_0027: stfld ""int Program.<Assign>d__0.<>1__state"" IL_002c: ldarg.0 IL_002d: ldloc.2 IL_002e: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0033: ldarg.0 IL_0034: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0039: ldloca.s V_2 IL_003b: ldarg.0 IL_003c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_0041: leave.s IL_009e IL_0043: ldarg.0 IL_0044: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0049: stloc.2 IL_004a: ldarg.0 IL_004b: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0050: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0056: ldarg.0 IL_0057: ldc.i4.m1 IL_0058: dup IL_0059: stloc.0 IL_005a: stfld ""int Program.<Assign>d__0.<>1__state"" IL_005f: ldloca.s V_2 IL_0061: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0066: stloc.1 IL_0067: ldsflda ""B A.b"" IL_006c: ldloc.1 IL_006d: stfld ""int B.x"" IL_0072: leave.s IL_008b } catch System.Exception { IL_0074: stloc.3 IL_0075: ldarg.0 IL_0076: ldc.i4.s -2 IL_0078: stfld ""int Program.<Assign>d__0.<>1__state"" IL_007d: ldarg.0 IL_007e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0083: ldloc.3 IL_0084: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0089: leave.s IL_009e } IL_008b: ldarg.0 IL_008c: ldc.i4.s -2 IL_008e: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0093: ldarg.0 IL_0094: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0099: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_009e: ret }"); } [Fact, WorkItem(47191, "https://github.com/dotnet/roslyn/issues/47191")] public void AssignStaticStructField() { var source = @" using System; using System.Threading.Tasks; public struct S1 { public int Field; } public class C { public static S1 s1; static async Task M(Task<int> t) { s1.Field = await t; } static async Task Main() { await M(Task.FromResult(1)); Console.Write(s1.Field); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); } [Fact, WorkItem(47191, "https://github.com/dotnet/roslyn/issues/47191")] public void AssignStaticStructField_ViaUsingStatic() { var source = @" using System; using System.Threading.Tasks; using static C; public struct S1 { public int Field; } public class C { public static S1 s1; } public class Program { static async Task M(Task<int> t) { s1.Field = await t; } static async Task Main() { await M(Task.FromResult(1)); Console.Write(s1.Field); } } "; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); } [Fact, WorkItem(47191, "https://github.com/dotnet/roslyn/issues/47191")] public void AssignInstanceStructField() { var source = @" using System; using System.Threading.Tasks; public struct S1 { public int Field; } public class C { public S1 s1; async Task M(Task<int> t) { s1.Field = await t; } static async Task Main() { var c = new C(); await c.M(Task.FromResult(1)); Console.Write(c.s1.Field); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); } } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenAsyncSpillTests : EmitMetadataTestBase { public CodeGenAsyncSpillTests() { } private CompilationVerifier CompileAndVerify(string source, string expectedOutput = null, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null) { return base.CompileAndVerify(source, expectedOutput: expectedOutput, references: references, options: options); } [Fact] public void AsyncWithTernary() { var source = @" using System; using System.Threading.Tasks; class Test { public static Task<T> F<T>(T x) { Console.WriteLine(""F("" + x + "")""); return Task.Factory.StartNew(() => { return x; }); } public static async Task<int> G(bool b1, bool b2) { int c = 0; c = c + (b1 ? 1 : await F(2)); c = c + (b2 ? await F(4) : 8); return await F(c); } public static int H(bool b1, bool b2) { Task<int> t = G(b1, b2); t.Wait(1000 * 60); return t.Result; } public static void Main() { Console.WriteLine(H(false, false)); Console.WriteLine(H(false, true)); Console.WriteLine(H(true, false)); Console.WriteLine(H(true, true)); } }"; var expected = @" F(2) F(10) 10 F(2) F(4) F(6) 6 F(9) 9 F(4) F(5) 5 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncWithAnd() { var source = @" using System; using System.Threading.Tasks; class Test { public static Task<T> F<T>(T x) { Console.WriteLine(""F("" + x + "")""); return Task.Factory.StartNew(() => { return x; }); } public static async Task<int> G(bool b1, bool b2) { bool x1 = b1 && await F(true); bool x2 = b1 && await F(false); bool x3 = b2 && await F(true); bool x4 = b2 && await F(false); int c = 0; if (x1) c += 1; if (x2) c += 2; if (x3) c += 4; if (x4) c += 8; return await F(c); } public static int H(bool b1, bool b2) { Task<int> t = G(b1, b2); t.Wait(1000 * 60); return t.Result; } public static void Main() { Console.WriteLine(H(false, true)); } }"; var expected = @" F(True) F(False) F(4) 4 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncWithOr() { var source = @" using System; using System.Threading.Tasks; class Test { public static Task<T> F<T>(T x) { Console.WriteLine(""F("" + x + "")""); return Task.Factory.StartNew(() => { return x; }); } public static async Task<int> G(bool b1, bool b2) { bool x1 = b1 || await F(true); bool x2 = b1 || await F(false); bool x3 = b2 || await F(true); bool x4 = b2 || await F(false); int c = 0; if (x1) c += 1; if (x2) c += 2; if (x3) c += 4; if (x4) c += 8; return await F(c); } public static int H(bool b1, bool b2) { Task<int> t = G(b1, b2); t.Wait(1000 * 60); return t.Result; } public static void Main() { Console.WriteLine(H(false, true)); } }"; var expected = @" F(True) F(False) F(13) 13 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncWithCoalesce() { var source = @" using System; using System.Threading.Tasks; class Test { public static Task<string> F(string x) { Console.WriteLine(""F("" + (x ?? ""null"") + "")""); return Task.Factory.StartNew(() => { return x; }); } public static async Task<string> G(string s1, string s2) { var result = await F(s1) ?? await F(s2); Console.WriteLine("" "" + (result ?? ""null"")); return result; } public static string H(string s1, string s2) { Task<string> t = G(s1, s2); t.Wait(1000 * 60); return t.Result; } public static void Main() { H(null, null); H(null, ""a""); H(""b"", null); H(""c"", ""d""); } }"; var expected = @" F(null) F(null) null F(null) F(a) a F(b) b F(c) c "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AwaitInExpr() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<int> F() { return await Task.Factory.StartNew(() => 21); } public static async Task<int> G() { int c = 0; c = (await F()) + 21; return c; } public static void Main() { Task<int> t = G(); t.Wait(1000 * 60); Console.WriteLine(t.Result); } }"; var expected = @" 42 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void SpillNestedUnary() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<int> F() { return 1; } public static async Task<int> G1() { return -(await F()); } public static async Task<int> G2() { return -(-(await F())); } public static async Task<int> G3() { return -(-(-(await F()))); } public static void WaitAndPrint(Task<int> t) { t.Wait(); Console.WriteLine(t.Result); } public static void Main() { WaitAndPrint(G1()); WaitAndPrint(G2()); WaitAndPrint(G3()); } }"; var expected = @" -1 1 -1 "; CompileAndVerify(source, expected); } [Fact] public void AsyncWithParamsAndLocals_DoubleAwait_Spilling() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<int> F(int x) { return await Task.Factory.StartNew(() => { return x; }); } public static async Task<int> G(int x) { int c = 0; c = (await F(x)) + c; c = (await F(x)) + c; return c; } public static void Main() { Task<int> t = G(21); t.Wait(1000 * 60); Console.WriteLine(t.Result); } }"; var expected = @" 42 "; // When the local 'c' gets hoisted, the statement: // c = (await F(x)) + c; // Gets rewritten to: // this.c_field = (await F(x)) + this.c_field; // // The code-gen for the assignment is something like this: // ldarg0 // load the 'this' reference to the stack // <emitted await expression> // stfld // // What we really want is to evaluate any parts of the lvalue that have side-effects (which is this case is // nothing), and then defer loading the address for the field reference until after the await expression: // <emitted await expression> // <store to tmp> // ldarg0 // <load tmp> // stfld // // So this case actually requires stack spilling, which is not yet implemented. This has the unfortunate // consequence of preventing await expressions from being assigned to hoisted locals. // CompileAndVerify(source, expectedOutput: expected); } [Fact] public void SpillCall() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Test { public static void Printer(int a, int b, int c, int d, int e) { foreach (var x in new List<int>() { a, b, c, d, e }) { Console.WriteLine(x); } } public static int Get(int x) { Console.WriteLine(""> "" + x); return x; } public static async Task<int> F(int x) { return await Task.Factory.StartNew(() => x); } public static async Task G() { Printer(Get(111), Get(222), Get(333), await F(Get(444)), Get(555)); } public static void Main() { Task t = G(); t.Wait(); } }"; var expected = @" > 111 > 222 > 333 > 444 > 555 111 222 333 444 555 "; CompileAndVerify(source, expected); } [Fact] public void SpillCall2() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Test { public static void Printer(int a, int b, int c, int d, int e) { foreach (var x in new List<int>() { a, b, c, d, e }) { Console.WriteLine(x); } } public static int Get(int x) { Console.WriteLine(""> "" + x); return x; } public static async Task<int> F(int x) { return await Task.Factory.StartNew(() => x); } public static async Task G() { Printer(Get(111), await F(Get(222)), Get(333), await F(Get(444)), Get(555)); } public static void Main() { Task t = G(); t.Wait(); } }"; var expected = @" > 111 > 222 > 333 > 444 > 555 111 222 333 444 555 "; CompileAndVerify(source, expected); } [Fact] public void SpillCall3() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Test { public static void Printer(int a, int b, int c, int d, int e, int f) { foreach (var x in new List<int>(){a, b, c, d, e, f}) { Console.WriteLine(x); } } public static async Task<int> F(int x) { return await Task.Factory.StartNew(() => x); } public static async Task G() { Printer(1, await F(2), 3, await F(await F(await F(await F(4)))), await F(5), 6); } public static void Main() { Task t = G(); t.Wait(); } }"; var expected = @" 1 2 3 4 5 6 "; CompileAndVerify(source, expected); } [Fact] public void SpillCall4() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Test { public static void Printer(int a, int b) { foreach (var x in new List<int>(){a, b}) { Console.WriteLine(x); } } public static async Task<int> F(int x) { return await Task.Factory.StartNew(() => x); } public static async Task G() { Printer(1, await F(await F(2))); } public static void Main() { Task t = G(); t.Wait(); } }"; var expected = @" 1 2 "; CompileAndVerify(source, expected); } [Fact] public void SpillSequences1() { var source = @" using System.Threading.Tasks; public class Test { public static int H(int a, int b, int c) { return a; } public static Task<int> G() { return null; } public static async Task<int> F(int[] array) { H(array[1] += 2, array[3] += await G(), 4); return 1; } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Test.<F>d__2.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"{ // Code size 273 (0x111) .maxstack 5 .locals init (int V_0, int V_1, int V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, Test.<F>d__2 V_4, System.Exception V_5) ~IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__2.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_0088 -IL_000e: nop -IL_000f: ldarg.0 IL_0010: ldarg.0 IL_0011: ldfld ""int[] Test.<F>d__2.array"" IL_0016: ldc.i4.1 IL_0017: ldelema ""int"" IL_001c: dup IL_001d: ldind.i4 IL_001e: ldc.i4.2 IL_001f: add IL_0020: dup IL_0021: stloc.2 IL_0022: stind.i4 IL_0023: ldloc.2 IL_0024: stfld ""int Test.<F>d__2.<>s__1"" IL_0029: ldarg.0 IL_002a: ldarg.0 IL_002b: ldfld ""int[] Test.<F>d__2.array"" IL_0030: stfld ""int[] Test.<F>d__2.<>s__4"" IL_0035: ldarg.0 IL_0036: ldfld ""int[] Test.<F>d__2.<>s__4"" IL_003b: ldc.i4.3 IL_003c: ldelem.i4 IL_003d: pop IL_003e: ldarg.0 IL_003f: ldarg.0 IL_0040: ldfld ""int[] Test.<F>d__2.<>s__4"" IL_0045: ldc.i4.3 IL_0046: ldelem.i4 IL_0047: stfld ""int Test.<F>d__2.<>s__2"" IL_004c: call ""System.Threading.Tasks.Task<int> Test.G()"" IL_0051: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0056: stloc.3 ~IL_0057: ldloca.s V_3 IL_0059: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_005e: brtrue.s IL_00a4 IL_0060: ldarg.0 IL_0061: ldc.i4.0 IL_0062: dup IL_0063: stloc.0 IL_0064: stfld ""int Test.<F>d__2.<>1__state"" <IL_0069: ldarg.0 IL_006a: ldloc.3 IL_006b: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_0070: ldarg.0 IL_0071: stloc.s V_4 IL_0073: ldarg.0 IL_0074: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_0079: ldloca.s V_3 IL_007b: ldloca.s V_4 IL_007d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<F>d__2>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<F>d__2)"" IL_0082: nop IL_0083: leave IL_0110 >IL_0088: ldarg.0 IL_0089: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_008e: stloc.3 IL_008f: ldarg.0 IL_0090: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_0095: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_009b: ldarg.0 IL_009c: ldc.i4.m1 IL_009d: dup IL_009e: stloc.0 IL_009f: stfld ""int Test.<F>d__2.<>1__state"" IL_00a4: ldarg.0 IL_00a5: ldloca.s V_3 IL_00a7: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00ac: stfld ""int Test.<F>d__2.<>s__3"" IL_00b1: ldarg.0 IL_00b2: ldfld ""int Test.<F>d__2.<>s__1"" IL_00b7: ldarg.0 IL_00b8: ldfld ""int[] Test.<F>d__2.<>s__4"" IL_00bd: ldc.i4.3 IL_00be: ldarg.0 IL_00bf: ldfld ""int Test.<F>d__2.<>s__2"" IL_00c4: ldarg.0 IL_00c5: ldfld ""int Test.<F>d__2.<>s__3"" IL_00ca: add IL_00cb: dup IL_00cc: stloc.2 IL_00cd: stelem.i4 IL_00ce: ldloc.2 IL_00cf: ldc.i4.4 IL_00d0: call ""int Test.H(int, int, int)"" IL_00d5: pop IL_00d6: ldarg.0 IL_00d7: ldnull IL_00d8: stfld ""int[] Test.<F>d__2.<>s__4"" -IL_00dd: ldc.i4.1 IL_00de: stloc.1 IL_00df: leave.s IL_00fb } catch System.Exception { ~IL_00e1: stloc.s V_5 IL_00e3: ldarg.0 IL_00e4: ldc.i4.s -2 IL_00e6: stfld ""int Test.<F>d__2.<>1__state"" IL_00eb: ldarg.0 IL_00ec: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_00f1: ldloc.s V_5 IL_00f3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00f8: nop IL_00f9: leave.s IL_0110 } -IL_00fb: ldarg.0 IL_00fc: ldc.i4.s -2 IL_00fe: stfld ""int Test.<F>d__2.<>1__state"" ~IL_0103: ldarg.0 IL_0104: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_0109: ldloc.1 IL_010a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_010f: nop IL_0110: ret }", sequencePoints: "Test+<F>d__2.MoveNext"); } [Fact] public void SpillSequencesRelease() { var source = @" using System.Threading.Tasks; public class Test { public static int H(int a, int b, int c) { return a; } public static Task<int> G() { return null; } public static async Task<int> F(int[] array) { H(array[1] += 2, array[3] += await G(), 4); return 1; } } "; var v = CompileAndVerify(source, options: TestOptions.ReleaseDll); v.VerifyIL("Test.<F>d__2.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 251 (0xfb) .maxstack 5 .locals init (int V_0, int V_1, int V_2, int V_3, System.Runtime.CompilerServices.TaskAwaiter<int> V_4, System.Exception V_5) ~IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__2.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_007d -IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""int[] Test.<F>d__2.array"" IL_0011: ldc.i4.1 IL_0012: ldelema ""int"" IL_0017: dup IL_0018: ldind.i4 IL_0019: ldc.i4.2 IL_001a: add IL_001b: dup IL_001c: stloc.3 IL_001d: stind.i4 IL_001e: ldloc.3 IL_001f: stfld ""int Test.<F>d__2.<>7__wrap1"" IL_0024: ldarg.0 IL_0025: ldarg.0 IL_0026: ldfld ""int[] Test.<F>d__2.array"" IL_002b: stfld ""int[] Test.<F>d__2.<>7__wrap3"" IL_0030: ldarg.0 IL_0031: ldfld ""int[] Test.<F>d__2.<>7__wrap3"" IL_0036: ldc.i4.3 IL_0037: ldelem.i4 IL_0038: pop IL_0039: ldarg.0 IL_003a: ldarg.0 IL_003b: ldfld ""int[] Test.<F>d__2.<>7__wrap3"" IL_0040: ldc.i4.3 IL_0041: ldelem.i4 IL_0042: stfld ""int Test.<F>d__2.<>7__wrap2"" IL_0047: call ""System.Threading.Tasks.Task<int> Test.G()"" IL_004c: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0051: stloc.s V_4 ~IL_0053: ldloca.s V_4 IL_0055: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_005a: brtrue.s IL_009a IL_005c: ldarg.0 IL_005d: ldc.i4.0 IL_005e: dup IL_005f: stloc.0 IL_0060: stfld ""int Test.<F>d__2.<>1__state"" <IL_0065: ldarg.0 IL_0066: ldloc.s V_4 IL_0068: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_006d: ldarg.0 IL_006e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_0073: ldloca.s V_4 IL_0075: ldarg.0 IL_0076: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<F>d__2>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<F>d__2)"" IL_007b: leave.s IL_00fa >IL_007d: ldarg.0 IL_007e: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_0083: stloc.s V_4 IL_0085: ldarg.0 IL_0086: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_008b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0091: ldarg.0 IL_0092: ldc.i4.m1 IL_0093: dup IL_0094: stloc.0 IL_0095: stfld ""int Test.<F>d__2.<>1__state"" IL_009a: ldloca.s V_4 IL_009c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00a1: stloc.2 IL_00a2: ldarg.0 IL_00a3: ldfld ""int Test.<F>d__2.<>7__wrap1"" IL_00a8: ldarg.0 IL_00a9: ldfld ""int[] Test.<F>d__2.<>7__wrap3"" IL_00ae: ldc.i4.3 IL_00af: ldarg.0 IL_00b0: ldfld ""int Test.<F>d__2.<>7__wrap2"" IL_00b5: ldloc.2 IL_00b6: add IL_00b7: dup IL_00b8: stloc.3 IL_00b9: stelem.i4 IL_00ba: ldloc.3 IL_00bb: ldc.i4.4 IL_00bc: call ""int Test.H(int, int, int)"" IL_00c1: pop IL_00c2: ldarg.0 IL_00c3: ldnull IL_00c4: stfld ""int[] Test.<F>d__2.<>7__wrap3"" -IL_00c9: ldc.i4.1 IL_00ca: stloc.1 IL_00cb: leave.s IL_00e6 } catch System.Exception { ~IL_00cd: stloc.s V_5 IL_00cf: ldarg.0 IL_00d0: ldc.i4.s -2 IL_00d2: stfld ""int Test.<F>d__2.<>1__state"" IL_00d7: ldarg.0 IL_00d8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_00dd: ldloc.s V_5 IL_00df: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00e4: leave.s IL_00fa } -IL_00e6: ldarg.0 IL_00e7: ldc.i4.s -2 IL_00e9: stfld ""int Test.<F>d__2.<>1__state"" ~IL_00ee: ldarg.0 IL_00ef: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_00f4: ldloc.1 IL_00f5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00fa: ret }", sequencePoints: "Test+<F>d__2.MoveNext"); } [Fact] public void SpillSequencesInConditionalExpression1() { var source = @" using System.Threading.Tasks; public class Test { public static int H(int a, int b, int c) { return a; } public static Task<int> G() { return null; } public static async Task<int> F(int[] array) { H(0, (1 == await G()) ? array[3] += await G() : 1, 4); return 1; } } "; CompileAndVerify(source, options: TestOptions.DebugDll); } [Fact] public void SpillSequencesInNullCoalescingOperator1() { var source = @" using System.Threading.Tasks; public class C { public static int H(int a, object b, int c) { return a; } public static object O(int a) { return null; } public static Task<int> G() { return null; } public static async Task<int> F(int[] array) { H(0, O(array[0] += await G()) ?? (array[1] += await G()), 4); return 1; } } "; CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { AssertEx.Equal(new[] { "<>1__state", "<>t__builder", "array", "<>7__wrap1", "<>7__wrap2", "<>u__1", "<>7__wrap3", "<>7__wrap4", }, module.GetFieldNames("C.<F>d__3")); }); CompileAndVerify(source, verify: Verification.Passes, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { AssertEx.Equal(new[] { "<>1__state", "<>t__builder", "array", "<>s__1", "<>s__2", "<>s__3", "<>s__4", "<>s__5", "<>s__6", "<>s__7", "<>u__1", "<>s__8" }, module.GetFieldNames("C.<F>d__3")); }); } [WorkItem(4628, "https://github.com/dotnet/roslyn/issues/4628")] [Fact] public void AsyncWithShortCircuiting001() { var source = @" using System; using System.Threading.Tasks; namespace AsyncConditionalBug { class Program { private readonly bool b=true; private async Task AsyncMethod() { Console.WriteLine(b && await Task.FromResult(false)); Console.WriteLine(b); } static void Main(string[] args) { new Program().AsyncMethod().Wait(); } } }"; var expected = @" False True "; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(4628, "https://github.com/dotnet/roslyn/issues/4628")] [Fact] public void AsyncWithShortCircuiting002() { var source = @" using System; using System.Threading.Tasks; namespace AsyncConditionalBug { class Program { private static readonly bool b=true; private async Task AsyncMethod() { Console.WriteLine(b && await Task.FromResult(false)); Console.WriteLine(b); } static void Main(string[] args) { new Program().AsyncMethod().Wait(); } } }"; var expected = @" False True "; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(4628, "https://github.com/dotnet/roslyn/issues/4628")] [Fact] public void AsyncWithShortCircuiting003() { var source = @" using System; using System.Threading.Tasks; namespace AsyncConditionalBug { class Program { private readonly string NULL = null; private async Task AsyncMethod() { Console.WriteLine(NULL ?? await Task.FromResult(""hello"")); Console.WriteLine(NULL); } static void Main(string[] args) { new Program().AsyncMethod().Wait(); } } }"; var expected = @" hello "; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(4638, "https://github.com/dotnet/roslyn/issues/4638")] [Fact] public void AsyncWithShortCircuiting004() { var source = @" using System; using System.Threading.Tasks; namespace AsyncConditionalBug { class Program { static void Main(string[] args) { try { DoSomething(Tuple.Create(1.ToString(), Guid.NewGuid())).GetAwaiter().GetResult(); } catch (Exception ex) { System.Console.Write(ex.Message); } } public static async Task DoSomething(Tuple<string, Guid> item) { if (item.Item2 != null || await IsValid(item.Item2)) { throw new Exception(""Not Valid!""); }; } private static async Task<bool> IsValid(Guid id) { return false; } } }"; var expected = @" Not Valid! "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void SpillSequencesInLogicalBinaryOperator1() { var source = @" using System.Threading.Tasks; public class Test { public static int H(int a, bool b, int c) { return a; } public static bool B(int a) { return true; } public static Task<int> G() { return null; } public static async Task<int> F(int[] array) { H(0, B(array[0] += await G()) || B(array[1] += await G()), 4); return 1; } } "; CompileAndVerify(source, options: TestOptions.DebugDll); } [Fact] public void SpillArray01() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { tests++; int[] arr = new int[await GetVal(4)]; if (arr.Length == 4) Driver.Count++; //multidimensional tests++; decimal[,] arr2 = new decimal[await GetVal(4), await GetVal(4)]; if (arr2.Rank == 2 && arr2.Length == 16) Driver.Count++; arr2 = new decimal[4, await GetVal(4)]; if (arr2.Rank == 2 && arr2.Length == 16) Driver.Count++; tests++; arr2 = new decimal[await GetVal(4), 4]; if (arr2.Rank == 2 && arr2.Length == 16) Driver.Count++; //jagged array tests++; decimal?[][] arr3 = new decimal?[await GetVal(4)][]; if (arr3.Rank == 2 && arr3.Length == 4) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray02_1() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { tests++; int[] arr = new int[await GetVal(4)]; if (arr.Length == 4) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray02_2() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { int[] arr = new int[4]; tests++; arr[0] = await GetVal(4); if (arr[0] == 4) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray02_3() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { int[] arr = new int[4]; arr[0] = 4; tests++; arr[0] += await GetVal(4); if (arr[0] == 8) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray02_4() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { int[] arr = new int[] { 8, 0, 0, 0 }; tests++; arr[1] += await (GetVal(arr[0])); if (arr[1] == 8) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray02_5() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { int[] arr = new int[] { 8, 8, 0, 0 }; tests++; arr[1] += await (GetVal(arr[await GetVal(0)])); if (arr[1] == 16) Driver.Count++; tests++; arr[await GetVal(2)]++; if (arr[2] == 1) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray02_6() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { int[] arr = new int[4]; tests++; arr[await GetVal(2)]++; if (arr[2] == 1) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray03() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int tests = 0; try { int[,] arr = new int[await GetVal(4), await GetVal(4)]; tests++; arr[0, 0] = await GetVal(4); if (arr[0, await (GetVal(0))] == 4) Driver.Count++; tests++; arr[0, 0] += await GetVal(4); if (arr[0, 0] == 8) Driver.Count++; tests++; arr[1, 1] += await (GetVal(arr[0, 0])); if (arr[1, 1] == 8) Driver.Count++; tests++; arr[1, 1] += await (GetVal(arr[0, await GetVal(0)])); if (arr[1, 1] == 16) Driver.Count++; tests++; arr[2, await GetVal(2)]++; if (arr[2, 2] == 1) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArray04() { var source = @" using System.Threading; using System.Threading.Tasks; using System; struct MyStruct<T> { T t { get; set; } public T this[T index] { get { return t; } set { t = value; } } } struct TestCase { public async void Run() { try { MyStruct<int> ms = new MyStruct<int>(); var x = ms[index: await Goo()]; } finally { Driver.CompletedSignal.Set(); } } public async Task<int> Goo() { await Task.Delay(1); return 1; } } class Driver { public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); } }"; CompileAndVerify(source, ""); } [Fact] public void SpillArrayAssign() { var source = @" using System; using System.Threading.Tasks; class TestCase { static int[] arr = new int[4]; static async Task Run() { arr[0] = await Task.Factory.StartNew(() => 42); } static void Main() { Task task = Run(); task.Wait(); Console.WriteLine(arr[0]); } }"; var expected = @" 42 "; CompileAndVerify(source, expected); } [WorkItem(19609, "https://github.com/dotnet/roslyn/issues/19609")] [Fact] public void SpillArrayAssign2() { var source = @" using System.Threading.Tasks; class Program { static int[] array = new int[5]; static void Main(string[] args) { try { System.Console.WriteLine(""test not awaited""); TestNotAwaited().Wait(); } catch { System.Console.WriteLine(""exception thrown""); } System.Console.WriteLine(); try { System.Console.WriteLine(""test awaited""); TestAwaited().Wait(); } catch { System.Console.WriteLine(""exception thrown""); } } static async Task TestNotAwaited() { array[6] = Moo1(); } static async Task TestAwaited() { array[6] = await Moo(); } static int Moo1() { System.Console.WriteLine(""hello""); return 123; } static async Task<int> Moo() { System.Console.WriteLine(""hello""); return 123; } }"; var expected = @" test not awaited hello exception thrown test awaited hello exception thrown "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void SpillArrayLocal() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run<T>(T t) where T : struct { int[] arr = new int[2] { -1, 42 }; int tests = 0; try { tests++; int t1 = arr[await GetVal(1)]; if (t1 == 42) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(6); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArrayCompoundAssignmentLValue() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class Driver { static int[] arr; static async Task Run() { arr = new int[1]; arr[0] += await Task.Factory.StartNew(() => 42); } static void Main() { Run().Wait(); Console.WriteLine(arr[0]); } }"; var expected = @" 42 "; CompileAndVerify(source, expected); } [Fact] public void SpillArrayCompoundAssignmentLValueAwait() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class Driver { static int[] arr; static async Task Run() { arr = new int[1]; arr[await Task.Factory.StartNew(() => 0)] += await Task.Factory.StartNew(() => 42); } static void Main() { Run().Wait(); Console.WriteLine(arr[0]); } }"; var expected = @" 42 "; CompileAndVerify(source, expected); } [Fact] public void SpillArrayCompoundAssignmentLValueAwait2() { var source = @" using System; using System.Threading; using System.Threading.Tasks; struct S1 { public int x; } struct S2 { public S1 s1; } class Driver { static async Task<int> Run() { var arr = new S2[1]; arr[await Task.Factory.StartNew(() => 0)].s1.x += await Task.Factory.StartNew(() => 42); return arr[await Task.Factory.StartNew(() => 0)].s1.x; } static void Main() { var t = Run(); t.Wait(); Console.WriteLine(t.Result); } }"; var expected = @" 42 "; CompileAndVerify(source, expected); } [Fact] public void DoubleSpillArrayCompoundAssignment() { var source = @" using System; using System.Threading; using System.Threading.Tasks; struct S1 { public int x; } struct S2 { public S1 s1; } class Driver { static async Task<int> Run() { var arr = new S2[1]; arr[await Task.Factory.StartNew(() => 0)].s1.x += (arr[await Task.Factory.StartNew(() => 0)].s1.x += await Task.Factory.StartNew(() => 42)); return arr[await Task.Factory.StartNew(() => 0)].s1.x; } static void Main() { var t = Run(); t.Wait(); Console.WriteLine(t.Result); } }"; var expected = @" 42 "; CompileAndVerify(source, expected); } [Fact] public void SpillArrayInitializers1() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run() { int tests = 0; try { //jagged array tests++; int[][] arr1 = new[] { new []{await GetVal(2),await GetVal(3)}, new []{4,await GetVal(5),await GetVal(6)} }; if (arr1[0][1] == 3 && arr1[1][1] == 5 && arr1[1][2] == 6) Driver.Count++; tests++; int[][] arr2 = new[] { new []{await GetVal(2),await GetVal(3)}, await Goo() }; if (arr2[0][1] == 3 && arr2[1][1] == 2) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } public async Task<int[]> Goo() { await Task.Delay(1); return new int[] { 1, 2, 3 }; } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArrayInitializers2() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run() { int tests = 0; try { //jagged array tests++; int[,] arr1 = { {await GetVal(2),await GetVal(3)}, {await GetVal(5),await GetVal(6)} }; if (arr1[0, 1] == 3 && arr1[1, 0] == 5 && arr1[1, 1] == 6) Driver.Count++; tests++; int[,] arr2 = { {await GetVal(2),3}, {4,await GetVal(5)} }; if (arr2[0, 1] == 3 && arr2[1, 1] == 5) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected); } [Fact] public void SpillArrayInitializers3() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run() { int tests = 0; try { //jagged array tests++; int[][] arr1 = new[] { new []{await GetVal(2),await Task.Run<int>(async()=>{await Task.Delay(1);return 3;})}, new []{await GetVal(5),4,await Task.Run<int>(async()=>{await Task.Delay(1);return 6;})} }; if (arr1[0][1] == 3 && arr1[1][1] == 4 && arr1[1][2] == 6) Driver.Count++; tests++; dynamic arr2 = new[] { new []{await GetVal(2),3}, await Goo() }; if (arr2[0][1] == 3 && arr2[1][1] == 2) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } public async Task<int[]> Goo() { await Task.Delay(1); return new int[] { 1, 2, 3 }; } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expected, references: new[] { CSharpRef }); } [Fact] public void SpillNestedExpressionInArrayInitializer() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<int[,]> Run() { return new int[,] { {1, 2, 21 + (await Task.Factory.StartNew(() => 21)) }, }; } public static void Main() { var t = Run(); t.Wait(); foreach (var xs in t.Result) { Console.WriteLine(xs); } } }"; var expected = @" 1 2 42 "; CompileAndVerify(source, expected); } [Fact] public void SpillConditionalAccess() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Test { class C1 { public int M(int x) { return x; } } public static int Get(int x) { Console.WriteLine(""> "" + x); return x; } public static async Task<int> F(int x) { return await Task.Factory.StartNew(() => x); } public static async Task<int?> G() { var c = new C1(); return c?.M(await F(Get(42))); } public static void Main() { var t = G(); System.Console.WriteLine(t.Result); } }"; var expected = @" > 42 42"; CompileAndVerify(source, expected); } [Fact] public void AssignToAwait() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class S { public int x = -1; } class Test { static S _s = new S(); public static async Task<S> GetS() { return await Task.Factory.StartNew(() => _s); } public static async Task Run() { (await GetS()).x = 42; Console.WriteLine(_s.x); } } class Driver { static void Main() { Test.Run().Wait(); } }"; var expected = @" 42 "; CompileAndVerify(source, expected); } [Fact] public void AssignAwaitToAwait() { var source = @" using System; using System.Threading.Tasks; class S { public int x = -1; } class Test { static S _s = new S(); public static async Task<S> GetS() { return await Task.Factory.StartNew(() => _s); } public static async Task Run() { (await GetS()).x = await Task.Factory.StartNew(() => 42); Console.WriteLine(_s.x); } } class Driver { static void Main() { Test.Run().Wait(); } }"; var expected = @" 42 "; CompileAndVerify(source, expected); } [ConditionalFact(typeof(DesktopOnly))] public void SpillArglist() { var source = @" using System; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; class TestCase { static StringBuilder sb = new StringBuilder(); public async Task Run() { try { Bar(__arglist(One(), await Two())); if (sb.ToString() == ""OneTwo"") Driver.Result = 0; } finally { Driver.CompleteSignal.Set(); } } int One() { sb.Append(""One""); return 1; } async Task<int> Two() { await Task.Delay(1); sb.Append(""Two""); return 2; } void Bar(__arglist) { var ai = new ArgIterator(__arglist); while (ai.GetRemainingCount() > 0) Console.WriteLine( __refvalue(ai.GetNextArg(), int)); } } class Driver { static public AutoResetEvent CompleteSignal = new AutoResetEvent(false); public static int Result = -1; public static void Main() { TestCase tc = new TestCase(); tc.Run(); CompleteSignal.WaitOne(); Console.WriteLine(Result); } }"; var expected = @" 1 2 0 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void SpillObjectInitializer1() { var source = @" using System; using System.Collections; using System.Threading; using System.Threading.Tasks; struct TestCase : IEnumerable { int X; public async Task Run() { int test = 0; int count = 0; try { test++; var x = new TestCase { X = await Bar() }; if (x.X == 1) count++; } finally { Driver.Result = test - count; Driver.CompleteSignal.Set(); } } async Task<int> Bar() { await Task.Delay(1); return 1; } public IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } } class Driver { static public AutoResetEvent CompleteSignal = new AutoResetEvent(false); public static int Result = -1; public static void Main() { TestCase tc = new TestCase(); tc.Run(); CompleteSignal.WaitOne(); Console.WriteLine(Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void SpillWithByRefArguments01() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class BaseTestCase { public void GooRef(ref decimal d, int x, out decimal od) { od = d; d++; } public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } } class TestCase : BaseTestCase { public async void Run() { int tests = 0; try { decimal d = 1; decimal od; tests++; base.GooRef(ref d, await base.GetVal(4), out od); if (d == 2 && od == 1) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void SpillOperator_Compound1() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run() { int tests = 0; try { tests++; int[] x = new int[] { 1, 2, 3, 4 }; x[await GetVal(0)] += await GetVal(4); if (x[0] == 5) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void SpillOperator_Compound2() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run() { int tests = 0; try { tests++; int[] x = new int[] { 1, 2, 3, 4 }; x[await GetVal(0)] += await GetVal(4); if (x[0] == 5) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Async_StackSpill_Argument_Generic04() { var source = @" using System; using System.Threading.Tasks; public class mc<T> { async public System.Threading.Tasks.Task<dynamic> Goo<V>(T t, V u) { await Task.Delay(1); return u; } } class Test { static async Task<int> Goo() { dynamic mc = new mc<string>(); var rez = await mc.Goo<string>(null, await ((Func<Task<string>>)(async () => { await Task.Delay(1); return ""Test""; }))()); if (rez == ""Test"") return 0; return 1; } static void Main() { Console.WriteLine(Goo().Result); } }"; CompileAndVerify(source, "0", references: new[] { CSharpRef }); } [Fact] public void AsyncStackSpill_assign01() { var source = @" using System; using System.Threading; using System.Threading.Tasks; struct TestCase { private int val; public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } public async void Run() { int tests = 0; try { tests++; int[] x = new int[] { 1, 2, 3, 4 }; val = x[await GetVal(0)] += await GetVal(4); if (x[0] == 5 && val == await GetVal(5)) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void SpillCollectionInitializer() { var source = @" using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; struct PrivateCollection : IEnumerable { public List<int> lst; //public so we can check the values public void Add(int x) { if (lst == null) lst = new List<int>(); lst.Add(x); } public IEnumerator GetEnumerator() { return lst as IEnumerator; } } class TestCase { public async Task<T> GetValue<T>(T x) { await Task.Delay(1); return x; } public async void Run() { int tests = 0; try { tests++; var myCol = new PrivateCollection() { await GetValue(1), await GetValue(2) }; if (myCol.lst[0] == 1 && myCol.lst[1] == 2) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test completes, set the flag. Driver.CompletedSignal.Set(); } } public int Goo { get; set; } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void SpillRefExpr() { var source = @" using System; using System.Threading.Tasks; class MyClass { public int Field; } class TestCase { public static int Goo(ref int x, int y) { return x + y; } public async Task<int> Run() { return Goo( ref (new MyClass() { Field = 21 }.Field), await Task.Factory.StartNew(() => 21)); } } static class Driver { static void Main() { var t = new TestCase().Run(); t.Wait(); Console.WriteLine(t.Result); } }"; CompileAndVerify(source, "42"); } [Fact] public void SpillManagedPointerAssign03() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task<T> GetVal<T>(T t) { await Task.Delay(1); return t; } class PrivClass { internal struct ValueT { public int Field; } internal ValueT[] arr = new ValueT[3]; } private PrivClass myClass; public async void Run() { int tests = 0; this.myClass = new PrivClass(); try { tests++; this.myClass.arr[0].Field = await GetVal(4); if (myClass.arr[0].Field == 4) Driver.Count++; tests++; this.myClass.arr[0].Field += await GetVal(4); if (myClass.arr[0].Field == 8) Driver.Count++; tests++; this.myClass.arr[await GetVal(1)].Field += await GetVal(4); if (myClass.arr[1].Field == 4) Driver.Count++; tests++; this.myClass.arr[await GetVal(1)].Field++; if (myClass.arr[1].Field == 5) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact, WorkItem(36443, "https://github.com/dotnet/roslyn/issues/36443")] public void SpillCompoundAssignmentToNullableMemberOfLocal_01() { var source = @" using System; using System.Threading.Tasks; struct S { int? i; static async Task Main() { S s = default; Console.WriteLine(s.i += await GetInt()); } static Task<int?> GetInt() => Task.FromResult((int?)1); }"; CompileAndVerify(source, expectedOutput: "", options: TestOptions.ReleaseExe); CompileAndVerify(source, expectedOutput: "", options: TestOptions.DebugExe); } [Fact, WorkItem(36443, "https://github.com/dotnet/roslyn/issues/36443")] public void SpillCompoundAssignmentToNullableMemberOfLocal_02() { var source = @" class C { static async System.Threading.Tasks.Task Main() { await new C().M(); } int field = 1; async System.Threading.Tasks.Task M() { this.field += await M2(); System.Console.Write(this.field); } async System.Threading.Tasks.Task<int> M2() { await System.Threading.Tasks.Task.Yield(); return 42; } } "; CompileAndVerify(source, expectedOutput: "43", options: TestOptions.DebugExe); CompileAndVerify(source, expectedOutput: "43", options: TestOptions.ReleaseExe); } [Fact, WorkItem(36443, "https://github.com/dotnet/roslyn/issues/36443")] public void SpillCompoundAssignmentToNullableMemberOfLocal_03() { var source = @" class C { static async System.Threading.Tasks.Task Main() { await new C().M(); } int? field = 1; async System.Threading.Tasks.Task M() { this.field += await M2(); System.Console.Write(this.field); } async System.Threading.Tasks.Task<int?> M2() { await System.Threading.Tasks.Task.Yield(); return 42; } } "; CompileAndVerify(source, expectedOutput: "43", options: TestOptions.ReleaseExe); CompileAndVerify(source, expectedOutput: "43", options: TestOptions.DebugExe); } [Fact, WorkItem(36443, "https://github.com/dotnet/roslyn/issues/36443")] public void SpillCompoundAssignmentToNullableMemberOfLocal_04() { var source = @" using System; using System.Threading.Tasks; struct S { int? i; static async Task M(S s = default) { s = default; Console.WriteLine(s.i += await GetInt()); } static async Task Main() { M(); } static Task<int?> GetInt() => Task.FromResult((int?)1); }"; CompileAndVerify(source, expectedOutput: "", options: TestOptions.ReleaseExe); CompileAndVerify(source, expectedOutput: "", options: TestOptions.DebugExe); } [Fact] public void SpillSacrificialRead() { var source = @" using System; using System.Threading.Tasks; class C { static void F1(ref int x, int y, int z) { x += y + z; } static int F0() { Console.WriteLine(-1); return 0; } static async Task<int> F2() { int[] x = new int[1] { 21 }; x = null; F1(ref x[0], F0(), await Task.Factory.StartNew(() => 21)); return x[0]; } public static void Main() { var t = F2(); try { t.Wait(); } catch(Exception e) { Console.WriteLine(0); return; } Console.WriteLine(-1); } }"; CompileAndVerify(source, "0"); } [Fact] public void SpillRefThisStruct() { var source = @" using System; using System.Threading.Tasks; struct s1 { public int X; public async void Goo1() { Bar(ref this, await Task<int>.FromResult(42)); } public void Goo2() { Bar(ref this, 42); } public void Bar(ref s1 x, int y) { x.X = 42; } } class c1 { public int X; public async void Goo1() { Bar(this, await Task<int>.FromResult(42)); } public void Goo2() { Bar(this, 42); } public void Bar(c1 x, int y) { x.X = 42; } } class C { public static void Main() { { s1 s; s.X = -1; s.Goo1(); Console.WriteLine(s.X); } { s1 s; s.X = -1; s.Goo2(); Console.WriteLine(s.X); } { c1 c = new c1(); c.X = -1; c.Goo1(); Console.WriteLine(c.X); } { c1 c = new c1(); c.X = -1; c.Goo2(); Console.WriteLine(c.X); } } }"; var expected = @" -1 42 42 42 "; CompileAndVerify(source, expected); } [Fact] [WorkItem(13734, "https://github.com/dotnet/roslyn/issues/13734")] public void MethodGroupConversionNoSpill() { string source = @" using System.Threading.Tasks; using System; public class AsyncBug { public static void Main() { Boom().GetAwaiter().GetResult(); } public static async Task Boom() { Func<Type> f = (await Task.FromResult(1)).GetType; Console.WriteLine(f()); } } "; var v = CompileAndVerify(source, "System.Int32"); } [Fact] [WorkItem(13734, "https://github.com/dotnet/roslyn/issues/13734")] public void MethodGroupConversionWithSpill() { string source = @" using System.Threading.Tasks; using System; using System.Linq; using System.Collections.Generic; namespace AsyncBug { class Program { private class SomeClass { public bool Method(int value) { return value % 2 == 0; } } private async Task<SomeClass> Danger() { await Task.Yield(); return new SomeClass(); } private async Task<IEnumerable<bool>> Killer() { return (new int[] {1, 2, 3, 4, 5}).Select((await Danger()).Method); } static void Main(string[] args) { foreach (var b in new Program().Killer().GetAwaiter().GetResult()) { Console.WriteLine(b); } } } } "; var expected = new bool[] { false, true, false, true, false }.Aggregate("", (str, next) => str += $"{next}{Environment.NewLine}"); var v = CompileAndVerify(source, expected); } [Fact] [WorkItem(17706, "https://github.com/dotnet/roslyn/issues/17706")] public void SpillAwaitBeforeRefReordered() { string source = @" using System.Threading.Tasks; public class C { private static int i; static ref int P => ref i; static void Assign(ref int first, int second) { first = second; } public static async Task M(Task<int> t) { // OK: await goes before the ref Assign(second: await t, first: ref P); } public static void Main() { M(Task.FromResult(42)).Wait(); System.Console.WriteLine(i); } } "; var v = CompileAndVerify(source, "42"); } [Fact] [WorkItem(17706, "https://github.com/dotnet/roslyn/issues/17706")] public void SpillRefBeforeAwaitReordered() { string source = @" using System.Threading.Tasks; public class C { private static int i; static ref int P => ref i; static void Assign(int first, ref int second) { second = first; } public static async Task M(Task<int> t) { // ERROR: await goes after the ref Assign(second: ref P, first: await t); } public static void Main() { M(Task.FromResult(42)).Wait(); System.Console.WriteLine(i); } } "; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe); comp.VerifyEmitDiagnostics( // (18,28): error CS8178: 'await' cannot be used in an expression containing a call to 'C.P.get' because it returns by reference // Assign(second: ref P, first: await t); Diagnostic(ErrorCode.ERR_RefReturningCallAndAwait, "P").WithArguments("C.P.get").WithLocation(18, 28) ); } [Fact] [WorkItem(27831, "https://github.com/dotnet/roslyn/issues/27831")] public void AwaitWithInParameter_ArgModifier() { CreateCompilation(@" using System.Threading.Tasks; class Foo { async Task A(string s, Task<int> task) { C(in s, await task); } void C(in object obj, int length) {} }").VerifyDiagnostics( // (7,14): error CS1503: Argument 1: cannot convert from 'in string' to 'in object' // C(in s, await task); Diagnostic(ErrorCode.ERR_BadArgType, "s").WithArguments("1", "in string", "in object").WithLocation(7, 14)); } [Fact] [WorkItem(27831, "https://github.com/dotnet/roslyn/issues/27831")] public void AwaitWithInParameter_NoArgModifier() { CompileAndVerify(@" using System; using System.Threading.Tasks; class Foo { static async Task Main() { await A(""test"", Task.FromResult(4)); } static async Task A(string s, Task<int> task) { B(s, await task); } static void B(in object obj, int v) { Console.WriteLine(obj); Console.WriteLine(v); } }", expectedOutput: @" test 4 "); } [Fact, WorkItem(36856, "https://github.com/dotnet/roslyn/issues/36856")] public void Crash36856() { var source = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { } private static async Task Serialize() { System.Text.Json.Serialization.JsonSerializer.Parse<string>(await TestAsync()); } private static Task<byte[]> TestAsync() { return null; } } namespace System { public readonly ref struct ReadOnlySpan<T> { public static implicit operator ReadOnlySpan<T>(T[] array) { throw null; } } } namespace System.Text.Json.Serialization { public static class JsonSerializer { public static TValue Parse<TValue>(ReadOnlySpan<byte> utf8Json, JsonSerializerOptions options = null) { throw null; } } public sealed class JsonSerializerOptions { } } "; var v = CompileAndVerify(source, options: TestOptions.DebugExe); v.VerifyIL("Program.<Serialize>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 184 (0xb8) .maxstack 3 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter<byte[]> V_1, Program.<Serialize>d__1 V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Serialize>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_0047 IL_000e: nop IL_000f: call ""System.Threading.Tasks.Task<byte[]> Program.TestAsync()"" IL_0014: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<byte[]> System.Threading.Tasks.Task<byte[]>.GetAwaiter()"" IL_0019: stloc.1 IL_001a: ldloca.s V_1 IL_001c: call ""bool System.Runtime.CompilerServices.TaskAwaiter<byte[]>.IsCompleted.get"" IL_0021: brtrue.s IL_0063 IL_0023: ldarg.0 IL_0024: ldc.i4.0 IL_0025: dup IL_0026: stloc.0 IL_0027: stfld ""int Program.<Serialize>d__1.<>1__state"" IL_002c: ldarg.0 IL_002d: ldloc.1 IL_002e: stfld ""System.Runtime.CompilerServices.TaskAwaiter<byte[]> Program.<Serialize>d__1.<>u__1"" IL_0033: ldarg.0 IL_0034: stloc.2 IL_0035: ldarg.0 IL_0036: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Serialize>d__1.<>t__builder"" IL_003b: ldloca.s V_1 IL_003d: ldloca.s V_2 IL_003f: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<byte[]>, Program.<Serialize>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<byte[]>, ref Program.<Serialize>d__1)"" IL_0044: nop IL_0045: leave.s IL_00b7 IL_0047: ldarg.0 IL_0048: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<byte[]> Program.<Serialize>d__1.<>u__1"" IL_004d: stloc.1 IL_004e: ldarg.0 IL_004f: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<byte[]> Program.<Serialize>d__1.<>u__1"" IL_0054: initobj ""System.Runtime.CompilerServices.TaskAwaiter<byte[]>"" IL_005a: ldarg.0 IL_005b: ldc.i4.m1 IL_005c: dup IL_005d: stloc.0 IL_005e: stfld ""int Program.<Serialize>d__1.<>1__state"" IL_0063: ldarg.0 IL_0064: ldloca.s V_1 IL_0066: call ""byte[] System.Runtime.CompilerServices.TaskAwaiter<byte[]>.GetResult()"" IL_006b: stfld ""byte[] Program.<Serialize>d__1.<>s__1"" IL_0070: ldarg.0 IL_0071: ldfld ""byte[] Program.<Serialize>d__1.<>s__1"" IL_0076: call ""System.ReadOnlySpan<byte> System.ReadOnlySpan<byte>.op_Implicit(byte[])"" IL_007b: ldnull IL_007c: call ""string System.Text.Json.Serialization.JsonSerializer.Parse<string>(System.ReadOnlySpan<byte>, System.Text.Json.Serialization.JsonSerializerOptions)"" IL_0081: pop IL_0082: ldarg.0 IL_0083: ldnull IL_0084: stfld ""byte[] Program.<Serialize>d__1.<>s__1"" IL_0089: leave.s IL_00a3 } catch System.Exception { IL_008b: stloc.3 IL_008c: ldarg.0 IL_008d: ldc.i4.s -2 IL_008f: stfld ""int Program.<Serialize>d__1.<>1__state"" IL_0094: ldarg.0 IL_0095: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Serialize>d__1.<>t__builder"" IL_009a: ldloc.3 IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a0: nop IL_00a1: leave.s IL_00b7 } IL_00a3: ldarg.0 IL_00a4: ldc.i4.s -2 IL_00a6: stfld ""int Program.<Serialize>d__1.<>1__state"" IL_00ab: ldarg.0 IL_00ac: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Serialize>d__1.<>t__builder"" IL_00b1: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b6: nop IL_00b7: ret } ", sequencePoints: "Program.Serialize"); } [Fact, WorkItem(37461, "https://github.com/dotnet/roslyn/issues/37461")] public void ShouldNotSpillStackallocToField_01() { var source = @" using System; using System.Threading.Tasks; public class P { static async Task Main() { await Async1(F1(), G(F2(), stackalloc int[] { 40, 500, 6000 })); } static int F1() => 70000; static int F2() => 800000; static int G(int k, Span<int> span) => k + span.Length + span[0] + span[1] + span[2]; static Task Async1(int k, int i) { Console.WriteLine(k + i); return Task.Delay(1); } } "; var expectedOutput = @"876543"; var comp = CreateCompilationWithMscorlibAndSpan(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var v = CompileAndVerify( compilation: comp, expectedOutput: expectedOutput, verify: Verification.Fails // localloc is not verifiable. ); comp = CreateCompilationWithMscorlibAndSpan(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); v = CompileAndVerify( compilation: comp, expectedOutput: expectedOutput, verify: Verification.Fails // localloc is not verifiable. ); } [Fact, WorkItem(37461, "https://github.com/dotnet/roslyn/issues/37461")] public void ShouldNotSpillStackallocToField_02() { var source = @" using System; using System.Threading.Tasks; public class P { static async Task Main() { await Async1(F1(), G(F2(), stackalloc int[] { 40, await Task.FromResult(500), 6000 })); } static int F1() => 70000; static int F2() => 800000; static int G(int k, Span<int> span) => k + span.Length + span[0] + span[1] + span[2]; static Task Async1(int k, int i) { Console.WriteLine(k + i); return Task.Delay(1); } } "; var expectedOutput = @"876543"; var comp = CreateCompilationWithMscorlibAndSpan(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var v = CompileAndVerify( compilation: comp, expectedOutput: expectedOutput, verify: Verification.Fails // localloc is not verifiable. ); comp = CreateCompilationWithMscorlibAndSpan(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); v = CompileAndVerify( compilation: comp, expectedOutput: expectedOutput, verify: Verification.Fails // localloc is not verifiable. ); } [Fact, WorkItem(37461, "https://github.com/dotnet/roslyn/issues/37461")] public void ShouldNotSpillStackallocToField_03() { var source = @" using System; using System.Threading.Tasks; public class P { static async Task Main() { await Async1(F1(), G(F2(), stackalloc int[] { 1, 2, 3 }, await F3())); } static object F1() => 1; static object F2() => 1; static Task<object> F3() => Task.FromResult<object>(1); static int G(object obj, Span<int> span, object o2) => span.Length; static async Task Async1(Object obj, int i) { await Task.Delay(1); } } "; foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe }) { var comp = CreateCompilationWithMscorlibAndSpan(source, options: options); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (9,66): error CS4007: 'await' cannot be used in an expression containing the type 'System.Span<int>' // await Async1(F1(), G(F2(), stackalloc int[] { 1, 2, 3 }, await F3())); Diagnostic(ErrorCode.ERR_ByRefTypeAndAwait, "await F3()").WithArguments("System.Span<int>").WithLocation(9, 66) ); } } [Fact] public void SpillStateMachineTemps() { var source = @"using System; using System.Threading.Tasks; public class C { public static void Main() { Console.WriteLine(M1(new Q(), SF()).Result); } public static async Task<int> M1(object o, Task<bool> c) { return o switch { Q { F: { P1: true } } when await c => 1, // cached Q.F is alive Q { F: { P2: true } } => 2, _ => 3, }; } public static async Task<bool> SF() { await Task.Delay(10); return false; } } class Q { public F F => new F(true); } struct F { bool _result; public F(bool result) { _result = result; } public bool P1 => _result; public bool P2 => _result; } "; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "2"); CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: "2"); } [Fact] [WorkItem(37713, "https://github.com/dotnet/roslyn/issues/37713")] public void RefStructInAsyncStateMachineWithWhenClause() { var source = @" using System.Threading.Tasks; class Program { async Task<int> M1(object o, Task<bool> c, int r) { return o switch { Q { F: { P1: true } } when await c => r, // error: cached Q.F is alive Q { F: { P2: true } } => 2, _ => 3, }; } async Task<int> M2(object o, Task<bool> c, int r) { return o switch { Q { F: { P1: true } } when await c => r, // ok: only Q.P1 is live Q { F: { P1: true } } => 2, _ => 3, }; } async Task<int> M3(object o, bool c, Task<int> r) { return o switch { Q { F: { P1: true } } when c => await r, // ok: nothing alive at await Q { F: { P2: true } } => 2, _ => 3, }; } async Task<int> M4(object o, Task<bool> c, int r) { return o switch { Q { F: { P1: true } } when await c => r, // ok: no switch state is alive _ => 3, }; } } public class Q { public S F => throw null!; } public ref struct S { public bool P1 => true; public bool P2 => true; } "; CreateCompilation(source, options: TestOptions.DebugDll).VerifyDiagnostics().VerifyEmitDiagnostics( // (9,17): error CS4013: Instance of type 'S' cannot be used inside a nested function, query expression, iterator block or async method // Q { F: { P1: true } } when await c => r, // error: cached Q.F is alive Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "F").WithArguments("S").WithLocation(9, 17) ); CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics().VerifyEmitDiagnostics( // (9,17): error CS4013: Instance of type 'S' cannot be used inside a nested function, query expression, iterator block or async method // Q { F: { P1: true } } when await c => r, // error: cached Q.F is alive Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "F").WithArguments("S").WithLocation(9, 17) ); } [Fact] [WorkItem(37783, "https://github.com/dotnet/roslyn/issues/37783")] public void ExpressionLambdaWithObjectInitializer() { var source = @"using System; using System.Linq.Expressions; using System.Threading.Tasks; class Program { public static async Task Main() { int value = 42; Console.WriteLine(await M(() => new Box<int>() { Value = value })); } static Task<int> M(Expression<Func<Box<int>>> e) { return Task.FromResult(e.Compile()().Value); } } class Box<T> { public T Value; } "; CompileAndVerify(source, expectedOutput: "42", options: TestOptions.DebugExe); CompileAndVerify(source, expectedOutput: "42", options: TestOptions.ReleaseExe); } [Fact] [WorkItem(38309, "https://github.com/dotnet/roslyn/issues/38309")] public void ExpressionLambdaWithUserDefinedControlFlow() { var source = @"using System; using System.Linq.Expressions; using System.Threading.Tasks; namespace RoslynFailFastReproduction { static class Program { static async Task Main(string[] args) { await MainAsync(args); } static async Task MainAsync(string[] args) { Expression<Func<AltBoolean, AltBoolean>> expr = x => x && x; var result = await Task.FromResult(true); Console.WriteLine(result); } class AltBoolean { public static AltBoolean operator &(AltBoolean x, AltBoolean y) => default; public static bool operator true(AltBoolean x) => default; public static bool operator false(AltBoolean x) => default; } } } "; CompileAndVerify(source, expectedOutput: "True", options: TestOptions.DebugExe); CompileAndVerify(source, expectedOutput: "True", options: TestOptions.ReleaseExe); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_ClassFieldAccessOnProperty() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a) { a.B.x = await Write(""RHS""); } static async Task Main(string[] args) { await TestPropertyAccessThrows(); await TestFieldAccessThrows(); await TestPropertyAccessSucceeds(); } static async Task TestPropertyAccessThrows() { Console.WriteLine(nameof(TestPropertyAccessThrows)); A a = null; Console.WriteLine(""Before Assignment""); try { await Assign(a); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestFieldAccessThrows() { Console.WriteLine(nameof(TestFieldAccessThrows)); var a = new A(); Console.WriteLine(""Before Assignment""); try { await Assign(a); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestPropertyAccessSucceeds() { Console.WriteLine(nameof(TestPropertyAccessSucceeds)); var a = new A{ B = new B() }; Console.WriteLine(""Before Assignment a.B.x is: "" + a.B.x); await Assign(a); Console.WriteLine(""After Assignment a.B.x is: "" + a.B.x); } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public B B { get; set; } } class B { public int x; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestPropertyAccessThrows Before Assignment Caught NullReferenceException TestFieldAccessThrows Before Assignment RHS Caught NullReferenceException TestPropertyAccessSucceeds Before Assignment a.B.x is: 0 RHS After Assignment a.B.x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 184 (0xb8) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0054 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A Program.<Assign>d__0.a"" IL_0011: callvirt ""B A.B.get"" IL_0016: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_001b: ldstr ""RHS"" IL_0020: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0025: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_002a: stloc.2 IL_002b: ldloca.s V_2 IL_002d: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0032: brtrue.s IL_0070 IL_0034: ldarg.0 IL_0035: ldc.i4.0 IL_0036: dup IL_0037: stloc.0 IL_0038: stfld ""int Program.<Assign>d__0.<>1__state"" IL_003d: ldarg.0 IL_003e: ldloc.2 IL_003f: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0044: ldarg.0 IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_004a: ldloca.s V_2 IL_004c: ldarg.0 IL_004d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_0052: leave.s IL_00b7 IL_0054: ldarg.0 IL_0055: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_005a: stloc.2 IL_005b: ldarg.0 IL_005c: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0061: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0067: ldarg.0 IL_0068: ldc.i4.m1 IL_0069: dup IL_006a: stloc.0 IL_006b: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0070: ldloca.s V_2 IL_0072: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0077: stloc.1 IL_0078: ldarg.0 IL_0079: ldfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_007e: ldloc.1 IL_007f: stfld ""int B.x"" IL_0084: ldarg.0 IL_0085: ldnull IL_0086: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_008b: leave.s IL_00a4 } catch System.Exception { IL_008d: stloc.3 IL_008e: ldarg.0 IL_008f: ldc.i4.s -2 IL_0091: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0096: ldarg.0 IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_009c: ldloc.3 IL_009d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a2: leave.s IL_00b7 } IL_00a4: ldarg.0 IL_00a5: ldc.i4.s -2 IL_00a7: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00ac: ldarg.0 IL_00ad: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00b2: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b7: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_ClassFieldAccessOnArray() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A[] arr) { arr[0].x = await Write(""RHS""); } static async Task Main(string[] args) { await TestIndexerThrows(); await TestAssignmentThrows(); await TestIndexerSucceeds(); await TestReassignsArrayAndIndexerDuringAwait(); await TestReassignsTargetDuringAwait(); } static async Task TestIndexerThrows() { Console.WriteLine(nameof(TestIndexerThrows)); var arr = new A[0]; Console.WriteLine(""Before Assignment""); try { await Assign(arr); } catch (IndexOutOfRangeException) { Console.WriteLine(""Caught IndexOutOfRangeException""); } } static async Task TestAssignmentThrows() { Console.WriteLine(nameof(TestAssignmentThrows)); var arr = new A[1]; Console.WriteLine(""Before Assignment""); try { await Assign(arr); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestIndexerSucceeds() { Console.WriteLine(nameof(TestIndexerSucceeds)); var arr = new A[1]{ new A() }; Console.WriteLine(""Before Assignment arr[0].x is: "" + arr[0].x); await Assign(arr); Console.WriteLine(""After Assignment arr[0].x is: "" + arr[0].x); } static async Task TestReassignsArrayAndIndexerDuringAwait() { Console.WriteLine(nameof(TestReassignsArrayAndIndexerDuringAwait)); var a = new A(); var arr = new A[1]{ a }; var index = 0; Console.WriteLine(""Before Assignment arr.Length is: "" + arr.Length); Console.WriteLine(""Before Assignment a.x is: "" + a.x); arr[index].x = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment arr.Length is: "" + arr.Length); Console.WriteLine(""After Assignment a.x is: "" + a.x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); arr = new A[0]; index = 1; Console.WriteLine(s); return 42; } } static async Task TestReassignsTargetDuringAwait() { Console.WriteLine(nameof(TestReassignsTargetDuringAwait)); var a = new A(); var arr = new A[1]{ a }; Console.WriteLine(""Before Assignment arr[0].x is: "" + arr[0].x); Console.WriteLine(""Before Assignment arr[0].y is: "" + arr[0].y); Console.WriteLine(""Before Assignment a.x is: "" + a.x); arr[0].x = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment arr[0].x is: "" + arr[0].x); Console.WriteLine(""After Assignment arr[0].y is: "" + arr[0].y); Console.WriteLine(""After Assignment a.x is: "" + a.x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); arr[0] = new A{ y = true }; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public int x; public bool y; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestIndexerThrows Before Assignment Caught IndexOutOfRangeException TestAssignmentThrows Before Assignment RHS Caught NullReferenceException TestIndexerSucceeds Before Assignment arr[0].x is: 0 RHS After Assignment arr[0].x is: 42 TestReassignsArrayAndIndexerDuringAwait Before Assignment arr.Length is: 1 Before Assignment a.x is: 0 RHS After Assignment arr.Length is: 0 After Assignment a.x is: 42 TestReassignsTargetDuringAwait Before Assignment arr[0].x is: 0 Before Assignment arr[0].y is: False Before Assignment a.x is: 0 RHS After Assignment arr[0].x is: 0 After Assignment arr[0].y is: True After Assignment a.x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 181 (0xb5) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0051 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A[] Program.<Assign>d__0.arr"" IL_0011: ldc.i4.0 IL_0012: ldelem.ref IL_0013: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0018: ldstr ""RHS"" IL_001d: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0022: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0027: stloc.2 IL_0028: ldloca.s V_2 IL_002a: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002f: brtrue.s IL_006d IL_0031: ldarg.0 IL_0032: ldc.i4.0 IL_0033: dup IL_0034: stloc.0 IL_0035: stfld ""int Program.<Assign>d__0.<>1__state"" IL_003a: ldarg.0 IL_003b: ldloc.2 IL_003c: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0041: ldarg.0 IL_0042: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0047: ldloca.s V_2 IL_0049: ldarg.0 IL_004a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_004f: leave.s IL_00b4 IL_0051: ldarg.0 IL_0052: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0057: stloc.2 IL_0058: ldarg.0 IL_0059: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_005e: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0064: ldarg.0 IL_0065: ldc.i4.m1 IL_0066: dup IL_0067: stloc.0 IL_0068: stfld ""int Program.<Assign>d__0.<>1__state"" IL_006d: ldloca.s V_2 IL_006f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0074: stloc.1 IL_0075: ldarg.0 IL_0076: ldfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_007b: ldloc.1 IL_007c: stfld ""int A.x"" IL_0081: ldarg.0 IL_0082: ldnull IL_0083: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0088: leave.s IL_00a1 } catch System.Exception { IL_008a: stloc.3 IL_008b: ldarg.0 IL_008c: ldc.i4.s -2 IL_008e: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0093: ldarg.0 IL_0094: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0099: ldloc.3 IL_009a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_009f: leave.s IL_00b4 } IL_00a1: ldarg.0 IL_00a2: ldc.i4.s -2 IL_00a4: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00a9: ldarg.0 IL_00aa: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00af: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b4: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_StructFieldAccessOnArray() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A[] arr) { arr[0].x = await Write(""RHS""); } static async Task Main(string[] args) { await TestIndexerThrows(); await TestIndexerSucceeds(); await TestReassignsArrayAndIndexerDuringAwait(); await TestReassignsTargetDuringAwait(); } static async Task TestIndexerThrows() { Console.WriteLine(nameof(TestIndexerThrows)); var arr = new A[0]; Console.WriteLine(""Before Assignment""); try { await Assign(arr); } catch (IndexOutOfRangeException) { Console.WriteLine(""Caught IndexOutOfRangeException""); } } static async Task TestIndexerSucceeds() { Console.WriteLine(nameof(TestIndexerSucceeds)); var arr = new A[1]; Console.WriteLine(""Before Assignment arr[0].x is: "" + arr[0].x); await Assign(arr); Console.WriteLine(""After Assignment arr[0].x is: "" + arr[0].x); } static async Task TestReassignsArrayAndIndexerDuringAwait() { Console.WriteLine(nameof(TestReassignsArrayAndIndexerDuringAwait)); var arr = new A[1]; var arrCopy = arr; var index = 0; Console.WriteLine(""Before Assignment arr.Length is: "" + arr.Length); Console.WriteLine(""Before Assignment arrCopy[0].x is: "" + arrCopy[0].x); arr[index].x = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment arr.Length is: "" + arr.Length); Console.WriteLine(""After Assignment arrCopy[0].x is: "" + arrCopy[0].x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); arr = new A[0]; index = 1; Console.WriteLine(s); return 42; } } static async Task TestReassignsTargetDuringAwait() { Console.WriteLine(nameof(TestReassignsTargetDuringAwait)); var arr = new A[1]; Console.WriteLine(""Before Assignment arr[0].x is: "" + arr[0].x); Console.WriteLine(""Before Assignment arr[0].y is: "" + arr[0].y); arr[0].x = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment arr[0].x is: "" + arr[0].x); Console.WriteLine(""Before Assignment arr[0].y is: "" + arr[0].y); async Task<int> WriteAndReassign(string s) { await Task.Yield(); arr[0] = new A{y = true }; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } struct A { public int x; public bool y; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestIndexerThrows Before Assignment Caught IndexOutOfRangeException TestIndexerSucceeds Before Assignment arr[0].x is: 0 RHS After Assignment arr[0].x is: 42 TestReassignsArrayAndIndexerDuringAwait Before Assignment arr.Length is: 1 Before Assignment arrCopy[0].x is: 0 RHS After Assignment arr.Length is: 0 After Assignment arrCopy[0].x is: 42 TestReassignsTargetDuringAwait Before Assignment arr[0].x is: 0 Before Assignment arr[0].y is: False RHS After Assignment arr[0].x is: 42 Before Assignment arr[0].y is: True") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 198 (0xc6) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_005c IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A[] Program.<Assign>d__0.arr"" IL_0011: stfld ""A[] Program.<Assign>d__0.<>7__wrap1"" IL_0016: ldarg.0 IL_0017: ldfld ""A[] Program.<Assign>d__0.<>7__wrap1"" IL_001c: ldc.i4.0 IL_001d: ldelema ""A"" IL_0022: pop IL_0023: ldstr ""RHS"" IL_0028: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_002d: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0032: stloc.2 IL_0033: ldloca.s V_2 IL_0035: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_003a: brtrue.s IL_0078 IL_003c: ldarg.0 IL_003d: ldc.i4.0 IL_003e: dup IL_003f: stloc.0 IL_0040: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0045: ldarg.0 IL_0046: ldloc.2 IL_0047: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_004c: ldarg.0 IL_004d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0052: ldloca.s V_2 IL_0054: ldarg.0 IL_0055: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_005a: leave.s IL_00c5 IL_005c: ldarg.0 IL_005d: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0062: stloc.2 IL_0063: ldarg.0 IL_0064: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0069: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_006f: ldarg.0 IL_0070: ldc.i4.m1 IL_0071: dup IL_0072: stloc.0 IL_0073: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0078: ldloca.s V_2 IL_007a: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_007f: stloc.1 IL_0080: ldarg.0 IL_0081: ldfld ""A[] Program.<Assign>d__0.<>7__wrap1"" IL_0086: ldc.i4.0 IL_0087: ldelema ""A"" IL_008c: ldloc.1 IL_008d: stfld ""int A.x"" IL_0092: ldarg.0 IL_0093: ldnull IL_0094: stfld ""A[] Program.<Assign>d__0.<>7__wrap1"" IL_0099: leave.s IL_00b2 } catch System.Exception { IL_009b: stloc.3 IL_009c: ldarg.0 IL_009d: ldc.i4.s -2 IL_009f: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00a4: ldarg.0 IL_00a5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00aa: ldloc.3 IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00b0: leave.s IL_00c5 } IL_00b2: ldarg.0 IL_00b3: ldc.i4.s -2 IL_00b5: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00ba: ldarg.0 IL_00bb: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00c0: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00c5: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_AssignmentToArray() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(int[] arr) { arr[0] = await Write(""RHS""); } static async Task Main(string[] args) { await TestIndexerThrows(); await TestIndexerSucceeds(); await TestReassignsArrayAndIndexerDuringAwait(); } static async Task TestIndexerThrows() { Console.WriteLine(nameof(TestIndexerThrows)); var arr = new int[0]; Console.WriteLine(""Before Assignment""); try { await Assign(arr); } catch (IndexOutOfRangeException) { Console.WriteLine(""Caught IndexOutOfRangeException""); } } static async Task TestIndexerSucceeds() { Console.WriteLine(nameof(TestIndexerSucceeds)); var arr = new int[1]; Console.WriteLine(""Before Assignment arr[0] is: "" + arr[0]); await Assign(arr); Console.WriteLine(""After Assignment arr[0] is: "" + arr[0]); } static async Task TestReassignsArrayAndIndexerDuringAwait() { Console.WriteLine(nameof(TestReassignsArrayAndIndexerDuringAwait)); var arr = new int[1]; var arrCopy = arr; var index = 0; Console.WriteLine(""Before Assignment arr.Length is: "" + arr.Length); Console.WriteLine(""Before Assignment arrCopy[0] is: "" + arrCopy[0]); arr[index] = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment arr.Length is: "" + arr.Length); Console.WriteLine(""After Assignment arrCopy[0] is: "" + arrCopy[0]); async Task<int> WriteAndReassign(string s) { await Task.Yield(); arr = new int[0]; index = 1; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestIndexerThrows Before Assignment RHS Caught IndexOutOfRangeException TestIndexerSucceeds Before Assignment arr[0] is: 0 RHS After Assignment arr[0] is: 42 TestReassignsArrayAndIndexerDuringAwait Before Assignment arr.Length is: 1 Before Assignment arrCopy[0] is: 0 RHS After Assignment arr.Length is: 0 After Assignment arrCopy[0] is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 176 (0xb0) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_004f IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""int[] Program.<Assign>d__0.arr"" IL_0011: stfld ""int[] Program.<Assign>d__0.<>7__wrap1"" IL_0016: ldstr ""RHS"" IL_001b: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0020: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0025: stloc.2 IL_0026: ldloca.s V_2 IL_0028: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002d: brtrue.s IL_006b IL_002f: ldarg.0 IL_0030: ldc.i4.0 IL_0031: dup IL_0032: stloc.0 IL_0033: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0038: ldarg.0 IL_0039: ldloc.2 IL_003a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_003f: ldarg.0 IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0045: ldloca.s V_2 IL_0047: ldarg.0 IL_0048: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_004d: leave.s IL_00af IL_004f: ldarg.0 IL_0050: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0055: stloc.2 IL_0056: ldarg.0 IL_0057: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_005c: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0062: ldarg.0 IL_0063: ldc.i4.m1 IL_0064: dup IL_0065: stloc.0 IL_0066: stfld ""int Program.<Assign>d__0.<>1__state"" IL_006b: ldloca.s V_2 IL_006d: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0072: stloc.1 IL_0073: ldarg.0 IL_0074: ldfld ""int[] Program.<Assign>d__0.<>7__wrap1"" IL_0079: ldc.i4.0 IL_007a: ldloc.1 IL_007b: stelem.i4 IL_007c: ldarg.0 IL_007d: ldnull IL_007e: stfld ""int[] Program.<Assign>d__0.<>7__wrap1"" IL_0083: leave.s IL_009c } catch System.Exception { IL_0085: stloc.3 IL_0086: ldarg.0 IL_0087: ldc.i4.s -2 IL_0089: stfld ""int Program.<Assign>d__0.<>1__state"" IL_008e: ldarg.0 IL_008f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0094: ldloc.3 IL_0095: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_009a: leave.s IL_00af } IL_009c: ldarg.0 IL_009d: ldc.i4.s -2 IL_009f: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00a4: ldarg.0 IL_00a5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00aa: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00af: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_StructFieldAccessOnStructFieldAccessOnClassField() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a) { a.b.c.x = await Write(""RHS""); } static async Task Main(string[] args) { await TestAIsNull(); await TestAIsNotNull(); await ReassignADuringAssignment(); } static async Task TestAIsNull() { Console.WriteLine(nameof(TestAIsNull)); A a = null; Console.WriteLine(""Before Assignment""); try { await Assign(a); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNotNull() { Console.WriteLine(nameof(TestAIsNotNull)); var a = new A(); Console.WriteLine(""Before Assignment a.b.c.x is: "" + a.b.c.x); await Assign(a); Console.WriteLine(""After Assignment a.b.c.x is: "" + a.b.c.x); } static async Task ReassignADuringAssignment() { Console.WriteLine(nameof(ReassignADuringAssignment)); var a = new A(); var aCopy = a; Console.WriteLine(""Before Assignment a is null == "" + (a is null)); Console.WriteLine(""Before Assignment aCopy.b.c.x is: "" + aCopy.b.c.x); a.b.c.x = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment a is null == "" + (a is null)); Console.WriteLine(""After Assignment aCopy.b.c.x is: "" + aCopy.b.c.x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); a = null; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public B b; } struct B { public C c; } struct C { public int x; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestAIsNull Before Assignment Caught NullReferenceException TestAIsNotNull Before Assignment a.b.c.x is: 0 RHS After Assignment a.b.c.x is: 42 ReassignADuringAssignment Before Assignment a is null == False Before Assignment aCopy.b.c.x is: 0 RHS After Assignment a is null == True After Assignment aCopy.b.c.x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 201 (0xc9) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_005b IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A Program.<Assign>d__0.a"" IL_0011: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0016: ldarg.0 IL_0017: ldfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_001c: ldfld ""B A.b"" IL_0021: pop IL_0022: ldstr ""RHS"" IL_0027: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_002c: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0031: stloc.2 IL_0032: ldloca.s V_2 IL_0034: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0039: brtrue.s IL_0077 IL_003b: ldarg.0 IL_003c: ldc.i4.0 IL_003d: dup IL_003e: stloc.0 IL_003f: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0044: ldarg.0 IL_0045: ldloc.2 IL_0046: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_004b: ldarg.0 IL_004c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0051: ldloca.s V_2 IL_0053: ldarg.0 IL_0054: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_0059: leave.s IL_00c8 IL_005b: ldarg.0 IL_005c: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0061: stloc.2 IL_0062: ldarg.0 IL_0063: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0068: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_006e: ldarg.0 IL_006f: ldc.i4.m1 IL_0070: dup IL_0071: stloc.0 IL_0072: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0077: ldloca.s V_2 IL_0079: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_007e: stloc.1 IL_007f: ldarg.0 IL_0080: ldfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0085: ldflda ""B A.b"" IL_008a: ldflda ""C B.c"" IL_008f: ldloc.1 IL_0090: stfld ""int C.x"" IL_0095: ldarg.0 IL_0096: ldnull IL_0097: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_009c: leave.s IL_00b5 } catch System.Exception { IL_009e: stloc.3 IL_009f: ldarg.0 IL_00a0: ldc.i4.s -2 IL_00a2: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00a7: ldarg.0 IL_00a8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00ad: ldloc.3 IL_00ae: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00b3: leave.s IL_00c8 } IL_00b5: ldarg.0 IL_00b6: ldc.i4.s -2 IL_00b8: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00bd: ldarg.0 IL_00be: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00c3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00c8: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_ClassPropertyAssignmentOnClassProperty() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a) { a.b.x = await Write(""RHS""); } static async Task Main(string[] args) { await TestAIsNull(); await TestAIsNotNull(); await ReassignADuringAssignment(); } static async Task TestAIsNull() { Console.WriteLine(nameof(TestAIsNull)); A a = null; Console.WriteLine(""Before Assignment""); try { await Assign(a); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNotNull() { Console.WriteLine(nameof(TestAIsNotNull)); var a = new A{ _b = new B() }; Console.WriteLine(""Before Assignment a._b._x is: "" + a._b._x); await Assign(a); Console.WriteLine(""After Assignment a._b._x is: "" + a._b._x); } static async Task ReassignADuringAssignment() { Console.WriteLine(nameof(ReassignADuringAssignment)); var a = new A{ _b = new B() }; var aCopy = a; Console.WriteLine(""Before Assignment a is null == "" + (a is null)); Console.WriteLine(""Before Assignment aCopy._b._x is: "" + aCopy._b._x); a.b.x = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment a is null == "" + (a is null)); Console.WriteLine(""After Assignment aCopy._b._x is: "" + aCopy._b._x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); a = null; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public B _b; public B b { get { Console.WriteLine(""GetB""); return _b; } set { Console.WriteLine(""SetB""); _b = value; }} } class B { public int _x; public int x { get { Console.WriteLine(""GetX""); return _x; } set { Console.WriteLine(""SetX""); _x = value; } } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestAIsNull Before Assignment Caught NullReferenceException TestAIsNotNull Before Assignment a._b._x is: 0 GetB RHS SetX After Assignment a._b._x is: 42 ReassignADuringAssignment Before Assignment a is null == False Before Assignment aCopy._b._x is: 0 GetB RHS SetX After Assignment a is null == True After Assignment aCopy._b._x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 184 (0xb8) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0054 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A Program.<Assign>d__0.a"" IL_0011: callvirt ""B A.b.get"" IL_0016: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_001b: ldstr ""RHS"" IL_0020: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0025: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_002a: stloc.2 IL_002b: ldloca.s V_2 IL_002d: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0032: brtrue.s IL_0070 IL_0034: ldarg.0 IL_0035: ldc.i4.0 IL_0036: dup IL_0037: stloc.0 IL_0038: stfld ""int Program.<Assign>d__0.<>1__state"" IL_003d: ldarg.0 IL_003e: ldloc.2 IL_003f: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0044: ldarg.0 IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_004a: ldloca.s V_2 IL_004c: ldarg.0 IL_004d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_0052: leave.s IL_00b7 IL_0054: ldarg.0 IL_0055: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_005a: stloc.2 IL_005b: ldarg.0 IL_005c: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0061: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0067: ldarg.0 IL_0068: ldc.i4.m1 IL_0069: dup IL_006a: stloc.0 IL_006b: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0070: ldloca.s V_2 IL_0072: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0077: stloc.1 IL_0078: ldarg.0 IL_0079: ldfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_007e: ldloc.1 IL_007f: callvirt ""void B.x.set"" IL_0084: ldarg.0 IL_0085: ldnull IL_0086: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_008b: leave.s IL_00a4 } catch System.Exception { IL_008d: stloc.3 IL_008e: ldarg.0 IL_008f: ldc.i4.s -2 IL_0091: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0096: ldarg.0 IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_009c: ldloc.3 IL_009d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a2: leave.s IL_00b7 } IL_00a4: ldarg.0 IL_00a5: ldc.i4.s -2 IL_00a7: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00ac: ldarg.0 IL_00ad: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00b2: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b7: ret }"); } [WorkItem(19609, "https://github.com/dotnet/roslyn/issues/19609")] [Fact] public void KeepLtrSemantics_FieldAccessOnClass() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a) { a.x = await Write(""RHS""); } static async Task Main(string[] args) { await TestAIsNull(); await TestAIsNotNull(); await ReassignADuringAssignment(); } static async Task TestAIsNull() { Console.WriteLine(nameof(TestAIsNull)); A a = null; Console.WriteLine(""Before Assignment""); try { await Assign(a); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNotNull() { Console.WriteLine(nameof(TestAIsNotNull)); var a = new A(); Console.WriteLine(""Before Assignment a.x is: "" + a.x); await Assign(a); Console.WriteLine(""After Assignment a.x is: "" + a.x); } static async Task ReassignADuringAssignment() { Console.WriteLine(nameof(ReassignADuringAssignment)); var a = new A(); var aCopy = a; Console.WriteLine(""Before Assignment a is null == "" + (a is null)); Console.WriteLine(""Before Assignment aCopy.x is: "" + aCopy.x); a.x = await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment a is null == "" + (a is null)); Console.WriteLine(""After Assignment aCopy.x is: "" + aCopy.x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); a = null; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public int x; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestAIsNull Before Assignment RHS Caught NullReferenceException TestAIsNotNull Before Assignment a.x is: 0 RHS After Assignment a.x is: 42 ReassignADuringAssignment Before Assignment a is null == False Before Assignment aCopy.x is: 0 RHS After Assignment a is null == True After Assignment aCopy.x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 179 (0xb3) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_004f IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A Program.<Assign>d__0.a"" IL_0011: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0016: ldstr ""RHS"" IL_001b: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0020: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0025: stloc.2 IL_0026: ldloca.s V_2 IL_0028: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002d: brtrue.s IL_006b IL_002f: ldarg.0 IL_0030: ldc.i4.0 IL_0031: dup IL_0032: stloc.0 IL_0033: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0038: ldarg.0 IL_0039: ldloc.2 IL_003a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_003f: ldarg.0 IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0045: ldloca.s V_2 IL_0047: ldarg.0 IL_0048: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_004d: leave.s IL_00b2 IL_004f: ldarg.0 IL_0050: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0055: stloc.2 IL_0056: ldarg.0 IL_0057: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_005c: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0062: ldarg.0 IL_0063: ldc.i4.m1 IL_0064: dup IL_0065: stloc.0 IL_0066: stfld ""int Program.<Assign>d__0.<>1__state"" IL_006b: ldloca.s V_2 IL_006d: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0072: stloc.1 IL_0073: ldarg.0 IL_0074: ldfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0079: ldloc.1 IL_007a: stfld ""int A.x"" IL_007f: ldarg.0 IL_0080: ldnull IL_0081: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0086: leave.s IL_009f } catch System.Exception { IL_0088: stloc.3 IL_0089: ldarg.0 IL_008a: ldc.i4.s -2 IL_008c: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0091: ldarg.0 IL_0092: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0097: ldloc.3 IL_0098: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_009d: leave.s IL_00b2 } IL_009f: ldarg.0 IL_00a0: ldc.i4.s -2 IL_00a2: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00a7: ldarg.0 IL_00a8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00ad: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b2: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_CompoundAssignment() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a) { a.x += await Write(""RHS""); } static async Task Main(string[] args) { await TestAIsNull(); await TestAIsNotNull(); await ReassignADuringAssignment(); await ReassignXDuringAssignment(); } static async Task TestAIsNull() { Console.WriteLine(nameof(TestAIsNull)); A a = null; Console.WriteLine(""Before Assignment""); try { await Assign(a); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNotNull() { Console.WriteLine(nameof(TestAIsNotNull)); var a = new A(){ x = 1 }; Console.WriteLine(""Before Assignment a.x is: "" + a.x); await Assign(a); Console.WriteLine(""After Assignment a.x is: "" + a.x); } static async Task ReassignADuringAssignment() { Console.WriteLine(nameof(ReassignADuringAssignment)); var a = new A(){ x = 1 }; var aCopy = a; Console.WriteLine(""Before Assignment a is null == "" + (a is null)); Console.WriteLine(""Before Assignment aCopy.x is: "" + aCopy.x); a.x += await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment a is null == "" + (a is null)); Console.WriteLine(""After Assignment aCopy.x is: "" + aCopy.x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); a = null; Console.WriteLine(s); return 42; } } static async Task ReassignXDuringAssignment() { Console.WriteLine(nameof(ReassignXDuringAssignment)); var a = new A(){ x = 1 }; Console.WriteLine(""Before Assignment a.x is: "" + a.x); a.x += await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment a.x is: "" + a.x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); a.x = 100; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public int x; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestAIsNull Before Assignment Caught NullReferenceException TestAIsNotNull Before Assignment a.x is: 1 RHS After Assignment a.x is: 43 ReassignADuringAssignment Before Assignment a is null == False Before Assignment aCopy.x is: 1 RHS After Assignment a is null == True After Assignment aCopy.x is: 43 ReassignXDuringAssignment Before Assignment a.x is: 1 RHS After Assignment a.x is: 43") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 202 (0xca) .maxstack 3 .locals init (int V_0, A V_1, int V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_005d IL_000a: ldarg.0 IL_000b: ldfld ""A Program.<Assign>d__0.a"" IL_0010: stloc.1 IL_0011: ldarg.0 IL_0012: ldloc.1 IL_0013: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0018: ldarg.0 IL_0019: ldloc.1 IL_001a: ldfld ""int A.x"" IL_001f: stfld ""int Program.<Assign>d__0.<>7__wrap2"" IL_0024: ldstr ""RHS"" IL_0029: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_002e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0033: stloc.3 IL_0034: ldloca.s V_3 IL_0036: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_003b: brtrue.s IL_0079 IL_003d: ldarg.0 IL_003e: ldc.i4.0 IL_003f: dup IL_0040: stloc.0 IL_0041: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0046: ldarg.0 IL_0047: ldloc.3 IL_0048: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_004d: ldarg.0 IL_004e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0053: ldloca.s V_3 IL_0055: ldarg.0 IL_0056: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_005b: leave.s IL_00c9 IL_005d: ldarg.0 IL_005e: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0063: stloc.3 IL_0064: ldarg.0 IL_0065: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_006a: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0070: ldarg.0 IL_0071: ldc.i4.m1 IL_0072: dup IL_0073: stloc.0 IL_0074: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0079: ldloca.s V_3 IL_007b: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0080: stloc.2 IL_0081: ldarg.0 IL_0082: ldfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0087: ldarg.0 IL_0088: ldfld ""int Program.<Assign>d__0.<>7__wrap2"" IL_008d: ldloc.2 IL_008e: add IL_008f: stfld ""int A.x"" IL_0094: ldarg.0 IL_0095: ldnull IL_0096: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_009b: leave.s IL_00b6 } catch System.Exception { IL_009d: stloc.s V_4 IL_009f: ldarg.0 IL_00a0: ldc.i4.s -2 IL_00a2: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00a7: ldarg.0 IL_00a8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00ad: ldloc.s V_4 IL_00af: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00b4: leave.s IL_00c9 } IL_00b6: ldarg.0 IL_00b7: ldc.i4.s -2 IL_00b9: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00be: ldarg.0 IL_00bf: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00c4: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00c9: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void KeepLtrSemantics_CompoundAssignmentProperties() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a) { a.x += await Write(""RHS""); } static async Task Main(string[] args) { await TestAIsNull(); await TestAIsNotNull(); await ReassignADuringAssignment(); await ReassignXDuringAssignment(); } static async Task TestAIsNull() { Console.WriteLine(nameof(TestAIsNull)); A a = null; Console.WriteLine(""Before Assignment""); try { await Assign(a); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNotNull() { Console.WriteLine(nameof(TestAIsNotNull)); var a = new A(){ _x = 1 }; Console.WriteLine(""Before Assignment a._x is: "" + a._x); await Assign(a); Console.WriteLine(""After Assignment a._x is: "" + a._x); } static async Task ReassignADuringAssignment() { Console.WriteLine(nameof(ReassignADuringAssignment)); var a = new A(){ _x = 1 }; var aCopy = a; Console.WriteLine(""Before Assignment a is null == "" + (a is null)); Console.WriteLine(""Before Assignment aCopy._x is: "" + aCopy._x); a.x += await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment a is null == "" + (a is null)); Console.WriteLine(""After Assignment aCopy._x is: "" + aCopy._x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); a = null; Console.WriteLine(s); return 42; } } static async Task ReassignXDuringAssignment() { Console.WriteLine(nameof(ReassignXDuringAssignment)); var a = new A(){ _x = 1 }; Console.WriteLine(""Before Assignment a._x is: "" + a._x); a.x += await WriteAndReassign(""RHS""); Console.WriteLine(""After Assignment a._x is: "" + a._x); async Task<int> WriteAndReassign(string s) { await Task.Yield(); a._x = 100; Console.WriteLine(s); return 42; } } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public int _x; public int x { get { Console.WriteLine(""GetX""); return _x; } set { Console.WriteLine(""SetX""); _x = value; } } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestAIsNull Before Assignment Caught NullReferenceException TestAIsNotNull Before Assignment a._x is: 1 GetX RHS SetX After Assignment a._x is: 43 ReassignADuringAssignment Before Assignment a is null == False Before Assignment aCopy._x is: 1 GetX RHS SetX After Assignment a is null == True After Assignment aCopy._x is: 43 ReassignXDuringAssignment Before Assignment a._x is: 1 GetX RHS SetX After Assignment a._x is: 43") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 202 (0xca) .maxstack 3 .locals init (int V_0, A V_1, int V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_005d IL_000a: ldarg.0 IL_000b: ldfld ""A Program.<Assign>d__0.a"" IL_0010: stloc.1 IL_0011: ldarg.0 IL_0012: ldloc.1 IL_0013: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0018: ldarg.0 IL_0019: ldloc.1 IL_001a: callvirt ""int A.x.get"" IL_001f: stfld ""int Program.<Assign>d__0.<>7__wrap2"" IL_0024: ldstr ""RHS"" IL_0029: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_002e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0033: stloc.3 IL_0034: ldloca.s V_3 IL_0036: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_003b: brtrue.s IL_0079 IL_003d: ldarg.0 IL_003e: ldc.i4.0 IL_003f: dup IL_0040: stloc.0 IL_0041: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0046: ldarg.0 IL_0047: ldloc.3 IL_0048: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_004d: ldarg.0 IL_004e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0053: ldloca.s V_3 IL_0055: ldarg.0 IL_0056: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_005b: leave.s IL_00c9 IL_005d: ldarg.0 IL_005e: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0063: stloc.3 IL_0064: ldarg.0 IL_0065: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_006a: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0070: ldarg.0 IL_0071: ldc.i4.m1 IL_0072: dup IL_0073: stloc.0 IL_0074: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0079: ldloca.s V_3 IL_007b: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0080: stloc.2 IL_0081: ldarg.0 IL_0082: ldfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_0087: ldarg.0 IL_0088: ldfld ""int Program.<Assign>d__0.<>7__wrap2"" IL_008d: ldloc.2 IL_008e: add IL_008f: callvirt ""void A.x.set"" IL_0094: ldarg.0 IL_0095: ldnull IL_0096: stfld ""A Program.<Assign>d__0.<>7__wrap1"" IL_009b: leave.s IL_00b6 } catch System.Exception { IL_009d: stloc.s V_4 IL_009f: ldarg.0 IL_00a0: ldc.i4.s -2 IL_00a2: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00a7: ldarg.0 IL_00a8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00ad: ldloc.s V_4 IL_00af: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00b4: leave.s IL_00c9 } IL_00b6: ldarg.0 IL_00b7: ldc.i4.s -2 IL_00b9: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00be: ldarg.0 IL_00bf: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00c4: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00c9: ret }"); } [WorkItem(19609, "https://github.com/dotnet/roslyn/issues/19609")] [Fact] public void KeepLtrSemantics_AssignmentToAssignment() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a, B b) { a.b.x = b.x = await Write(""RHS""); } static async Task Main(string[] args) { await TestAIsNullBIsNull(); await TestAIsNullBIsNotNull(); await TestAIsNotNullBIsNull(); await TestADotBIsNullBIsNotNull(); await TestADotBIsNotNullBIsNotNull(); } static async Task TestAIsNullBIsNull() { Console.WriteLine(nameof(TestAIsNullBIsNull)); A a = null; B b = null; Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNullBIsNotNull() { Console.WriteLine(nameof(TestAIsNullBIsNotNull)); A a = null; B b = new B(); Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNotNullBIsNull() { Console.WriteLine(nameof(TestAIsNotNullBIsNull)); A a = new A{ b = new B() }; B b = null; Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestADotBIsNullBIsNotNull() { Console.WriteLine(nameof(TestADotBIsNullBIsNotNull)); A a = new A(); B b = new B(); Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestADotBIsNotNullBIsNotNull() { Console.WriteLine(nameof(TestADotBIsNotNullBIsNotNull)); A a = new A{ b = new B() }; B b = new B(); Console.WriteLine(""Before Assignment a.b.x is: "" + a.b.x); Console.WriteLine(""Before Assignment b.x is: "" + b.x); await Assign(a, b); Console.WriteLine(""After Assignment a.b.x is: "" + a.b.x); Console.WriteLine(""After Assignment b.x is: "" + b.x); } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public B b; } class B { public int x; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestAIsNullBIsNull Before Assignment Caught NullReferenceException TestAIsNullBIsNotNull Before Assignment Caught NullReferenceException TestAIsNotNullBIsNull Before Assignment RHS Caught NullReferenceException TestADotBIsNullBIsNotNull Before Assignment RHS Caught NullReferenceException TestADotBIsNotNullBIsNotNull Before Assignment a.b.x is: 0 Before Assignment b.x is: 0 RHS After Assignment a.b.x is: 42 After Assignment b.x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 219 (0xdb) .maxstack 4 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, int V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0060 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A Program.<Assign>d__0.a"" IL_0011: ldfld ""B A.b"" IL_0016: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_001b: ldarg.0 IL_001c: ldarg.0 IL_001d: ldfld ""B Program.<Assign>d__0.b"" IL_0022: stfld ""B Program.<Assign>d__0.<>7__wrap2"" IL_0027: ldstr ""RHS"" IL_002c: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0031: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0036: stloc.2 IL_0037: ldloca.s V_2 IL_0039: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_003e: brtrue.s IL_007c IL_0040: ldarg.0 IL_0041: ldc.i4.0 IL_0042: dup IL_0043: stloc.0 IL_0044: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0049: ldarg.0 IL_004a: ldloc.2 IL_004b: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0050: ldarg.0 IL_0051: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0056: ldloca.s V_2 IL_0058: ldarg.0 IL_0059: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_005e: leave.s IL_00da IL_0060: ldarg.0 IL_0061: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0066: stloc.2 IL_0067: ldarg.0 IL_0068: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_006d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0073: ldarg.0 IL_0074: ldc.i4.m1 IL_0075: dup IL_0076: stloc.0 IL_0077: stfld ""int Program.<Assign>d__0.<>1__state"" IL_007c: ldloca.s V_2 IL_007e: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0083: stloc.1 IL_0084: ldarg.0 IL_0085: ldfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_008a: ldarg.0 IL_008b: ldfld ""B Program.<Assign>d__0.<>7__wrap2"" IL_0090: ldloc.1 IL_0091: dup IL_0092: stloc.3 IL_0093: stfld ""int B.x"" IL_0098: ldloc.3 IL_0099: stfld ""int B.x"" IL_009e: ldarg.0 IL_009f: ldnull IL_00a0: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_00a5: ldarg.0 IL_00a6: ldnull IL_00a7: stfld ""B Program.<Assign>d__0.<>7__wrap2"" IL_00ac: leave.s IL_00c7 } catch System.Exception { IL_00ae: stloc.s V_4 IL_00b0: ldarg.0 IL_00b1: ldc.i4.s -2 IL_00b3: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00b8: ldarg.0 IL_00b9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00be: ldloc.s V_4 IL_00c0: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00c5: leave.s IL_00da } IL_00c7: ldarg.0 IL_00c8: ldc.i4.s -2 IL_00ca: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00cf: ldarg.0 IL_00d0: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00da: ret }"); } [WorkItem(19609, "https://github.com/dotnet/roslyn/issues/19609")] [Fact] public void KeepLtrSemantics_AssignmentToAssignmentProperties() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign(A a, B b) { a.b.x = b.x = await Write(""RHS""); } static async Task Main(string[] args) { await TestAIsNullBIsNull(); await TestAIsNullBIsNotNull(); await TestAIsNotNullBIsNull(); await TestADotBIsNullBIsNotNull(); await TestADotBIsNotNullBIsNotNull(); } static async Task TestAIsNullBIsNull() { Console.WriteLine(nameof(TestAIsNullBIsNull)); A a = null; B b = null; Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNullBIsNotNull() { Console.WriteLine(nameof(TestAIsNullBIsNotNull)); A a = null; B b = new B(); Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestAIsNotNullBIsNull() { Console.WriteLine(nameof(TestAIsNotNullBIsNull)); A a = new A{ _b = new B() }; B b = null; Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestADotBIsNullBIsNotNull() { Console.WriteLine(nameof(TestADotBIsNullBIsNotNull)); A a = new A(); B b = new B(); Console.WriteLine(""Before Assignment""); try { await Assign(a, b); } catch (NullReferenceException) { Console.WriteLine(""Caught NullReferenceException""); } } static async Task TestADotBIsNotNullBIsNotNull() { Console.WriteLine(nameof(TestADotBIsNotNullBIsNotNull)); A a = new A{ _b = new B() }; B b = new B(); Console.WriteLine(""Before Assignment a._b._x is: "" + a._b._x); Console.WriteLine(""Before Assignment b._x is: "" + b._x); await Assign(a, b); Console.WriteLine(""After Assignment a._b._x is: "" + a._b._x); Console.WriteLine(""After Assignment b._x is: "" + b._x); } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } } class A { public B _b; public B b { get { Console.WriteLine(""GetB""); return _b; } set { Console.WriteLine(""SetB""); _b = value; }} } class B { public int _x; public int x { get { Console.WriteLine(""GetX""); return _x; } set { Console.WriteLine(""SetX""); _x = value; } } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"TestAIsNullBIsNull Before Assignment Caught NullReferenceException TestAIsNullBIsNotNull Before Assignment Caught NullReferenceException TestAIsNotNullBIsNull Before Assignment GetB RHS Caught NullReferenceException TestADotBIsNullBIsNotNull Before Assignment GetB RHS SetX Caught NullReferenceException TestADotBIsNotNullBIsNotNull Before Assignment a._b._x is: 0 Before Assignment b._x is: 0 GetB RHS SetX SetX After Assignment a._b._x is: 42 After Assignment b._x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 219 (0xdb) .maxstack 3 .locals init (int V_0, int V_1, int V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0060 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""A Program.<Assign>d__0.a"" IL_0011: callvirt ""B A.b.get"" IL_0016: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_001b: ldarg.0 IL_001c: ldarg.0 IL_001d: ldfld ""B Program.<Assign>d__0.b"" IL_0022: stfld ""B Program.<Assign>d__0.<>7__wrap2"" IL_0027: ldstr ""RHS"" IL_002c: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0031: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0036: stloc.3 IL_0037: ldloca.s V_3 IL_0039: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_003e: brtrue.s IL_007c IL_0040: ldarg.0 IL_0041: ldc.i4.0 IL_0042: dup IL_0043: stloc.0 IL_0044: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0049: ldarg.0 IL_004a: ldloc.3 IL_004b: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0050: ldarg.0 IL_0051: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0056: ldloca.s V_3 IL_0058: ldarg.0 IL_0059: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_005e: leave.s IL_00da IL_0060: ldarg.0 IL_0061: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0066: stloc.3 IL_0067: ldarg.0 IL_0068: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_006d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0073: ldarg.0 IL_0074: ldc.i4.m1 IL_0075: dup IL_0076: stloc.0 IL_0077: stfld ""int Program.<Assign>d__0.<>1__state"" IL_007c: ldloca.s V_3 IL_007e: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0083: stloc.1 IL_0084: ldarg.0 IL_0085: ldfld ""B Program.<Assign>d__0.<>7__wrap2"" IL_008a: ldloc.1 IL_008b: dup IL_008c: stloc.2 IL_008d: callvirt ""void B.x.set"" IL_0092: ldarg.0 IL_0093: ldfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_0098: ldloc.2 IL_0099: callvirt ""void B.x.set"" IL_009e: ldarg.0 IL_009f: ldnull IL_00a0: stfld ""B Program.<Assign>d__0.<>7__wrap1"" IL_00a5: ldarg.0 IL_00a6: ldnull IL_00a7: stfld ""B Program.<Assign>d__0.<>7__wrap2"" IL_00ac: leave.s IL_00c7 } catch System.Exception { IL_00ae: stloc.s V_4 IL_00b0: ldarg.0 IL_00b1: ldc.i4.s -2 IL_00b3: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00b8: ldarg.0 IL_00b9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00be: ldloc.s V_4 IL_00c0: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00c5: leave.s IL_00da } IL_00c7: ldarg.0 IL_00c8: ldc.i4.s -2 IL_00ca: stfld ""int Program.<Assign>d__0.<>1__state"" IL_00cf: ldarg.0 IL_00d0: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00da: ret }"); } [Fact] [WorkItem(42755, "https://github.com/dotnet/roslyn/issues/42755")] public void AssignmentToFieldOfStaticFieldOfStruct() { var source = @" using System; using System.Threading.Tasks; class Program { static async Task Assign() { A.b.x = await Write(""RHS""); } static async Task<int> Write(string s) { await Task.Yield(); Console.WriteLine(s); return 42; } static async Task Main(string[] args) { Console.WriteLine(""Before Assignment A.b.x is: "" + A.b.x); await Assign(); Console.WriteLine(""After Assignment A.b.x is: "" + A.b.x); } } struct A { public static B b; } struct B { public int x; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"Before Assignment A.b.x is: 0 RHS After Assignment A.b.x is: 42") .VerifyIL("Program.<Assign>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 159 (0x9f) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Assign>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0043 IL_000a: ldstr ""RHS"" IL_000f: call ""System.Threading.Tasks.Task<int> Program.Write(string)"" IL_0014: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0021: brtrue.s IL_005f IL_0023: ldarg.0 IL_0024: ldc.i4.0 IL_0025: dup IL_0026: stloc.0 IL_0027: stfld ""int Program.<Assign>d__0.<>1__state"" IL_002c: ldarg.0 IL_002d: ldloc.2 IL_002e: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0033: ldarg.0 IL_0034: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0039: ldloca.s V_2 IL_003b: ldarg.0 IL_003c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Assign>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Assign>d__0)"" IL_0041: leave.s IL_009e IL_0043: ldarg.0 IL_0044: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0049: stloc.2 IL_004a: ldarg.0 IL_004b: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Assign>d__0.<>u__1"" IL_0050: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0056: ldarg.0 IL_0057: ldc.i4.m1 IL_0058: dup IL_0059: stloc.0 IL_005a: stfld ""int Program.<Assign>d__0.<>1__state"" IL_005f: ldloca.s V_2 IL_0061: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0066: stloc.1 IL_0067: ldsflda ""B A.b"" IL_006c: ldloc.1 IL_006d: stfld ""int B.x"" IL_0072: leave.s IL_008b } catch System.Exception { IL_0074: stloc.3 IL_0075: ldarg.0 IL_0076: ldc.i4.s -2 IL_0078: stfld ""int Program.<Assign>d__0.<>1__state"" IL_007d: ldarg.0 IL_007e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0083: ldloc.3 IL_0084: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0089: leave.s IL_009e } IL_008b: ldarg.0 IL_008c: ldc.i4.s -2 IL_008e: stfld ""int Program.<Assign>d__0.<>1__state"" IL_0093: ldarg.0 IL_0094: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Assign>d__0.<>t__builder"" IL_0099: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_009e: ret }"); } [Fact, WorkItem(47191, "https://github.com/dotnet/roslyn/issues/47191")] public void AssignStaticStructField() { var source = @" using System; using System.Threading.Tasks; public struct S1 { public int Field; } public class C { public static S1 s1; static async Task M(Task<int> t) { s1.Field = await t; } static async Task Main() { await M(Task.FromResult(1)); Console.Write(s1.Field); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); } [Fact, WorkItem(47191, "https://github.com/dotnet/roslyn/issues/47191")] public void AssignStaticStructField_ViaUsingStatic() { var source = @" using System; using System.Threading.Tasks; using static C; public struct S1 { public int Field; } public class C { public static S1 s1; } public class Program { static async Task M(Task<int> t) { s1.Field = await t; } static async Task Main() { await M(Task.FromResult(1)); Console.Write(s1.Field); } } "; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); } [Fact, WorkItem(47191, "https://github.com/dotnet/roslyn/issues/47191")] public void AssignInstanceStructField() { var source = @" using System; using System.Threading.Tasks; public struct S1 { public int Field; } public class C { public S1 s1; async Task M(Task<int> t) { s1.Field = await t; } static async Task Main() { var c = new C(); await c.M(Task.FromResult(1)); Console.Write(c.s1.Field); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); } } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Compilers/VisualBasic/vbc/App.config
<?xml version="1.0" encoding="utf-8" ?> <!-- 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. --> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <runtime> <AppContextSwitchOverrides value="Switch.System.Security.Cryptography.UseLegacyFipsThrow=false" /> <gcServer enabled="true" /> <gcConcurrent enabled="false"/> </runtime> </configuration>
<?xml version="1.0" encoding="utf-8" ?> <!-- 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. --> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <runtime> <AppContextSwitchOverrides value="Switch.System.Security.Cryptography.UseLegacyFipsThrow=false" /> <gcServer enabled="true" /> <gcConcurrent enabled="false"/> </runtime> </configuration>
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Analyzers/Core/Analyzers/PopulateSwitch/AbstractPopulateSwitchDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal abstract class AbstractPopulateSwitchDiagnosticAnalyzer<TSwitchOperation, TSwitchSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TSwitchOperation : IOperation where TSwitchSyntax : SyntaxNode { private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(AnalyzersResources.Add_missing_cases), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(AnalyzersResources.Populate_switch), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); protected AbstractPopulateSwitchDiagnosticAnalyzer(string diagnosticId, EnforceOnBuild enforceOnBuild) : base(diagnosticId, enforceOnBuild, option: null, s_localizableTitle, s_localizableMessage) { } #region Interface methods protected abstract OperationKind OperationKind { get; } protected abstract ICollection<ISymbol> GetMissingEnumMembers(TSwitchOperation operation); protected abstract bool HasDefaultCase(TSwitchOperation operation); protected abstract Location GetDiagnosticLocation(TSwitchSyntax switchBlock); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterOperationAction(AnalyzeOperation, OperationKind); private void AnalyzeOperation(OperationAnalysisContext context) { var switchOperation = (TSwitchOperation)context.Operation; if (switchOperation.Syntax is not TSwitchSyntax switchBlock) return; var tree = switchBlock.SyntaxTree; if (SwitchIsIncomplete(switchOperation, out var missingCases, out var missingDefaultCase) && !tree.OverlapsHiddenPosition(switchBlock.Span, context.CancellationToken)) { Debug.Assert(missingCases || missingDefaultCase); var properties = ImmutableDictionary<string, string?>.Empty .Add(PopulateSwitchStatementHelpers.MissingCases, missingCases.ToString()) .Add(PopulateSwitchStatementHelpers.MissingDefaultCase, missingDefaultCase.ToString()); #pragma warning disable CS8620 // Mismatch in nullability of 'properties' parameter and argument types - Parameter type for 'properties' has been updated to 'ImmutableDictionary<string, string?>?' in newer version of Microsoft.CodeAnalysis (3.7.x). var diagnostic = Diagnostic.Create( Descriptor, GetDiagnosticLocation(switchBlock), properties: properties, additionalLocations: new[] { switchBlock.GetLocation() }); #pragma warning restore CS8620 context.ReportDiagnostic(diagnostic); } } #endregion private bool SwitchIsIncomplete( TSwitchOperation operation, out bool missingCases, out bool missingDefaultCase) { var missingEnumMembers = GetMissingEnumMembers(operation); missingCases = missingEnumMembers.Count > 0; missingDefaultCase = !HasDefaultCase(operation); // The switch is incomplete if we're missing any cases or we're missing a default case. return missingDefaultCase || missingCases; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal abstract class AbstractPopulateSwitchDiagnosticAnalyzer<TSwitchOperation, TSwitchSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TSwitchOperation : IOperation where TSwitchSyntax : SyntaxNode { private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(AnalyzersResources.Add_missing_cases), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(AnalyzersResources.Populate_switch), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); protected AbstractPopulateSwitchDiagnosticAnalyzer(string diagnosticId, EnforceOnBuild enforceOnBuild) : base(diagnosticId, enforceOnBuild, option: null, s_localizableTitle, s_localizableMessage) { } #region Interface methods protected abstract OperationKind OperationKind { get; } protected abstract ICollection<ISymbol> GetMissingEnumMembers(TSwitchOperation operation); protected abstract bool HasDefaultCase(TSwitchOperation operation); protected abstract Location GetDiagnosticLocation(TSwitchSyntax switchBlock); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterOperationAction(AnalyzeOperation, OperationKind); private void AnalyzeOperation(OperationAnalysisContext context) { var switchOperation = (TSwitchOperation)context.Operation; if (switchOperation.Syntax is not TSwitchSyntax switchBlock) return; var tree = switchBlock.SyntaxTree; if (SwitchIsIncomplete(switchOperation, out var missingCases, out var missingDefaultCase) && !tree.OverlapsHiddenPosition(switchBlock.Span, context.CancellationToken)) { Debug.Assert(missingCases || missingDefaultCase); var properties = ImmutableDictionary<string, string?>.Empty .Add(PopulateSwitchStatementHelpers.MissingCases, missingCases.ToString()) .Add(PopulateSwitchStatementHelpers.MissingDefaultCase, missingDefaultCase.ToString()); #pragma warning disable CS8620 // Mismatch in nullability of 'properties' parameter and argument types - Parameter type for 'properties' has been updated to 'ImmutableDictionary<string, string?>?' in newer version of Microsoft.CodeAnalysis (3.7.x). var diagnostic = Diagnostic.Create( Descriptor, GetDiagnosticLocation(switchBlock), properties: properties, additionalLocations: new[] { switchBlock.GetLocation() }); #pragma warning restore CS8620 context.ReportDiagnostic(diagnostic); } } #endregion private bool SwitchIsIncomplete( TSwitchOperation operation, out bool missingCases, out bool missingDefaultCase) { var missingEnumMembers = GetMissingEnumMembers(operation); missingCases = missingEnumMembers.Count > 0; missingDefaultCase = !HasDefaultCase(operation); // The switch is incomplete if we're missing any cases or we're missing a default case. return missingDefaultCase || missingCases; } } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./docs/features/nullable-reference-types.md
Nullable Reference Types ========= Reference types may be nullable, non-nullable, or null-oblivious (abbreviated here as `?`, `!`, and `~`). ## Setting project level nullable context Project level nullable context can be set by using "nullable" command line switch: -nullable[+|-] Specify nullable context option enable|disable. -nullable:{enable|disable|warnings|annotations} Specify nullable context option enable|disable|warnings|annotations. Through msbuild the context could be set by supplying an argument for a "Nullable" parameter of Csc build task. Accepted values are "enable", "disable", "warnings", "annotations", or null (for the default nullable context according to the compiler). The Microsoft.CSharp.Core.targets passes value of msbuild property named "Nullable" for that parameter. Note that in previous preview releases of C# 8.0 this "Nullable" property was successively named "NullableReferenceTypes" then "NullableContextOptions". ## Annotations In source, nullable reference types are annotated with `?`. ```c# string? OptString; // may be null Dictionary<string, object?>? OptDictionaryOptValues; // dictionary may be null, values may be null ``` A warning is reported when annotating a reference type with `?` outside a `#nullable` context. [Metadata representation](nullable-metadata.md) ## Declaration warnings _Describe warnings reported for declarations in initial binding._ ## Flow analysis Flow analysis is used to infer the nullability of variables within executable code. The inferred nullability of a variable is independent of the variable's declared nullability. Method calls are analyzed even when they are conditionally omitted. For instance, `Debug.Assert` in release mode. ### Warnings _Describe set of warnings. Differentiate W warnings._ If the analysis determines that a null check always (or never) passes, a hidden diagnostic is produced. For example: `"string" is null`. ### Null tests A number of null checks affect the flow state when tested for: - comparisons to `null`: `x == null` and `x != null` - `is` operator: `x is null`, `x is K` (where `K` is a constant), `x is string`, `x is string s` - calls to well-known equality methods, including: - `static bool object.Equals(object, object)` - `static bool object.ReferenceEquals(object, object)` - `bool object.Equals(object)` and overrides - `bool IEquatable<T>.Equals(T)` and implementations - `bool IEqualityComparer<T>.Equals(T, T)` and implementations Some null checks are "pure null tests", which means that they can cause a variable whose flow state was previously not-null to update to maybe-null. Pure null tests include: - `x == null`, `x != null` *whether using a built-in or user-defined operator* - `(Type)x == null`, `(Type)x != null` - `x is null` - `object.Equals(x, null)`, `object.ReferenceEquals(x, null)` - `IEqualityComparer<Type?>.Equals(x, null)` All of the above checks except for `x is null` are commutative. For example, `null == x` is also a valid pure null test. Some expressions which may not return `bool` are also considered pure null tests: - `x?.Member` will change the receiver's flow state to maybe-null unconditionally - `x ?? y` will change the LHS expression's flow state to maybe-null unconditionally Example of how a pure null test can affect flow analysis: ```cs string s = "hello"; if (s != null) { _ = s.ToString(); // ok } else { _ = s.ToString(); // warning } ``` Versus a "not pure" null test: ```cs string s = "hello"; if (s is string) { _ = s.ToString(); // ok } else { _ = s.ToString(); // ok } ``` Invocation of methods annotated with the following attributes will also affect flow analysis: - simple pre-conditions: `[AllowNull]` and `[DisallowNull]` - simple post-conditions: `[MaybeNull]` and `[NotNull]` - conditional post-conditions: `[MaybeNullWhen(bool)]` and `[NotNullWhen(bool)]` - `[DoesNotReturnIf(bool)]` (e.g. `[DoesNotReturnIf(false)]` for `Debug.Assert`) and `[DoesNotReturn]` - `[NotNullIfNotNull(string)]` - member post-conditions: `[MemberNotNull(params string[])]` and `[MemberNotNullWhen(bool, params string[])]` See https://github.com/dotnet/csharplang/blob/main/meetings/2019/LDM-2019-05-15.md The `Interlocked.CompareExchange` methods have special handling in flow analysis instead of being annotated due to the complexity of their nullability semantics. The affected overloads include: - `static object? System.Threading.Interlocked.CompareExchange(ref object? location, object? value, object? comparand)` - `static T System.Threading.Interlocked.CompareExchange<T>(ref T location, T value, T comparand) where T : class?` When simple pre- and post-condition attributes are applied to a property, and an allowed input state is assigned to the property, the property's state is updated to be an allowed output state. For instance an `[AllowNull] string` property can be assigned `null` and still return not-null values. Enforcing nullability attributes within method bodies: - An input parameter marked with `[AllowNull]` is initialized with a maybe-null (or maybe-default) state. - An input parameter marked with `[DisallowNull]` is initialized with a not-null state. - A parameter marked with `[MaybeNull]` or `[MaybeNullWhen]` can be assigned a maybe-null value, without warning. Same for return values. Same for a nullable parameter marked with `[NotNullWhen]` (the attribute is ignored). - A parameter marked with `[NotNull]` will produce a warning when assigned a maybe-null value. Same for return values. - The state of a parameter marked with `[MaybeNullWhen]`/`[NotNullWhen]` is checked upon exiting the method instead. - A method marked with `[DoesNotReturn]` will produce a warning if it returns or exits normally. Note: we don't validate the internal consistency of auto-properties, so it is possible to misuse attributes on auto-props as on fields. For example: `[AllowNull, NotNull] public TOpen P { get; set; }`. Enforcing nullability attributes when overriding and implementing: In addition to checking the types in overrides/implementations are compatible with overridden/implemented members, we also check that the nullability attributes are compatible. - For input parameters (by-value and `in`), we check that the widest allowed value by the overridden/implemented parameter can be assigned to the overriding/implementing parameter. - For output parameters (`out` and return values), we check that the widest produced value by the overriding/implementing parameter can be assigned to the overridden/implemented parameter. - For `ref` parameters and return values, we check both. - We check that the post-condition contract `[NotNull]`/`[MaybeNull]` on input parameters is enforced by overriding/implementing members. - We check that overrides/implementations have the `[DoesNotReturn]` attribute if the overridden/implemented member has it. - We check that members used in `[MemberNotNull(...)]` or `[MemberNotNullWhen(...)]` are not null upon exit, by assuming they had maybe-null state on entry. ## `default` If `T` is a reference type, `default(T)` is `T?`. ```c# string? s = default(string); // assigns ?, no warning string t = default; // assigns ?, warning ``` If `T` is a value type, `default(T)` is `T` and any non-value-type fields in `T` are maybe null. If `T` is a value type, `new T()` is equivalent to `default(T)`. ```c# struct Pair<T, U> { public T First; public U Second; } var p = default(Pair<object?, string>); // ok: Pair<object?, string!> p p.Second.ToString(); // warning (object?, string) t = default; // ok t.Item2.ToString(); // warning ``` If `T` is an unconstrained type parameter, `default(T)` is a `T` that is maybe null. ```c# T t = default; // warning ``` ### Conversions Conversions can be calculated with ~ considered distinct from ? and !, or with ~ implicitly convertible to ? and !. Given `IIn<in T>` and `IOut<out T>`, with ~ distinct: - `T!` is a `T~` is a `T?` - `IIn<T!>` is a `IIn<T~>` is a `IIn<T?>` - `IOut<T?>` is a `IOut<T~>` is a `IOut<T!>` Most conversions are considered with ~ implicitly convertible to ? and !. _Describe warnings from user-defined conversions._ ### Assignment For `x = y`, the nullability of the converted type of `y` is used for `x`. A warning is reported if there is a mismatch between top-level or nested nullability comparing the inferred nullability of `x` and the declared type of `y`. The warning is a W warning when assigning `?` to `!` and the target is a local. ```c# notNull = maybeNull; // assigns ?, warning notNull = oblivious; // assigns ~, no warning oblivious = maybeNull; // assigns ?, no warning ``` ### Local declarations Nullablilty follows from assignment above. Assigning `?` to `!` is a W warning. ```c# string notNull = maybeNull; // assigns ?, warning ``` The nullability of `var` declarations is the nullable version of the inferred type. ```c# var s = maybeNull; // s is ?, no warning if (maybeNull == null) return; var t = maybeNull; // t is ? too ``` ### Suppression operator (`!`) The postfix `!` operator sets the top-level nullability to non-nullable. Conversions on a suppressed expression produce no nullability warnings. ```c# var x = optionalString!; // x is string! var y = obliviousString!; // y is string! var z = new [] { optionalString, obliviousString }!; // no change, z is string?[]! ``` A warning is reported when using the `!` operator absent a `NonNullTypes` context. Unnecessary usages of `!` do not produce any diagnostics, including `!!`. A suppressed expression `e!` can be target-typed if the operand expression `e` can be target-typed. ### Explicit cast Explicit cast to `?` changes top-level nullability. Explicit cast to `!` does not change top-level nullability and may produce W warning. ```c# var x = (string)maybeNull; // x is string?, W warning var y = (string)oblivious; // y is string~, no warning var z = (string?)notNull; // y is string?, no warning ``` A warning is reported if the type of operand including nested nullability is not explicitly convertible to the target type. ```c# sealed class MyList<T> : IEnumerable<T> { } var x = new MyList<string?>(); var y = (IEnumerable<object>)x; // warning var z = (IEnumerable<object?>)x; // no warning ``` ### Method type inference We modify the spec rule for [Fixing](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#fixing "Fixing") to take account of types that may be equivalent (i.e. have an identity conversion) yet may not be identical in the set of bounds. The existing spec says (third bullet) > If among the remaining candidate types `Uj` there is a unique type `V` from which there is an implicit conversion to all the other candidate types, then `Xi` is fixed to `V`. This is not correct for C# 5 (i.e., it is a bug in the language specification), as it fails to handle bounds such as `Dictionary<object, dynamic>` and `Dictionary<dynamic, object>`, which are merged to `Dictionary<dynamic, dynamic>`. This is [an open issue](https://github.com/ECMA-TC49-TG2/spec/issues/951) that we anticipate will be addressed in the next iteration of the ECMA specification. Handling nullability properly will require additional changes beyond those in that next iteration of the ECMA spec. When adding to the set of exact bounds of a type parameter, types that are equivalent (i.e. have an identity conversion) but not identical are merged using *invariant* rules. When adding to the set of lower bounds of a type parameter, types that are equivalent but not identical are merged using *covariant* rules. When adding to the set of upper bounds of a type parameter, types that are equivalent but not identical are merged using *contravariant* rules. In the final fixing step, types that are equivalent but not identical are merged using *covariant* rules. Merging equivalent but not identical types is done as follows: #### Invariant merging rules - Merging `dynamic` and `object` results in the type `dynamic`. - Merging tuple types that differ in element names is specified elsewhere. - Merging equivalent types that differ in nullability is performed as follows: merging the types `Tn` and `Um` (where `n` and `m` are differing nullability annotations) results in the type `Vk` where `V` is the result of merging `T` and `U` using the invariant rule, and `k` is as follows: - if either `n` or `m` are non-nullable, non-nullable. - if either `n` or `m` are nullable, nullable. - otherwise oblivious. - Merging constructed generic types is performed as follows: Merging the types `K<A1, A2, ...>` and `K<B1, B2, ...>` results in the type `K<C1, C2, ...>` where `Ci` is the result of merging `Ai` and `Bi` by the invariant rule. - Merging tuple types `(A1, A2, ...)` and `(B1, B2, ...)` results in the type `(C1, C2, ...)` where `Ci` is the result of merging `Ai` and `Bi` by the invariant rule. - Merging the array types `T[]` and `U[]` results in the type `V[]` where `V` is the result of merging `T` and `U` by the invariant rule. #### Covariant merging rules - Merging `dynamic` and `object` results in the type `dynamic`. - Merging tuple types that differ in element names is specified elsewhere. - Merging equivalent types that differ in nullability is performed as follows: merging the types `Tn` and `Um` (where `n` and `m` are differing nullability annotations) results in the type `Vk` where `V` is the result of merging `T` and `U` using the covariant rule, and `k` is as follows: - if either `n` or `m` are nullable, nullable. - if either `n` or `m` are oblivious, oblivious. - otherwise non-nullable. - Merging constructed generic types is performed as follows: Merging the types `K<A1, A2, ...>` and `K<B1, B2, ...>` results in the type `K<C1, C2, ...>` where `Ci` is the result of merging `Ai` and `Bi` by - the invariant rule if `K`'s type parameter in the `i` position is invariant. - the covariant rule if `K`'s type parameter in the `i` position is declared `out`. - the contravariant rule if the `K`'s type parameter in the `i` position is declared `in`. - Merging tuple types `(A1, A2, ...)` and `(B1, B2, ...)` results in the type `(C1, C2, ...)` where `Ci` is the result of merging `Ai` and `Bi` by the covariant rule. - Merging the array types `T[]` and `U[]` results in the type `V[]` where `V` is the result of merging `T` and `U` by the invariant rule. #### Contravariant merging rules - Merging `dynamic` and `object` results in the type `dynamic`. - Merging tuple types that differ in element names is specified elsewhere. - Merging equivalent types that differ in nullability is performed as follows: merging the types `Tn` and `Um` (where `n` and `m` are differing nullability annotations) results in the type `Vk` where `V` is the result of merging `T` and `U` using the contravariant rule, and `k` is as follows: - if either `n` or `m` are non-nullable, non-nullable. - if either `n` or `m` are oblivious, oblivious. - otherwise nullable. - Merging constructed generic types is performed as follows: Merging the types `K<A1, A2, ...>` and `K<B1, B2, ...>` results in the type `K<C1, C2, ...>` where `Ci` is the result of merging `Ai` and `Bi` by - the invariant rule if `K`'s type parameter in the `i` position is invariant. - the covariant rule if `K`'s type parameter in the `i` position is declared `in`. - the contravariant rule if `K`'s type parameter in the `i` position is declared `out`. - Merging tuple types `(A1, A2, ...)` and `(B1, B2, ...)` results in the type `(C1, C2, ...)` where `Ci` is the result of merging `Ai` and `Bi` by the contravariant rule. - Merging the array types `T[]` and `U[]` results in the type `V[]` where `V` is the result of merging `T` and `U` by the invariant rule. It is intended that these merging rules are associative and commutative, so that a compiler may merge a set of equivalent types pairwise in any order to compute the final result. > ***Open issue***: these rules do not describe the handling of merging a nested generic type `K<A>.L<B>` with `K<C>.L<D>`. That should be handled the same as a hypothetical type `KL<A, B>` would be merged with `KL<C, D>`. > ***Open issue***: these rules do not describe the handling of merging pointer types. ### Array creation The calculation of the _best type_ element nullability uses the Conversions rules above and the covariant merging rules. ```c# var w = new [] { notNull, oblivious }; // ~[]! var x = new [] { notNull, maybeNull, oblivious }; // ?[]! var y = new [] { enumerableOfNotNull, enumerableOfMaybeNull, enumerableOfOblivious }; // IEnumerable<?>! var z = new [] { listOfNotNull, listOfMaybeNull, listOfOblivious }; // List<~>! ``` ### Anonymous types Fields of anonymous types have nullability of the arguments, inferred from the initializing expression. ```c# static void F<T>(T x, T y) { if (x == null) return; var a = new { x, y }; // inferred as x:T, y:T (both Unannotated) a.x.ToString(); // ok (non-null tracked by the nullable flow state of the initial value for property x) a.y.ToString(); // warning } ``` ### Null-coalescing operator The top-level nullability of `x ?? y` is `!` if `x` is `!` and otherwise the top-level nullability of `y`. A warning is reported if there is a nested nullability mismatch between `x` and `y`. ### Try-finally We infer the state after a try statement in part by keeping track of which variables may have been assigned a null value in the finally block. This tracking distinguishes actual assignments from inferences: only actual assignments (but not inferences) affect the state after the try statement. See https://github.com/dotnet/roslyn/issues/34018 and https://github.com/dotnet/roslyn/pull/35276. This is not yet reflected in the language specification for nullable reference types (as we don't have a specification for how to handle try statements at this time). ## Type parameters A `class?` constraint is allowed, which, like class, requires the type argument to be a reference type, but allows it to be nullable. [Nullable strawman](https://github.com/dotnet/csharplang/issues/790) [4/25/18](https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-04-25.md) Explicit `object` (or `System.Object`) constraints of any nullability are disallowed. However, type substitution can lead to `object!` or `object~` constraints to appear among the constraint types, when their nullability is significant by comparison to other constraints. An `object!` constraint requires the type to be non-nullable (value or reference type). However, an explicit `object?` constraint is not allowed. An unconstrained (here it means - no type constraints, and no `class`, `struct`, or `unmanaged` constraints) type parameter is essentially equivalent to one constrained by `object?` when it is declared in a context where nullable annotations are enabled. If annotations are disabled, the type parameter is essentially equivalent to one constrained by `object~`. The context is determined at the identifier that declares the type parameter within a type parameter list. [4/25/18](https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-04-25.md) Note, the `object`/`System.Object` constraint is represented in metadata as any other type constraint, the type is System.Object. An explicit `notnull` constraint is allowed, which requires the type to be non-nullable (value or reference type). [5/15/19](https://github.com/dotnet/csharplang/blob/main/meetings/2019/LDM-2019-05-15.md) The rules to determine when it is a named type constraint or a special `notnull` constraint are similar to rules for `unmanaged`. Similarly, it is valid only at the first position in constraints list. A warning is reported for nullable type argument for type parameter with `class` constraint or non-nullable reference type or interface type constraint. [4/25/18](https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-04-25.md) ```c# static void F1<T>() where T : class { } static void F2<T>() where T : Stream { } static void F3<T>() where T : IDisposable { } F1<Stream?>(); // warning F2<Stream?>(); // warning F3<Stream?>(); // warning ``` Type parameter constraints may include nullable reference type and interface types. [4/25/18](https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-04-25.md) ```c# static void F2<T> where T : Stream? { } static void F3<T>() where T : IDisposable? { } F2<Stream?>(); // ok F3<Stream?>(); // ok ``` A warning is reported for inconsistent top-level nullability of constraint types. [4/25/18](https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-04-25.md) ```c# static void F4<T> where T : class, Stream? { } // warning static void F5<T> where T : Stream?, IDisposable { } // warning ``` An error is reported for duplicate constraints where constraints are compared ignoring top-level and nested nullability. ```c# class C<T> where T : class { static void F1<U>() where U : T, T? { } // error: duplicate constraint static void F2<U>() where U : I<T>, I<T?> { } // error: duplicate constraint } ``` _What are the rules for annotated (unannotated) type arguments for generic type parameters from unannotated (annotated) types and methods?_ ```c# [NotNullTypes(false)] List<T> F1<T>(T t) where T : class { ... } [NotNullTypes(true)] List<T> F2<T>(T t) where T : class { ... } [NotNullTypes(true)] List<T?> F3<T>(T? t) where T : class { ... } var x = F1(notNullString); // List<string!> or List<string~> ? var y = F1(maybeNullString); // List<string?> or List<string~> ? var z = F2(obliviousString); // List<string~>! or List<string!>! ? var w = F3(obliviousString); // List<string~>! or List<string?>! ? ``` A warning is reported for dereferencing variables of type T, where T is an unconstrained type parameter. ```C# static void F<T>(T t) => t.ToString(); // Warn possible null dereference ``` A warning is reported when attempting to convert a null, default, or potentially null value to an unconstrained type parameter. ```C# static T F<T>() => default; // Warn converting default to T ``` ## Object creation An error is reported for creating an instance of a nullable reference type. ```c# new C?(); // error new List<C?>(); // ok ``` ## Generated code Older code generation strategies may not be nullable aware. Setting the project-level nullable context to "enable" could result in many warnings that a user is unable to fix. To support this scenario any syntax tree that is determined to be generated will have its nullable state implicitly set to "disable", regardless of the overall project state. A syntax tree is determined to be generated if meets one or more of the following criteria: - File name begins with: - TemporaryGeneratedFile_ - File name ends with: - .designer.cs - .generated.cs - .g.cs - .g.i.cs - Contains a top level comment that contains - `<autogenerated` - `<auto-generated` Newer, nullable-aware generators may then opt-in to nullable analysis by including a generated `#nullable restore` at the beginning of the code, ensuring that the generated syntax tree will be analyzed according to the project-level nullable context. ## Public APIs There are a few questions that an API consumer would want to answer: 1. should I print a `?` after the type? 2. can I assign a `null` value to a variable of this type? 3. could I read a `null` value from a variable of this type? Two primitive concepts we wish to expose are: `IsAnnotated` and `NonNullTypes`. _We may expose some higher-level concepts (to address questions 2 and 3 conveniently) as well._ | | IsAnnotated | |--| ----------- | | `string?` | `true` | | `int?` / `Nullable<int>` | `true` (_needs confirmation_) | | `Nullable<T>` | `true` | | `T? where T : class` | `true` | | `T? where T : struct` | `true` (_needs confirmation_) | | `string` | `false` | | `int` | `false` | | `T where T : class/object` | `false` | | `T where T : class?` | `false` | | `T where T : struct` | `false` | | `T` | `false` |
Nullable Reference Types ========= Reference types may be nullable, non-nullable, or null-oblivious (abbreviated here as `?`, `!`, and `~`). ## Setting project level nullable context Project level nullable context can be set by using "nullable" command line switch: -nullable[+|-] Specify nullable context option enable|disable. -nullable:{enable|disable|warnings|annotations} Specify nullable context option enable|disable|warnings|annotations. Through msbuild the context could be set by supplying an argument for a "Nullable" parameter of Csc build task. Accepted values are "enable", "disable", "warnings", "annotations", or null (for the default nullable context according to the compiler). The Microsoft.CSharp.Core.targets passes value of msbuild property named "Nullable" for that parameter. Note that in previous preview releases of C# 8.0 this "Nullable" property was successively named "NullableReferenceTypes" then "NullableContextOptions". ## Annotations In source, nullable reference types are annotated with `?`. ```c# string? OptString; // may be null Dictionary<string, object?>? OptDictionaryOptValues; // dictionary may be null, values may be null ``` A warning is reported when annotating a reference type with `?` outside a `#nullable` context. [Metadata representation](nullable-metadata.md) ## Declaration warnings _Describe warnings reported for declarations in initial binding._ ## Flow analysis Flow analysis is used to infer the nullability of variables within executable code. The inferred nullability of a variable is independent of the variable's declared nullability. Method calls are analyzed even when they are conditionally omitted. For instance, `Debug.Assert` in release mode. ### Warnings _Describe set of warnings. Differentiate W warnings._ If the analysis determines that a null check always (or never) passes, a hidden diagnostic is produced. For example: `"string" is null`. ### Null tests A number of null checks affect the flow state when tested for: - comparisons to `null`: `x == null` and `x != null` - `is` operator: `x is null`, `x is K` (where `K` is a constant), `x is string`, `x is string s` - calls to well-known equality methods, including: - `static bool object.Equals(object, object)` - `static bool object.ReferenceEquals(object, object)` - `bool object.Equals(object)` and overrides - `bool IEquatable<T>.Equals(T)` and implementations - `bool IEqualityComparer<T>.Equals(T, T)` and implementations Some null checks are "pure null tests", which means that they can cause a variable whose flow state was previously not-null to update to maybe-null. Pure null tests include: - `x == null`, `x != null` *whether using a built-in or user-defined operator* - `(Type)x == null`, `(Type)x != null` - `x is null` - `object.Equals(x, null)`, `object.ReferenceEquals(x, null)` - `IEqualityComparer<Type?>.Equals(x, null)` All of the above checks except for `x is null` are commutative. For example, `null == x` is also a valid pure null test. Some expressions which may not return `bool` are also considered pure null tests: - `x?.Member` will change the receiver's flow state to maybe-null unconditionally - `x ?? y` will change the LHS expression's flow state to maybe-null unconditionally Example of how a pure null test can affect flow analysis: ```cs string s = "hello"; if (s != null) { _ = s.ToString(); // ok } else { _ = s.ToString(); // warning } ``` Versus a "not pure" null test: ```cs string s = "hello"; if (s is string) { _ = s.ToString(); // ok } else { _ = s.ToString(); // ok } ``` Invocation of methods annotated with the following attributes will also affect flow analysis: - simple pre-conditions: `[AllowNull]` and `[DisallowNull]` - simple post-conditions: `[MaybeNull]` and `[NotNull]` - conditional post-conditions: `[MaybeNullWhen(bool)]` and `[NotNullWhen(bool)]` - `[DoesNotReturnIf(bool)]` (e.g. `[DoesNotReturnIf(false)]` for `Debug.Assert`) and `[DoesNotReturn]` - `[NotNullIfNotNull(string)]` - member post-conditions: `[MemberNotNull(params string[])]` and `[MemberNotNullWhen(bool, params string[])]` See https://github.com/dotnet/csharplang/blob/main/meetings/2019/LDM-2019-05-15.md The `Interlocked.CompareExchange` methods have special handling in flow analysis instead of being annotated due to the complexity of their nullability semantics. The affected overloads include: - `static object? System.Threading.Interlocked.CompareExchange(ref object? location, object? value, object? comparand)` - `static T System.Threading.Interlocked.CompareExchange<T>(ref T location, T value, T comparand) where T : class?` When simple pre- and post-condition attributes are applied to a property, and an allowed input state is assigned to the property, the property's state is updated to be an allowed output state. For instance an `[AllowNull] string` property can be assigned `null` and still return not-null values. Enforcing nullability attributes within method bodies: - An input parameter marked with `[AllowNull]` is initialized with a maybe-null (or maybe-default) state. - An input parameter marked with `[DisallowNull]` is initialized with a not-null state. - A parameter marked with `[MaybeNull]` or `[MaybeNullWhen]` can be assigned a maybe-null value, without warning. Same for return values. Same for a nullable parameter marked with `[NotNullWhen]` (the attribute is ignored). - A parameter marked with `[NotNull]` will produce a warning when assigned a maybe-null value. Same for return values. - The state of a parameter marked with `[MaybeNullWhen]`/`[NotNullWhen]` is checked upon exiting the method instead. - A method marked with `[DoesNotReturn]` will produce a warning if it returns or exits normally. Note: we don't validate the internal consistency of auto-properties, so it is possible to misuse attributes on auto-props as on fields. For example: `[AllowNull, NotNull] public TOpen P { get; set; }`. Enforcing nullability attributes when overriding and implementing: In addition to checking the types in overrides/implementations are compatible with overridden/implemented members, we also check that the nullability attributes are compatible. - For input parameters (by-value and `in`), we check that the widest allowed value by the overridden/implemented parameter can be assigned to the overriding/implementing parameter. - For output parameters (`out` and return values), we check that the widest produced value by the overriding/implementing parameter can be assigned to the overridden/implemented parameter. - For `ref` parameters and return values, we check both. - We check that the post-condition contract `[NotNull]`/`[MaybeNull]` on input parameters is enforced by overriding/implementing members. - We check that overrides/implementations have the `[DoesNotReturn]` attribute if the overridden/implemented member has it. - We check that members used in `[MemberNotNull(...)]` or `[MemberNotNullWhen(...)]` are not null upon exit, by assuming they had maybe-null state on entry. ## `default` If `T` is a reference type, `default(T)` is `T?`. ```c# string? s = default(string); // assigns ?, no warning string t = default; // assigns ?, warning ``` If `T` is a value type, `default(T)` is `T` and any non-value-type fields in `T` are maybe null. If `T` is a value type, `new T()` is equivalent to `default(T)`. ```c# struct Pair<T, U> { public T First; public U Second; } var p = default(Pair<object?, string>); // ok: Pair<object?, string!> p p.Second.ToString(); // warning (object?, string) t = default; // ok t.Item2.ToString(); // warning ``` If `T` is an unconstrained type parameter, `default(T)` is a `T` that is maybe null. ```c# T t = default; // warning ``` ### Conversions Conversions can be calculated with ~ considered distinct from ? and !, or with ~ implicitly convertible to ? and !. Given `IIn<in T>` and `IOut<out T>`, with ~ distinct: - `T!` is a `T~` is a `T?` - `IIn<T!>` is a `IIn<T~>` is a `IIn<T?>` - `IOut<T?>` is a `IOut<T~>` is a `IOut<T!>` Most conversions are considered with ~ implicitly convertible to ? and !. _Describe warnings from user-defined conversions._ ### Assignment For `x = y`, the nullability of the converted type of `y` is used for `x`. A warning is reported if there is a mismatch between top-level or nested nullability comparing the inferred nullability of `x` and the declared type of `y`. The warning is a W warning when assigning `?` to `!` and the target is a local. ```c# notNull = maybeNull; // assigns ?, warning notNull = oblivious; // assigns ~, no warning oblivious = maybeNull; // assigns ?, no warning ``` ### Local declarations Nullablilty follows from assignment above. Assigning `?` to `!` is a W warning. ```c# string notNull = maybeNull; // assigns ?, warning ``` The nullability of `var` declarations is the nullable version of the inferred type. ```c# var s = maybeNull; // s is ?, no warning if (maybeNull == null) return; var t = maybeNull; // t is ? too ``` ### Suppression operator (`!`) The postfix `!` operator sets the top-level nullability to non-nullable. Conversions on a suppressed expression produce no nullability warnings. ```c# var x = optionalString!; // x is string! var y = obliviousString!; // y is string! var z = new [] { optionalString, obliviousString }!; // no change, z is string?[]! ``` A warning is reported when using the `!` operator absent a `NonNullTypes` context. Unnecessary usages of `!` do not produce any diagnostics, including `!!`. A suppressed expression `e!` can be target-typed if the operand expression `e` can be target-typed. ### Explicit cast Explicit cast to `?` changes top-level nullability. Explicit cast to `!` does not change top-level nullability and may produce W warning. ```c# var x = (string)maybeNull; // x is string?, W warning var y = (string)oblivious; // y is string~, no warning var z = (string?)notNull; // y is string?, no warning ``` A warning is reported if the type of operand including nested nullability is not explicitly convertible to the target type. ```c# sealed class MyList<T> : IEnumerable<T> { } var x = new MyList<string?>(); var y = (IEnumerable<object>)x; // warning var z = (IEnumerable<object?>)x; // no warning ``` ### Method type inference We modify the spec rule for [Fixing](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#fixing "Fixing") to take account of types that may be equivalent (i.e. have an identity conversion) yet may not be identical in the set of bounds. The existing spec says (third bullet) > If among the remaining candidate types `Uj` there is a unique type `V` from which there is an implicit conversion to all the other candidate types, then `Xi` is fixed to `V`. This is not correct for C# 5 (i.e., it is a bug in the language specification), as it fails to handle bounds such as `Dictionary<object, dynamic>` and `Dictionary<dynamic, object>`, which are merged to `Dictionary<dynamic, dynamic>`. This is [an open issue](https://github.com/ECMA-TC49-TG2/spec/issues/951) that we anticipate will be addressed in the next iteration of the ECMA specification. Handling nullability properly will require additional changes beyond those in that next iteration of the ECMA spec. When adding to the set of exact bounds of a type parameter, types that are equivalent (i.e. have an identity conversion) but not identical are merged using *invariant* rules. When adding to the set of lower bounds of a type parameter, types that are equivalent but not identical are merged using *covariant* rules. When adding to the set of upper bounds of a type parameter, types that are equivalent but not identical are merged using *contravariant* rules. In the final fixing step, types that are equivalent but not identical are merged using *covariant* rules. Merging equivalent but not identical types is done as follows: #### Invariant merging rules - Merging `dynamic` and `object` results in the type `dynamic`. - Merging tuple types that differ in element names is specified elsewhere. - Merging equivalent types that differ in nullability is performed as follows: merging the types `Tn` and `Um` (where `n` and `m` are differing nullability annotations) results in the type `Vk` where `V` is the result of merging `T` and `U` using the invariant rule, and `k` is as follows: - if either `n` or `m` are non-nullable, non-nullable. - if either `n` or `m` are nullable, nullable. - otherwise oblivious. - Merging constructed generic types is performed as follows: Merging the types `K<A1, A2, ...>` and `K<B1, B2, ...>` results in the type `K<C1, C2, ...>` where `Ci` is the result of merging `Ai` and `Bi` by the invariant rule. - Merging tuple types `(A1, A2, ...)` and `(B1, B2, ...)` results in the type `(C1, C2, ...)` where `Ci` is the result of merging `Ai` and `Bi` by the invariant rule. - Merging the array types `T[]` and `U[]` results in the type `V[]` where `V` is the result of merging `T` and `U` by the invariant rule. #### Covariant merging rules - Merging `dynamic` and `object` results in the type `dynamic`. - Merging tuple types that differ in element names is specified elsewhere. - Merging equivalent types that differ in nullability is performed as follows: merging the types `Tn` and `Um` (where `n` and `m` are differing nullability annotations) results in the type `Vk` where `V` is the result of merging `T` and `U` using the covariant rule, and `k` is as follows: - if either `n` or `m` are nullable, nullable. - if either `n` or `m` are oblivious, oblivious. - otherwise non-nullable. - Merging constructed generic types is performed as follows: Merging the types `K<A1, A2, ...>` and `K<B1, B2, ...>` results in the type `K<C1, C2, ...>` where `Ci` is the result of merging `Ai` and `Bi` by - the invariant rule if `K`'s type parameter in the `i` position is invariant. - the covariant rule if `K`'s type parameter in the `i` position is declared `out`. - the contravariant rule if the `K`'s type parameter in the `i` position is declared `in`. - Merging tuple types `(A1, A2, ...)` and `(B1, B2, ...)` results in the type `(C1, C2, ...)` where `Ci` is the result of merging `Ai` and `Bi` by the covariant rule. - Merging the array types `T[]` and `U[]` results in the type `V[]` where `V` is the result of merging `T` and `U` by the invariant rule. #### Contravariant merging rules - Merging `dynamic` and `object` results in the type `dynamic`. - Merging tuple types that differ in element names is specified elsewhere. - Merging equivalent types that differ in nullability is performed as follows: merging the types `Tn` and `Um` (where `n` and `m` are differing nullability annotations) results in the type `Vk` where `V` is the result of merging `T` and `U` using the contravariant rule, and `k` is as follows: - if either `n` or `m` are non-nullable, non-nullable. - if either `n` or `m` are oblivious, oblivious. - otherwise nullable. - Merging constructed generic types is performed as follows: Merging the types `K<A1, A2, ...>` and `K<B1, B2, ...>` results in the type `K<C1, C2, ...>` where `Ci` is the result of merging `Ai` and `Bi` by - the invariant rule if `K`'s type parameter in the `i` position is invariant. - the covariant rule if `K`'s type parameter in the `i` position is declared `in`. - the contravariant rule if `K`'s type parameter in the `i` position is declared `out`. - Merging tuple types `(A1, A2, ...)` and `(B1, B2, ...)` results in the type `(C1, C2, ...)` where `Ci` is the result of merging `Ai` and `Bi` by the contravariant rule. - Merging the array types `T[]` and `U[]` results in the type `V[]` where `V` is the result of merging `T` and `U` by the invariant rule. It is intended that these merging rules are associative and commutative, so that a compiler may merge a set of equivalent types pairwise in any order to compute the final result. > ***Open issue***: these rules do not describe the handling of merging a nested generic type `K<A>.L<B>` with `K<C>.L<D>`. That should be handled the same as a hypothetical type `KL<A, B>` would be merged with `KL<C, D>`. > ***Open issue***: these rules do not describe the handling of merging pointer types. ### Array creation The calculation of the _best type_ element nullability uses the Conversions rules above and the covariant merging rules. ```c# var w = new [] { notNull, oblivious }; // ~[]! var x = new [] { notNull, maybeNull, oblivious }; // ?[]! var y = new [] { enumerableOfNotNull, enumerableOfMaybeNull, enumerableOfOblivious }; // IEnumerable<?>! var z = new [] { listOfNotNull, listOfMaybeNull, listOfOblivious }; // List<~>! ``` ### Anonymous types Fields of anonymous types have nullability of the arguments, inferred from the initializing expression. ```c# static void F<T>(T x, T y) { if (x == null) return; var a = new { x, y }; // inferred as x:T, y:T (both Unannotated) a.x.ToString(); // ok (non-null tracked by the nullable flow state of the initial value for property x) a.y.ToString(); // warning } ``` ### Null-coalescing operator The top-level nullability of `x ?? y` is `!` if `x` is `!` and otherwise the top-level nullability of `y`. A warning is reported if there is a nested nullability mismatch between `x` and `y`. ### Try-finally We infer the state after a try statement in part by keeping track of which variables may have been assigned a null value in the finally block. This tracking distinguishes actual assignments from inferences: only actual assignments (but not inferences) affect the state after the try statement. See https://github.com/dotnet/roslyn/issues/34018 and https://github.com/dotnet/roslyn/pull/35276. This is not yet reflected in the language specification for nullable reference types (as we don't have a specification for how to handle try statements at this time). ## Type parameters A `class?` constraint is allowed, which, like class, requires the type argument to be a reference type, but allows it to be nullable. [Nullable strawman](https://github.com/dotnet/csharplang/issues/790) [4/25/18](https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-04-25.md) Explicit `object` (or `System.Object`) constraints of any nullability are disallowed. However, type substitution can lead to `object!` or `object~` constraints to appear among the constraint types, when their nullability is significant by comparison to other constraints. An `object!` constraint requires the type to be non-nullable (value or reference type). However, an explicit `object?` constraint is not allowed. An unconstrained (here it means - no type constraints, and no `class`, `struct`, or `unmanaged` constraints) type parameter is essentially equivalent to one constrained by `object?` when it is declared in a context where nullable annotations are enabled. If annotations are disabled, the type parameter is essentially equivalent to one constrained by `object~`. The context is determined at the identifier that declares the type parameter within a type parameter list. [4/25/18](https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-04-25.md) Note, the `object`/`System.Object` constraint is represented in metadata as any other type constraint, the type is System.Object. An explicit `notnull` constraint is allowed, which requires the type to be non-nullable (value or reference type). [5/15/19](https://github.com/dotnet/csharplang/blob/main/meetings/2019/LDM-2019-05-15.md) The rules to determine when it is a named type constraint or a special `notnull` constraint are similar to rules for `unmanaged`. Similarly, it is valid only at the first position in constraints list. A warning is reported for nullable type argument for type parameter with `class` constraint or non-nullable reference type or interface type constraint. [4/25/18](https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-04-25.md) ```c# static void F1<T>() where T : class { } static void F2<T>() where T : Stream { } static void F3<T>() where T : IDisposable { } F1<Stream?>(); // warning F2<Stream?>(); // warning F3<Stream?>(); // warning ``` Type parameter constraints may include nullable reference type and interface types. [4/25/18](https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-04-25.md) ```c# static void F2<T> where T : Stream? { } static void F3<T>() where T : IDisposable? { } F2<Stream?>(); // ok F3<Stream?>(); // ok ``` A warning is reported for inconsistent top-level nullability of constraint types. [4/25/18](https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-04-25.md) ```c# static void F4<T> where T : class, Stream? { } // warning static void F5<T> where T : Stream?, IDisposable { } // warning ``` An error is reported for duplicate constraints where constraints are compared ignoring top-level and nested nullability. ```c# class C<T> where T : class { static void F1<U>() where U : T, T? { } // error: duplicate constraint static void F2<U>() where U : I<T>, I<T?> { } // error: duplicate constraint } ``` _What are the rules for annotated (unannotated) type arguments for generic type parameters from unannotated (annotated) types and methods?_ ```c# [NotNullTypes(false)] List<T> F1<T>(T t) where T : class { ... } [NotNullTypes(true)] List<T> F2<T>(T t) where T : class { ... } [NotNullTypes(true)] List<T?> F3<T>(T? t) where T : class { ... } var x = F1(notNullString); // List<string!> or List<string~> ? var y = F1(maybeNullString); // List<string?> or List<string~> ? var z = F2(obliviousString); // List<string~>! or List<string!>! ? var w = F3(obliviousString); // List<string~>! or List<string?>! ? ``` A warning is reported for dereferencing variables of type T, where T is an unconstrained type parameter. ```C# static void F<T>(T t) => t.ToString(); // Warn possible null dereference ``` A warning is reported when attempting to convert a null, default, or potentially null value to an unconstrained type parameter. ```C# static T F<T>() => default; // Warn converting default to T ``` ## Object creation An error is reported for creating an instance of a nullable reference type. ```c# new C?(); // error new List<C?>(); // ok ``` ## Generated code Older code generation strategies may not be nullable aware. Setting the project-level nullable context to "enable" could result in many warnings that a user is unable to fix. To support this scenario any syntax tree that is determined to be generated will have its nullable state implicitly set to "disable", regardless of the overall project state. A syntax tree is determined to be generated if meets one or more of the following criteria: - File name begins with: - TemporaryGeneratedFile_ - File name ends with: - .designer.cs - .generated.cs - .g.cs - .g.i.cs - Contains a top level comment that contains - `<autogenerated` - `<auto-generated` Newer, nullable-aware generators may then opt-in to nullable analysis by including a generated `#nullable restore` at the beginning of the code, ensuring that the generated syntax tree will be analyzed according to the project-level nullable context. ## Public APIs There are a few questions that an API consumer would want to answer: 1. should I print a `?` after the type? 2. can I assign a `null` value to a variable of this type? 3. could I read a `null` value from a variable of this type? Two primitive concepts we wish to expose are: `IsAnnotated` and `NonNullTypes`. _We may expose some higher-level concepts (to address questions 2 and 3 conveniently) as well._ | | IsAnnotated | |--| ----------- | | `string?` | `true` | | `int?` / `Nullable<int>` | `true` (_needs confirmation_) | | `Nullable<T>` | `true` | | `T? where T : class` | `true` | | `T? where T : struct` | `true` (_needs confirmation_) | | `string` | `false` | | `int` | `false` | | `T where T : class/object` | `false` | | `T where T : class?` | `false` | | `T where T : struct` | `false` | | `T` | `false` |
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/EditorFeatures/Test2/Rename/RenameEngineResult.vb
' 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 System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Imports Microsoft.VisualStudio.Text Imports Xunit.Abstractions Imports Xunit.Sdk Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename ''' <summary> ''' A class that holds the result of a rename engine call, and asserts ''' various things about it. This is used in the tests for the rename engine ''' to make asserting that certain spans were converted to what they should be. ''' </summary> Friend Class RenameEngineResult Implements IDisposable Private ReadOnly _workspace As TestWorkspace Private ReadOnly _resolution As ConflictResolution ''' <summary> ''' The list of related locations that haven't been asserted about yet. Items are ''' removed from here when they are asserted on, so the set should be empty once we're ''' done. ''' </summary> Private ReadOnly _unassertedRelatedLocations As HashSet(Of RelatedLocation) Private ReadOnly _renameTo As String Private _failedAssert As Boolean Private Sub New(workspace As TestWorkspace, resolution As ConflictResolution, renameTo As String) _workspace = workspace _resolution = resolution _unassertedRelatedLocations = New HashSet(Of RelatedLocation)(resolution.RelatedLocations) _renameTo = renameTo End Sub Public Shared Function Create( helper As ITestOutputHelper, workspaceXml As XElement, renameTo As String, host As RenameTestHost, Optional changedOptionSet As Dictionary(Of OptionKey, Object) = Nothing, Optional expectFailure As Boolean = False, Optional sourceGenerator As ISourceGenerator = Nothing) As RenameEngineResult Dim composition = EditorTestCompositions.EditorFeatures.AddParts(GetType(NoCompilationContentTypeLanguageService), GetType(NoCompilationContentTypeDefinitions)) If host = RenameTestHost.OutOfProcess_SingleCall OrElse host = RenameTestHost.OutOfProcess_SplitCall Then composition = composition.WithTestHostParts(Remote.Testing.TestHost.OutOfProcess) End If Dim workspace = TestWorkspace.CreateWorkspace(workspaceXml, composition:=composition) workspace.SetTestLogger(AddressOf helper.WriteLine) If sourceGenerator IsNot Nothing Then workspace.OnAnalyzerReferenceAdded(workspace.CurrentSolution.ProjectIds.Single(), New TestGeneratorReference(sourceGenerator)) End If Dim engineResult As RenameEngineResult = Nothing Try If workspace.Documents.Where(Function(d) d.CursorPosition.HasValue).Count <> 1 Then AssertEx.Fail("The test must have a single $$ marking the symbol being renamed.") End If Dim cursorDocument = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue) Dim cursorPosition = cursorDocument.CursorPosition.Value Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id) Dim symbol = RenameLocations.ReferenceProcessing.TryGetRenamableSymbolAsync(document, cursorPosition, CancellationToken.None).Result If symbol Is Nothing Then AssertEx.Fail("The symbol touching the $$ could not be found.") End If Dim optionSet = workspace.Options If changedOptionSet IsNot Nothing Then For Each entry In changedOptionSet optionSet = optionSet.WithChangedOption(entry.Key, entry.Value) Next End If Dim result = GetConflictResolution(renameTo, workspace.CurrentSolution, symbol, optionSet, host) If expectFailure Then Assert.NotNull(result.ErrorMessage) Return engineResult Else Assert.Null(result.ErrorMessage) End If engineResult = New RenameEngineResult(workspace, result, renameTo) engineResult.AssertUnlabeledSpansRenamedAndHaveNoConflicts() Catch ' Something blew up, so we still own the test workspace If engineResult IsNot Nothing Then engineResult.Dispose() Else workspace.Dispose() End If Throw End Try Return engineResult End Function Private Shared Function GetConflictResolution( renameTo As String, solution As Solution, symbol As ISymbol, optionSet As OptionSet, host As RenameTestHost) As ConflictResolution Dim renameOptions = RenameOptionSet.From(solution, optionSet) If host = RenameTestHost.OutOfProcess_SplitCall Then ' This tests that each portion of rename can properly marshal to/from the OOP process. It validates ' features that need to call each part independently and operate on the intermediary values. Dim locations = Renamer.FindRenameLocationsAsync( solution, symbol, renameOptions, CancellationToken.None).GetAwaiter().GetResult() Return locations.ResolveConflictsAsync(renameTo, nonConflictSymbols:=Nothing, cancellationToken:=CancellationToken.None).GetAwaiter().GetResult() Else ' This tests that rename properly works when the entire call is remoted to OOP and the final result is ' marshaled back. Return Renamer.RenameSymbolAsync( solution, symbol, renameTo, renameOptions, nonConflictSymbols:=Nothing, CancellationToken.None).GetAwaiter().GetResult() End If End Function Friend ReadOnly Property ConflictResolution As ConflictResolution Get Return _resolution End Get End Property Private Sub AssertUnlabeledSpansRenamedAndHaveNoConflicts() For Each documentWithSpans In _workspace.Documents.Where(Function(d) Not d.IsSourceGenerated) Dim oldSyntaxTree = _workspace.CurrentSolution.GetDocument(documentWithSpans.Id).GetSyntaxTreeAsync().Result For Each span In documentWithSpans.SelectedSpans Dim location = oldSyntaxTree.GetLocation(span) AssertLocationReferencedAs(location, RelatedLocationType.NoConflict) AssertLocationReplacedWith(location, _renameTo) Next Next End Sub Public Sub AssertLabeledSpansInStringsAndCommentsAre(label As String, replacement As String) AssertLabeledSpansAre(label, replacement, RelatedLocationType.NoConflict, isRenameWithinStringOrComment:=True) End Sub Public Sub AssertLabeledSpansAre(label As String, Optional replacement As String = Nothing, Optional type As RelatedLocationType? = Nothing, Optional isRenameWithinStringOrComment As Boolean = False) For Each location In GetLabeledLocations(label) If replacement IsNot Nothing Then If type.HasValue Then AssertLocationReplacedWith(location, replacement, isRenameWithinStringOrComment) End If End If If type.HasValue AndAlso Not isRenameWithinStringOrComment Then AssertLocationReferencedAs(location, type.Value) End If Next End Sub Public Sub AssertLabeledSpecialSpansAre(label As String, replacement As String, type As RelatedLocationType?) For Each location In GetLabeledLocations(label) If replacement IsNot Nothing Then If type.HasValue Then AssertLocationReplacedWith(location, replacement) AssertLocationReferencedAs(location, type.Value) End If End If Next End Sub Private Function GetLabeledLocations(label As String) As IEnumerable(Of Location) Dim locations As New List(Of Location) For Each document In _workspace.Documents Dim annotatedSpans = document.AnnotatedSpans If annotatedSpans.ContainsKey(label) Then Dim syntaxTree = _workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxTreeAsync().Result For Each span In annotatedSpans(label) locations.Add(syntaxTree.GetLocation(span)) Next End If Next If locations.Count = 0 Then _failedAssert = True AssertEx.Fail(String.Format("The label '{0}' was not mentioned in the test.", label)) End If Return locations End Function Private Sub AssertLocationReplacedWith(location As Location, replacementText As String, Optional isRenameWithinStringOrComment As Boolean = False) Try Dim documentId = ConflictResolution.OldSolution.GetDocumentId(location.SourceTree) Dim newLocation = ConflictResolution.GetResolutionTextSpan(location.SourceSpan, documentId) Dim newTree = ConflictResolution.NewSolution.GetDocument(documentId).GetSyntaxTreeAsync().Result Dim newToken = newTree.GetRoot.FindToken(newLocation.Start, findInsideTrivia:=True) Dim newText As String If newToken.Span = newLocation Then newText = newToken.ToString() ElseIf isRenameWithinStringOrComment AndAlso newToken.FullSpan.Contains(newLocation) Then newText = newToken.ToFullString().Substring(newLocation.Start - newToken.FullSpan.Start, newLocation.Length) Else newText = newTree.GetText().ToString(newLocation) End If Assert.Equal(replacementText, newText) Catch ex As XunitException _failedAssert = True Throw End Try End Sub Private Sub AssertLocationReferencedAs(location As Location, type As RelatedLocationType) Try Dim documentId = ConflictResolution.OldSolution.GetDocumentId(location.SourceTree) Dim reference = _unassertedRelatedLocations.SingleOrDefault( Function(r) r.ConflictCheckSpan = location.SourceSpan AndAlso r.DocumentId = documentId) Assert.NotNull(reference) Assert.True(type.HasFlag(reference.Type)) _unassertedRelatedLocations.Remove(reference) Catch ex As XunitException _failedAssert = True Throw End Try End Sub Private Sub Dispose() Implements IDisposable.Dispose ' Make sure we're cleaned up. Don't want the test harness crashing... GC.SuppressFinalize(Me) ' If we failed some other assert, we know we're going to have things left ' over. So let's just suppress these so we don't lose the root cause If Not _failedAssert Then If _unassertedRelatedLocations.Count > 0 Then AssertEx.Fail( "There were additional related locations that were unasserted:" + Environment.NewLine _ + String.Join(Environment.NewLine, From location In _unassertedRelatedLocations Let document = _workspace.CurrentSolution.GetDocument(location.DocumentId) Let spanText = document.GetTextSynchronously(CancellationToken.None).ToString(location.ConflictCheckSpan) Select $"{spanText} @{document.Name}[{location.ConflictCheckSpan.Start}..{location.ConflictCheckSpan.End})")) End If End If _workspace.Dispose() End Sub Protected Overrides Sub Finalize() If Not Environment.HasShutdownStarted Then Throw New Exception("Dispose was not called in a Rename test.") End If End Sub Public Sub AssertReplacementTextInvalid() Try Assert.False(_resolution.ReplacementTextValid) Catch ex As XunitException _failedAssert = True Throw End Try End Sub Public Sub AssertIsInvalidResolution() Assert.Null(_resolution) End Sub End Class End Namespace
' 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 System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Imports Microsoft.VisualStudio.Text Imports Xunit.Abstractions Imports Xunit.Sdk Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename ''' <summary> ''' A class that holds the result of a rename engine call, and asserts ''' various things about it. This is used in the tests for the rename engine ''' to make asserting that certain spans were converted to what they should be. ''' </summary> Friend Class RenameEngineResult Implements IDisposable Private ReadOnly _workspace As TestWorkspace Private ReadOnly _resolution As ConflictResolution ''' <summary> ''' The list of related locations that haven't been asserted about yet. Items are ''' removed from here when they are asserted on, so the set should be empty once we're ''' done. ''' </summary> Private ReadOnly _unassertedRelatedLocations As HashSet(Of RelatedLocation) Private ReadOnly _renameTo As String Private _failedAssert As Boolean Private Sub New(workspace As TestWorkspace, resolution As ConflictResolution, renameTo As String) _workspace = workspace _resolution = resolution _unassertedRelatedLocations = New HashSet(Of RelatedLocation)(resolution.RelatedLocations) _renameTo = renameTo End Sub Public Shared Function Create( helper As ITestOutputHelper, workspaceXml As XElement, renameTo As String, host As RenameTestHost, Optional changedOptionSet As Dictionary(Of OptionKey, Object) = Nothing, Optional expectFailure As Boolean = False, Optional sourceGenerator As ISourceGenerator = Nothing) As RenameEngineResult Dim composition = EditorTestCompositions.EditorFeatures.AddParts(GetType(NoCompilationContentTypeLanguageService), GetType(NoCompilationContentTypeDefinitions)) If host = RenameTestHost.OutOfProcess_SingleCall OrElse host = RenameTestHost.OutOfProcess_SplitCall Then composition = composition.WithTestHostParts(Remote.Testing.TestHost.OutOfProcess) End If Dim workspace = TestWorkspace.CreateWorkspace(workspaceXml, composition:=composition) workspace.SetTestLogger(AddressOf helper.WriteLine) If sourceGenerator IsNot Nothing Then workspace.OnAnalyzerReferenceAdded(workspace.CurrentSolution.ProjectIds.Single(), New TestGeneratorReference(sourceGenerator)) End If Dim engineResult As RenameEngineResult = Nothing Try If workspace.Documents.Where(Function(d) d.CursorPosition.HasValue).Count <> 1 Then AssertEx.Fail("The test must have a single $$ marking the symbol being renamed.") End If Dim cursorDocument = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue) Dim cursorPosition = cursorDocument.CursorPosition.Value Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id) Dim symbol = RenameLocations.ReferenceProcessing.TryGetRenamableSymbolAsync(document, cursorPosition, CancellationToken.None).Result If symbol Is Nothing Then AssertEx.Fail("The symbol touching the $$ could not be found.") End If Dim optionSet = workspace.Options If changedOptionSet IsNot Nothing Then For Each entry In changedOptionSet optionSet = optionSet.WithChangedOption(entry.Key, entry.Value) Next End If Dim result = GetConflictResolution(renameTo, workspace.CurrentSolution, symbol, optionSet, host) If expectFailure Then Assert.NotNull(result.ErrorMessage) Return engineResult Else Assert.Null(result.ErrorMessage) End If engineResult = New RenameEngineResult(workspace, result, renameTo) engineResult.AssertUnlabeledSpansRenamedAndHaveNoConflicts() Catch ' Something blew up, so we still own the test workspace If engineResult IsNot Nothing Then engineResult.Dispose() Else workspace.Dispose() End If Throw End Try Return engineResult End Function Private Shared Function GetConflictResolution( renameTo As String, solution As Solution, symbol As ISymbol, optionSet As OptionSet, host As RenameTestHost) As ConflictResolution Dim renameOptions = RenameOptionSet.From(solution, optionSet) If host = RenameTestHost.OutOfProcess_SplitCall Then ' This tests that each portion of rename can properly marshal to/from the OOP process. It validates ' features that need to call each part independently and operate on the intermediary values. Dim locations = Renamer.FindRenameLocationsAsync( solution, symbol, renameOptions, CancellationToken.None).GetAwaiter().GetResult() Return locations.ResolveConflictsAsync(renameTo, nonConflictSymbols:=Nothing, cancellationToken:=CancellationToken.None).GetAwaiter().GetResult() Else ' This tests that rename properly works when the entire call is remoted to OOP and the final result is ' marshaled back. Return Renamer.RenameSymbolAsync( solution, symbol, renameTo, renameOptions, nonConflictSymbols:=Nothing, CancellationToken.None).GetAwaiter().GetResult() End If End Function Friend ReadOnly Property ConflictResolution As ConflictResolution Get Return _resolution End Get End Property Private Sub AssertUnlabeledSpansRenamedAndHaveNoConflicts() For Each documentWithSpans In _workspace.Documents.Where(Function(d) Not d.IsSourceGenerated) Dim oldSyntaxTree = _workspace.CurrentSolution.GetDocument(documentWithSpans.Id).GetSyntaxTreeAsync().Result For Each span In documentWithSpans.SelectedSpans Dim location = oldSyntaxTree.GetLocation(span) AssertLocationReferencedAs(location, RelatedLocationType.NoConflict) AssertLocationReplacedWith(location, _renameTo) Next Next End Sub Public Sub AssertLabeledSpansInStringsAndCommentsAre(label As String, replacement As String) AssertLabeledSpansAre(label, replacement, RelatedLocationType.NoConflict, isRenameWithinStringOrComment:=True) End Sub Public Sub AssertLabeledSpansAre(label As String, Optional replacement As String = Nothing, Optional type As RelatedLocationType? = Nothing, Optional isRenameWithinStringOrComment As Boolean = False) For Each location In GetLabeledLocations(label) If replacement IsNot Nothing Then If type.HasValue Then AssertLocationReplacedWith(location, replacement, isRenameWithinStringOrComment) End If End If If type.HasValue AndAlso Not isRenameWithinStringOrComment Then AssertLocationReferencedAs(location, type.Value) End If Next End Sub Public Sub AssertLabeledSpecialSpansAre(label As String, replacement As String, type As RelatedLocationType?) For Each location In GetLabeledLocations(label) If replacement IsNot Nothing Then If type.HasValue Then AssertLocationReplacedWith(location, replacement) AssertLocationReferencedAs(location, type.Value) End If End If Next End Sub Private Function GetLabeledLocations(label As String) As IEnumerable(Of Location) Dim locations As New List(Of Location) For Each document In _workspace.Documents Dim annotatedSpans = document.AnnotatedSpans If annotatedSpans.ContainsKey(label) Then Dim syntaxTree = _workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxTreeAsync().Result For Each span In annotatedSpans(label) locations.Add(syntaxTree.GetLocation(span)) Next End If Next If locations.Count = 0 Then _failedAssert = True AssertEx.Fail(String.Format("The label '{0}' was not mentioned in the test.", label)) End If Return locations End Function Private Sub AssertLocationReplacedWith(location As Location, replacementText As String, Optional isRenameWithinStringOrComment As Boolean = False) Try Dim documentId = ConflictResolution.OldSolution.GetDocumentId(location.SourceTree) Dim newLocation = ConflictResolution.GetResolutionTextSpan(location.SourceSpan, documentId) Dim newTree = ConflictResolution.NewSolution.GetDocument(documentId).GetSyntaxTreeAsync().Result Dim newToken = newTree.GetRoot.FindToken(newLocation.Start, findInsideTrivia:=True) Dim newText As String If newToken.Span = newLocation Then newText = newToken.ToString() ElseIf isRenameWithinStringOrComment AndAlso newToken.FullSpan.Contains(newLocation) Then newText = newToken.ToFullString().Substring(newLocation.Start - newToken.FullSpan.Start, newLocation.Length) Else newText = newTree.GetText().ToString(newLocation) End If Assert.Equal(replacementText, newText) Catch ex As XunitException _failedAssert = True Throw End Try End Sub Private Sub AssertLocationReferencedAs(location As Location, type As RelatedLocationType) Try Dim documentId = ConflictResolution.OldSolution.GetDocumentId(location.SourceTree) Dim reference = _unassertedRelatedLocations.SingleOrDefault( Function(r) r.ConflictCheckSpan = location.SourceSpan AndAlso r.DocumentId = documentId) Assert.NotNull(reference) Assert.True(type.HasFlag(reference.Type)) _unassertedRelatedLocations.Remove(reference) Catch ex As XunitException _failedAssert = True Throw End Try End Sub Private Sub Dispose() Implements IDisposable.Dispose ' Make sure we're cleaned up. Don't want the test harness crashing... GC.SuppressFinalize(Me) ' If we failed some other assert, we know we're going to have things left ' over. So let's just suppress these so we don't lose the root cause If Not _failedAssert Then If _unassertedRelatedLocations.Count > 0 Then AssertEx.Fail( "There were additional related locations that were unasserted:" + Environment.NewLine _ + String.Join(Environment.NewLine, From location In _unassertedRelatedLocations Let document = _workspace.CurrentSolution.GetDocument(location.DocumentId) Let spanText = document.GetTextSynchronously(CancellationToken.None).ToString(location.ConflictCheckSpan) Select $"{spanText} @{document.Name}[{location.ConflictCheckSpan.Start}..{location.ConflictCheckSpan.End})")) End If End If _workspace.Dispose() End Sub Protected Overrides Sub Finalize() If Not Environment.HasShutdownStarted Then Throw New Exception("Dispose was not called in a Rename test.") End If End Sub Public Sub AssertReplacementTextInvalid() Try Assert.False(_resolution.ReplacementTextValid) Catch ex As XunitException _failedAssert = True Throw End Try End Sub Public Sub AssertIsInvalidResolution() Assert.Null(_resolution) End Sub End Class End Namespace
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Features/Lsif/GeneratorTest/HoverTests.vb
' 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.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServer.Protocol Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests <UseExportProvider> Public NotInheritable Class HoverTests Private Const TestProjectAssemblyName As String = "TestProject" <Theory> <InlineData("class [|C|] { string s; }")> <InlineData("class C { void [|M|]() { } }")> <InlineData("class C { string [|s|]; }")> <InlineData("class C { void M(string [|s|]) { M(s); } }")> <InlineData("class C { void M(string s) { string [|local|] = """"; } }")> <InlineData(" class C { /// <summary>Doc Comment</summary> void [|M|]() { } }")> Public Async Function TestDefinition(code As String) As Task Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" AssemblyName=<%= TestProjectAssemblyName %> FilePath="Z:\TestProject.csproj" CommonReferences="true"> <Document Name="A.cs" FilePath="Z:\A.cs"> <%= code %> </Document> </Project> </Workspace>)) Dim rangeVertex = Await lsif.GetSelectedRangeAsync() Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() Dim hoverVertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).SingleOrDefault() Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Value, MarkupContent) Dim expectedHoverContents As String Select Case code Case "class [|C|] { string s; }" expectedHoverContents = "class C" Case "class C { void [|M|]() { } }" expectedHoverContents = "void C.M()" Case "class C { string [|s|]; }" expectedHoverContents = $"({FeaturesResources.field}) string C.s" Case "class C { void M(string [|s|]) { M(s); } }" expectedHoverContents = $"({FeaturesResources.parameter}) string s" Case "class C { void M(string s) { string [|local|] = """"; } }" expectedHoverContents = $"({FeaturesResources.local_variable}) string local" Case " class C { /// <summary>Doc Comment</summary> void [|M|]() { } }" expectedHoverContents = "void C.M() Doc Comment" Case Else Throw TestExceptionUtilities.UnexpectedValue(code) End Select Assert.Equal(MarkupKind.PlainText, hoverMarkupContent.Kind) Assert.Equal(expectedHoverContents + Environment.NewLine, hoverMarkupContent.Value) End Function <Theory> <InlineData("class C { [|string|] s; }")> <InlineData("class C { void M() { [|M|](); } }")> <InlineData("class C { void M(string s) { M([|s|]); } }")> <InlineData("class C { void M(string s) { string local = """"; M([|local|]); } }")> <InlineData("using [|S|] = System.String;")> <InlineData("class C { [|global|]::System.String s; }")> <InlineData(" class C { /// <see cref=""C.[|M|]()"" /> void M() { } }")> Public Async Function TestReference(code As String) As Task Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" AssemblyName=<%= TestProjectAssemblyName %> FilePath="Z:\TestProject.csproj" CommonReferences="true"> <Document Name="A.cs" FilePath="Z:\A.cs"> <%= code %> </Document> </Project> </Workspace>)) Dim rangeVertex = Await lsif.GetSelectedRangeAsync() Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() Dim hoverVertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).SingleOrDefault() Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Value, MarkupContent) Dim expectedHoverContents As String Select Case code Case "class C { [|string|] s; }" expectedHoverContents = "class System.String" Case "class C { void M() { [|M|](); } }" expectedHoverContents = "void C.M()" Case "class C { void M(string s) { M([|s|]); } }" expectedHoverContents = $"({FeaturesResources.parameter}) string s" Case "class C { void M(string s) { string local = """"; M([|local|]); } }" expectedHoverContents = $"({FeaturesResources.local_variable}) string local" Case "using [|S|] = System.String;" expectedHoverContents = "class System.String" Case "class C { [|global|]::System.String s; }" expectedHoverContents = "<global namespace>" Case " class C { /// <see cref=""C.[|M|]()"" /> void M() { } }" expectedHoverContents = "void C.M()" Case Else Throw TestExceptionUtilities.UnexpectedValue(code) End Select Assert.Equal(MarkupKind.PlainText, hoverMarkupContent.Kind) Assert.Equal(expectedHoverContents + Environment.NewLine, hoverMarkupContent.Value) End Function <Fact> Public Async Function ToplevelResultsInMultipleFiles() As Task Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" AssemblyName=<%= TestProjectAssemblyName %> FilePath="Z:\TestProject.csproj" CommonReferences="true"> <Document Name="A.cs" FilePath="Z:\A.cs"> class A { [|string|] s; } </Document> <Document Name="B.cs" FilePath="Z:\B.cs"> class B { [|string|] s; } </Document> <Document Name="C.cs" FilePath="Z:\C.cs"> class C { [|string|] s; } </Document> <Document Name="D.cs" FilePath="Z:\D.cs"> class D { [|string|] s; } </Document> <Document Name="E.cs" FilePath="Z:\E.cs"> class E { [|string|] s; } </Document> </Project> </Workspace>)) Dim hoverVertex As Graph.HoverResult = Nothing For Each rangeVertex In Await lsif.GetSelectedRangesAsync() Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() Dim vertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).Single() If hoverVertex Is Nothing Then hoverVertex = vertex Else Assert.Same(hoverVertex, vertex) End If Next Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Value, MarkupContent) Assert.Equal(MarkupKind.PlainText, hoverMarkupContent.Kind) Assert.Equal("class System.String" + Environment.NewLine, hoverMarkupContent.Value) End Function End Class End Namespace
' 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.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServer.Protocol Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests <UseExportProvider> Public NotInheritable Class HoverTests Private Const TestProjectAssemblyName As String = "TestProject" <Theory> <InlineData("class [|C|] { string s; }")> <InlineData("class C { void [|M|]() { } }")> <InlineData("class C { string [|s|]; }")> <InlineData("class C { void M(string [|s|]) { M(s); } }")> <InlineData("class C { void M(string s) { string [|local|] = """"; } }")> <InlineData(" class C { /// <summary>Doc Comment</summary> void [|M|]() { } }")> Public Async Function TestDefinition(code As String) As Task Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" AssemblyName=<%= TestProjectAssemblyName %> FilePath="Z:\TestProject.csproj" CommonReferences="true"> <Document Name="A.cs" FilePath="Z:\A.cs"> <%= code %> </Document> </Project> </Workspace>)) Dim rangeVertex = Await lsif.GetSelectedRangeAsync() Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() Dim hoverVertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).SingleOrDefault() Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Value, MarkupContent) Dim expectedHoverContents As String Select Case code Case "class [|C|] { string s; }" expectedHoverContents = "class C" Case "class C { void [|M|]() { } }" expectedHoverContents = "void C.M()" Case "class C { string [|s|]; }" expectedHoverContents = $"({FeaturesResources.field}) string C.s" Case "class C { void M(string [|s|]) { M(s); } }" expectedHoverContents = $"({FeaturesResources.parameter}) string s" Case "class C { void M(string s) { string [|local|] = """"; } }" expectedHoverContents = $"({FeaturesResources.local_variable}) string local" Case " class C { /// <summary>Doc Comment</summary> void [|M|]() { } }" expectedHoverContents = "void C.M() Doc Comment" Case Else Throw TestExceptionUtilities.UnexpectedValue(code) End Select Assert.Equal(MarkupKind.PlainText, hoverMarkupContent.Kind) Assert.Equal(expectedHoverContents + Environment.NewLine, hoverMarkupContent.Value) End Function <Theory> <InlineData("class C { [|string|] s; }")> <InlineData("class C { void M() { [|M|](); } }")> <InlineData("class C { void M(string s) { M([|s|]); } }")> <InlineData("class C { void M(string s) { string local = """"; M([|local|]); } }")> <InlineData("using [|S|] = System.String;")> <InlineData("class C { [|global|]::System.String s; }")> <InlineData(" class C { /// <see cref=""C.[|M|]()"" /> void M() { } }")> Public Async Function TestReference(code As String) As Task Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" AssemblyName=<%= TestProjectAssemblyName %> FilePath="Z:\TestProject.csproj" CommonReferences="true"> <Document Name="A.cs" FilePath="Z:\A.cs"> <%= code %> </Document> </Project> </Workspace>)) Dim rangeVertex = Await lsif.GetSelectedRangeAsync() Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() Dim hoverVertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).SingleOrDefault() Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Value, MarkupContent) Dim expectedHoverContents As String Select Case code Case "class C { [|string|] s; }" expectedHoverContents = "class System.String" Case "class C { void M() { [|M|](); } }" expectedHoverContents = "void C.M()" Case "class C { void M(string s) { M([|s|]); } }" expectedHoverContents = $"({FeaturesResources.parameter}) string s" Case "class C { void M(string s) { string local = """"; M([|local|]); } }" expectedHoverContents = $"({FeaturesResources.local_variable}) string local" Case "using [|S|] = System.String;" expectedHoverContents = "class System.String" Case "class C { [|global|]::System.String s; }" expectedHoverContents = "<global namespace>" Case " class C { /// <see cref=""C.[|M|]()"" /> void M() { } }" expectedHoverContents = "void C.M()" Case Else Throw TestExceptionUtilities.UnexpectedValue(code) End Select Assert.Equal(MarkupKind.PlainText, hoverMarkupContent.Kind) Assert.Equal(expectedHoverContents + Environment.NewLine, hoverMarkupContent.Value) End Function <Fact> Public Async Function ToplevelResultsInMultipleFiles() As Task Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" AssemblyName=<%= TestProjectAssemblyName %> FilePath="Z:\TestProject.csproj" CommonReferences="true"> <Document Name="A.cs" FilePath="Z:\A.cs"> class A { [|string|] s; } </Document> <Document Name="B.cs" FilePath="Z:\B.cs"> class B { [|string|] s; } </Document> <Document Name="C.cs" FilePath="Z:\C.cs"> class C { [|string|] s; } </Document> <Document Name="D.cs" FilePath="Z:\D.cs"> class D { [|string|] s; } </Document> <Document Name="E.cs" FilePath="Z:\E.cs"> class E { [|string|] s; } </Document> </Project> </Workspace>)) Dim hoverVertex As Graph.HoverResult = Nothing For Each rangeVertex In Await lsif.GetSelectedRangesAsync() Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() Dim vertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).Single() If hoverVertex Is Nothing Then hoverVertex = vertex Else Assert.Same(hoverVertex, vertex) End If Next Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Value, MarkupContent) Assert.Equal(MarkupKind.PlainText, hoverMarkupContent.Kind) Assert.Equal("class System.String" + Environment.NewLine, hoverMarkupContent.Value) End Function End Class End Namespace
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Tools/BuildBoss/ProjectType.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { internal enum ProjectFileType { CSharp, Basic, Shared, Tool, Unknown } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { internal enum ProjectFileType { CSharp, Basic, Shared, Tool, Unknown } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_WhileStatement.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using System.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitWhileStatement(BoundWhileStatement node) { Debug.Assert(node != null); var rewrittenCondition = VisitExpression(node.Condition); var rewrittenBody = VisitStatement(node.Body); Debug.Assert(rewrittenBody is { }); // EnC: We need to insert a hidden sequence point to handle function remapping in case // the containing method is edited while methods invoked in the condition are being executed. if (!node.WasCompilerGenerated && this.Instrument) { rewrittenCondition = _instrumenter.InstrumentWhileStatementCondition(node, rewrittenCondition, _factory); } return RewriteWhileStatement( node, node.Locals, rewrittenCondition, rewrittenBody, node.BreakLabel, node.ContinueLabel, node.HasErrors); } private BoundStatement RewriteWhileStatement( BoundLoopStatement loop, BoundExpression rewrittenCondition, BoundStatement rewrittenBody, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors) { Debug.Assert(loop.Kind == BoundKind.WhileStatement || loop.Kind == BoundKind.ForEachStatement); // while (condition) // body; // // becomes // // goto continue; // start: // { // body // continue: // GotoIfTrue condition start; // } // break: SyntaxNode syntax = loop.Syntax; var startLabel = new GeneratedLabelSymbol("start"); BoundStatement ifConditionGotoStart = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, true, startLabel); BoundStatement gotoContinue = new BoundGotoStatement(syntax, continueLabel); if (this.Instrument && !loop.WasCompilerGenerated) { switch (loop.Kind) { case BoundKind.WhileStatement: ifConditionGotoStart = _instrumenter.InstrumentWhileStatementConditionalGotoStartOrBreak((BoundWhileStatement)loop, ifConditionGotoStart); break; case BoundKind.ForEachStatement: ifConditionGotoStart = _instrumenter.InstrumentForEachStatementConditionalGotoStart((BoundForEachStatement)loop, ifConditionGotoStart); break; default: throw ExceptionUtilities.UnexpectedValue(loop.Kind); } // mark the initial jump as hidden. We do it to tell that this is not a part of previous statement. This // jump may be a target of another jump (for example if loops are nested) and that would give the // impression that the previous statement is being re-executed. gotoContinue = BoundSequencePoint.CreateHidden(gotoContinue); } return BoundStatementList.Synthesized(syntax, hasErrors, gotoContinue, new BoundLabelStatement(syntax, startLabel), rewrittenBody, new BoundLabelStatement(syntax, continueLabel), ifConditionGotoStart, new BoundLabelStatement(syntax, breakLabel)); } private BoundStatement RewriteWhileStatement( BoundWhileStatement loop, ImmutableArray<LocalSymbol> locals, BoundExpression rewrittenCondition, BoundStatement rewrittenBody, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors) { if (locals.IsEmpty) { return RewriteWhileStatement(loop, rewrittenCondition, rewrittenBody, breakLabel, continueLabel, hasErrors); } // We need to enter scope-block from the top, that is where an instance of a display class will be created // if any local is captured within a lambda. // while (condition) // body; // // becomes // // continue: // { // GotoIfFalse condition break; // body // goto continue; // } // break: SyntaxNode syntax = loop.Syntax; BoundStatement continueLabelStatement = new BoundLabelStatement(syntax, continueLabel); BoundStatement ifNotConditionGotoBreak = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, false, breakLabel); if (this.Instrument && !loop.WasCompilerGenerated) { ifNotConditionGotoBreak = _instrumenter.InstrumentWhileStatementConditionalGotoStartOrBreak(loop, ifNotConditionGotoBreak); continueLabelStatement = BoundSequencePoint.CreateHidden(continueLabelStatement); } return BoundStatementList.Synthesized(syntax, hasErrors, continueLabelStatement, new BoundBlock(syntax, locals, ImmutableArray.Create( ifNotConditionGotoBreak, rewrittenBody, new BoundGotoStatement(syntax, continueLabel))), new BoundLabelStatement(syntax, breakLabel)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using System.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitWhileStatement(BoundWhileStatement node) { Debug.Assert(node != null); var rewrittenCondition = VisitExpression(node.Condition); var rewrittenBody = VisitStatement(node.Body); Debug.Assert(rewrittenBody is { }); // EnC: We need to insert a hidden sequence point to handle function remapping in case // the containing method is edited while methods invoked in the condition are being executed. if (!node.WasCompilerGenerated && this.Instrument) { rewrittenCondition = _instrumenter.InstrumentWhileStatementCondition(node, rewrittenCondition, _factory); } return RewriteWhileStatement( node, node.Locals, rewrittenCondition, rewrittenBody, node.BreakLabel, node.ContinueLabel, node.HasErrors); } private BoundStatement RewriteWhileStatement( BoundLoopStatement loop, BoundExpression rewrittenCondition, BoundStatement rewrittenBody, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors) { Debug.Assert(loop.Kind == BoundKind.WhileStatement || loop.Kind == BoundKind.ForEachStatement); // while (condition) // body; // // becomes // // goto continue; // start: // { // body // continue: // GotoIfTrue condition start; // } // break: SyntaxNode syntax = loop.Syntax; var startLabel = new GeneratedLabelSymbol("start"); BoundStatement ifConditionGotoStart = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, true, startLabel); BoundStatement gotoContinue = new BoundGotoStatement(syntax, continueLabel); if (this.Instrument && !loop.WasCompilerGenerated) { switch (loop.Kind) { case BoundKind.WhileStatement: ifConditionGotoStart = _instrumenter.InstrumentWhileStatementConditionalGotoStartOrBreak((BoundWhileStatement)loop, ifConditionGotoStart); break; case BoundKind.ForEachStatement: ifConditionGotoStart = _instrumenter.InstrumentForEachStatementConditionalGotoStart((BoundForEachStatement)loop, ifConditionGotoStart); break; default: throw ExceptionUtilities.UnexpectedValue(loop.Kind); } // mark the initial jump as hidden. We do it to tell that this is not a part of previous statement. This // jump may be a target of another jump (for example if loops are nested) and that would give the // impression that the previous statement is being re-executed. gotoContinue = BoundSequencePoint.CreateHidden(gotoContinue); } return BoundStatementList.Synthesized(syntax, hasErrors, gotoContinue, new BoundLabelStatement(syntax, startLabel), rewrittenBody, new BoundLabelStatement(syntax, continueLabel), ifConditionGotoStart, new BoundLabelStatement(syntax, breakLabel)); } private BoundStatement RewriteWhileStatement( BoundWhileStatement loop, ImmutableArray<LocalSymbol> locals, BoundExpression rewrittenCondition, BoundStatement rewrittenBody, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors) { if (locals.IsEmpty) { return RewriteWhileStatement(loop, rewrittenCondition, rewrittenBody, breakLabel, continueLabel, hasErrors); } // We need to enter scope-block from the top, that is where an instance of a display class will be created // if any local is captured within a lambda. // while (condition) // body; // // becomes // // continue: // { // GotoIfFalse condition break; // body // goto continue; // } // break: SyntaxNode syntax = loop.Syntax; BoundStatement continueLabelStatement = new BoundLabelStatement(syntax, continueLabel); BoundStatement ifNotConditionGotoBreak = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, false, breakLabel); if (this.Instrument && !loop.WasCompilerGenerated) { ifNotConditionGotoBreak = _instrumenter.InstrumentWhileStatementConditionalGotoStartOrBreak(loop, ifNotConditionGotoBreak); continueLabelStatement = BoundSequencePoint.CreateHidden(continueLabelStatement); } return BoundStatementList.Synthesized(syntax, hasErrors, continueLabelStatement, new BoundBlock(syntax, locals, ImmutableArray.Create( ifNotConditionGotoBreak, rewrittenBody, new BoundGotoStatement(syntax, continueLabel))), new BoundLabelStatement(syntax, breakLabel)); } } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Workspaces/VisualBasic/Portable/CodeGeneration/ConstructorGenerator.vb
' 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.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Module ConstructorGenerator Private Function LastConstructorOrField(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return If(LastConstructor(members), LastField(members)) End Function Friend Function AddConstructorTo(destination As TypeBlockSyntax, constructor As IMethodSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean)) As TypeBlockSyntax Dim constructorDeclaration = GenerateConstructorDeclaration(constructor, GetDestination(destination), options) Dim members = Insert(destination.Members, constructorDeclaration, options, availableIndices, after:=AddressOf LastConstructorOrField, before:=AddressOf FirstMember) Return FixTerminators(destination.WithMembers(members)) End Function Friend Function GenerateConstructorDeclaration(constructor As IMethodSymbol, destination As CodeGenerationDestination, options As CodeGenerationOptions) As StatementSyntax Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of StatementSyntax)(constructor, options) If reusableSyntax IsNot Nothing Then Return reusableSyntax End If Dim constructorStatement = SyntaxFactory.SubNewStatement() _ .WithAttributeLists(AttributeGenerator.GenerateAttributeBlocks(constructor.GetAttributes(), options)) _ .WithModifiers(GenerateModifiers(constructor, destination, options)) _ .WithParameterList(ParameterGenerator.GenerateParameterList(constructor.Parameters, options)) Dim hasNoBody = Not options.GenerateMethodBodies Dim declaration = If(hasNoBody, DirectCast(constructorStatement, StatementSyntax), SyntaxFactory.ConstructorBlock( constructorStatement, statements:=GenerateStatements(constructor), endSubStatement:=SyntaxFactory.EndSubStatement())) Return AddAnnotationsTo(constructor, AddFormatterAndCodeGeneratorAnnotationsTo( ConditionallyAddDocumentationCommentTo(declaration, constructor, options))) End Function Private Function GenerateStatements(constructor As IMethodSymbol) As SyntaxList(Of StatementSyntax) If CodeGenerationConstructorInfo.GetStatements(constructor).IsDefault AndAlso CodeGenerationConstructorInfo.GetBaseConstructorArgumentsOpt(constructor).IsDefault AndAlso CodeGenerationConstructorInfo.GetThisConstructorArgumentsOpt(constructor).IsDefault Then Return Nothing End If Dim statements = New List(Of StatementSyntax) If Not CodeGenerationConstructorInfo.GetBaseConstructorArgumentsOpt(constructor).IsDefault Then statements.Add(CreateBaseConstructorCall(constructor)) End If If Not CodeGenerationConstructorInfo.GetThisConstructorArgumentsOpt(constructor).IsDefault Then statements.Add(CreateThisConstructorCall(CodeGenerationConstructorInfo.GetThisConstructorArgumentsOpt(constructor))) End If If Not CodeGenerationConstructorInfo.GetStatements(constructor).IsDefault Then statements.AddRange(StatementGenerator.GenerateStatements( CodeGenerationConstructorInfo.GetStatements(constructor))) End If Return SyntaxFactory.List(statements) End Function Private Function GenerateModifiers(constructor As IMethodSymbol, destination As CodeGenerationDestination, options As CodeGenerationOptions) As SyntaxTokenList Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens) If constructor.IsStatic Then tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword)) Else AddAccessibilityModifiers(constructor.DeclaredAccessibility, tokens, destination, options, Accessibility.Public) End If Return SyntaxFactory.TokenList(tokens) End Using End Function Private Function CreateBaseConstructorCall(constructor As IMethodSymbol) As StatementSyntax Return SyntaxFactory.ExpressionStatement( expression:=SyntaxFactory.InvocationExpression( SyntaxFactory.SimpleMemberAccessExpression( expression:=SyntaxFactory.MyBaseExpression(), operatorToken:=SyntaxFactory.Token(SyntaxKind.DotToken), name:=SyntaxFactory.IdentifierName("New")), argumentList:=SyntaxFactory.ArgumentList( arguments:=SyntaxFactory.SeparatedList(constructor.Parameters.Select(Function(p) SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName(p.Name))).OfType(Of ArgumentSyntax))))) End Function Private Function CreateThisConstructorCall(arguments As IList(Of SyntaxNode)) As StatementSyntax Return SyntaxFactory.ExpressionStatement( expression:=SyntaxFactory.InvocationExpression( SyntaxFactory.SimpleMemberAccessExpression( expression:=SyntaxFactory.MeExpression(), operatorToken:=SyntaxFactory.Token(SyntaxKind.DotToken), name:=SyntaxFactory.IdentifierName("New")), argumentList:=ArgumentGenerator.GenerateArgumentList(arguments))) End Function End Module End Namespace
' 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.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Module ConstructorGenerator Private Function LastConstructorOrField(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return If(LastConstructor(members), LastField(members)) End Function Friend Function AddConstructorTo(destination As TypeBlockSyntax, constructor As IMethodSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean)) As TypeBlockSyntax Dim constructorDeclaration = GenerateConstructorDeclaration(constructor, GetDestination(destination), options) Dim members = Insert(destination.Members, constructorDeclaration, options, availableIndices, after:=AddressOf LastConstructorOrField, before:=AddressOf FirstMember) Return FixTerminators(destination.WithMembers(members)) End Function Friend Function GenerateConstructorDeclaration(constructor As IMethodSymbol, destination As CodeGenerationDestination, options As CodeGenerationOptions) As StatementSyntax Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of StatementSyntax)(constructor, options) If reusableSyntax IsNot Nothing Then Return reusableSyntax End If Dim constructorStatement = SyntaxFactory.SubNewStatement() _ .WithAttributeLists(AttributeGenerator.GenerateAttributeBlocks(constructor.GetAttributes(), options)) _ .WithModifiers(GenerateModifiers(constructor, destination, options)) _ .WithParameterList(ParameterGenerator.GenerateParameterList(constructor.Parameters, options)) Dim hasNoBody = Not options.GenerateMethodBodies Dim declaration = If(hasNoBody, DirectCast(constructorStatement, StatementSyntax), SyntaxFactory.ConstructorBlock( constructorStatement, statements:=GenerateStatements(constructor), endSubStatement:=SyntaxFactory.EndSubStatement())) Return AddAnnotationsTo(constructor, AddFormatterAndCodeGeneratorAnnotationsTo( ConditionallyAddDocumentationCommentTo(declaration, constructor, options))) End Function Private Function GenerateStatements(constructor As IMethodSymbol) As SyntaxList(Of StatementSyntax) If CodeGenerationConstructorInfo.GetStatements(constructor).IsDefault AndAlso CodeGenerationConstructorInfo.GetBaseConstructorArgumentsOpt(constructor).IsDefault AndAlso CodeGenerationConstructorInfo.GetThisConstructorArgumentsOpt(constructor).IsDefault Then Return Nothing End If Dim statements = New List(Of StatementSyntax) If Not CodeGenerationConstructorInfo.GetBaseConstructorArgumentsOpt(constructor).IsDefault Then statements.Add(CreateBaseConstructorCall(constructor)) End If If Not CodeGenerationConstructorInfo.GetThisConstructorArgumentsOpt(constructor).IsDefault Then statements.Add(CreateThisConstructorCall(CodeGenerationConstructorInfo.GetThisConstructorArgumentsOpt(constructor))) End If If Not CodeGenerationConstructorInfo.GetStatements(constructor).IsDefault Then statements.AddRange(StatementGenerator.GenerateStatements( CodeGenerationConstructorInfo.GetStatements(constructor))) End If Return SyntaxFactory.List(statements) End Function Private Function GenerateModifiers(constructor As IMethodSymbol, destination As CodeGenerationDestination, options As CodeGenerationOptions) As SyntaxTokenList Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens) If constructor.IsStatic Then tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword)) Else AddAccessibilityModifiers(constructor.DeclaredAccessibility, tokens, destination, options, Accessibility.Public) End If Return SyntaxFactory.TokenList(tokens) End Using End Function Private Function CreateBaseConstructorCall(constructor As IMethodSymbol) As StatementSyntax Return SyntaxFactory.ExpressionStatement( expression:=SyntaxFactory.InvocationExpression( SyntaxFactory.SimpleMemberAccessExpression( expression:=SyntaxFactory.MyBaseExpression(), operatorToken:=SyntaxFactory.Token(SyntaxKind.DotToken), name:=SyntaxFactory.IdentifierName("New")), argumentList:=SyntaxFactory.ArgumentList( arguments:=SyntaxFactory.SeparatedList(constructor.Parameters.Select(Function(p) SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName(p.Name))).OfType(Of ArgumentSyntax))))) End Function Private Function CreateThisConstructorCall(arguments As IList(Of SyntaxNode)) As StatementSyntax Return SyntaxFactory.ExpressionStatement( expression:=SyntaxFactory.InvocationExpression( SyntaxFactory.SimpleMemberAccessExpression( expression:=SyntaxFactory.MeExpression(), operatorToken:=SyntaxFactory.Token(SyntaxKind.DotToken), name:=SyntaxFactory.IdentifierName("New")), argumentList:=ArgumentGenerator.GenerateArgumentList(arguments))) End Function End Module End Namespace
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Compilers/Core/Portable/FileSystem/RelativePathResolver.cs
// 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. #nullable disable #pragma warning disable 436 // The type 'RelativePathResolver' conflicts with imported type using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Roslyn.Utilities; using System.IO; namespace Microsoft.CodeAnalysis { internal class RelativePathResolver : IEquatable<RelativePathResolver> { public ImmutableArray<string> SearchPaths { get; } public string BaseDirectory { get; } /// <summary> /// Initializes a new instance of the <see cref="RelativePathResolver"/> class. /// </summary> /// <param name="searchPaths">An ordered set of fully qualified /// paths which are searched when resolving assembly names.</param> /// <param name="baseDirectory">Directory used when resolving relative paths.</param> public RelativePathResolver(ImmutableArray<string> searchPaths, string baseDirectory) { Debug.Assert(searchPaths.All(PathUtilities.IsAbsolute)); Debug.Assert(baseDirectory == null || PathUtilities.GetPathKind(baseDirectory) == PathKind.Absolute); SearchPaths = searchPaths; BaseDirectory = baseDirectory; } public string ResolvePath(string reference, string baseFilePath) { string resolvedPath = FileUtilities.ResolveRelativePath(reference, baseFilePath, BaseDirectory, SearchPaths, FileExists); if (resolvedPath == null) { return null; } return FileUtilities.TryNormalizeAbsolutePath(resolvedPath); } protected virtual bool FileExists(string fullPath) { Debug.Assert(fullPath != null); Debug.Assert(PathUtilities.IsAbsolute(fullPath)); return File.Exists(fullPath); } public RelativePathResolver WithSearchPaths(ImmutableArray<string> searchPaths) => new(searchPaths, BaseDirectory); public RelativePathResolver WithBaseDirectory(string baseDirectory) => new(SearchPaths, baseDirectory); public bool Equals(RelativePathResolver other) => BaseDirectory == other.BaseDirectory && SearchPaths.SequenceEqual(other.SearchPaths); public override int GetHashCode() => Hash.Combine(BaseDirectory, Hash.CombineValues(SearchPaths)); public override bool Equals(object obj) => Equals(obj as RelativePathResolver); } }
// 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. #nullable disable #pragma warning disable 436 // The type 'RelativePathResolver' conflicts with imported type using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Roslyn.Utilities; using System.IO; namespace Microsoft.CodeAnalysis { internal class RelativePathResolver : IEquatable<RelativePathResolver> { public ImmutableArray<string> SearchPaths { get; } public string BaseDirectory { get; } /// <summary> /// Initializes a new instance of the <see cref="RelativePathResolver"/> class. /// </summary> /// <param name="searchPaths">An ordered set of fully qualified /// paths which are searched when resolving assembly names.</param> /// <param name="baseDirectory">Directory used when resolving relative paths.</param> public RelativePathResolver(ImmutableArray<string> searchPaths, string baseDirectory) { Debug.Assert(searchPaths.All(PathUtilities.IsAbsolute)); Debug.Assert(baseDirectory == null || PathUtilities.GetPathKind(baseDirectory) == PathKind.Absolute); SearchPaths = searchPaths; BaseDirectory = baseDirectory; } public string ResolvePath(string reference, string baseFilePath) { string resolvedPath = FileUtilities.ResolveRelativePath(reference, baseFilePath, BaseDirectory, SearchPaths, FileExists); if (resolvedPath == null) { return null; } return FileUtilities.TryNormalizeAbsolutePath(resolvedPath); } protected virtual bool FileExists(string fullPath) { Debug.Assert(fullPath != null); Debug.Assert(PathUtilities.IsAbsolute(fullPath)); return File.Exists(fullPath); } public RelativePathResolver WithSearchPaths(ImmutableArray<string> searchPaths) => new(searchPaths, BaseDirectory); public RelativePathResolver WithBaseDirectory(string baseDirectory) => new(SearchPaths, baseDirectory); public bool Equals(RelativePathResolver other) => BaseDirectory == other.BaseDirectory && SearchPaths.SequenceEqual(other.SearchPaths); public override int GetHashCode() => Hash.Combine(BaseDirectory, Hash.CombineValues(SearchPaths)); public override bool Equals(object obj) => Equals(obj as RelativePathResolver); } }
-1
dotnet/roslyn
56,187
Add External Access options for TypeScript
Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
tmat
"2021-09-03T22:11:29Z"
"2021-09-07T17:42:47Z"
4fada24142fb5bfdf4ec530e56eebf712227cbc9
409fcc26226c782f306d81cdbeed06d86b2de3f4
Add External Access options for TypeScript. Used in https://devdiv.visualstudio.com/DevDiv/_git/TypeScript-VS/pullrequest/349183
./src/Compilers/VisualBasic/Test/Semantic/Semantics/Lambda_Relaxation.vb
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class Lambda_Relaxation Inherits BasicTestBase <Fact()> Public Sub ArgumentIsVbOrBoxWidening() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Integer) = Sub(x As Object) 'BIND1:"Sub(x As Object)" System.Console.WriteLine(x) End Sub x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWidening", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Integer)" IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0024: ldc.i4.2 IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: box "Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub ArgumentIsVbOrBoxWidening2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Integer) x1 = CType(Sub(x As Object) 'BIND1:"Sub(x As Object)" System.Console.WriteLine(x) End Sub, System.Action(Of Integer)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Identity", conv.Kind.ToString()) Assert.True(conv.Exists) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Integer)" IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0024: ldc.i4.2 IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: box "Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentIsVbOrBoxWidening3() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Integer) x1 = DirectCast(Sub(x As Object) 'BIND1:"Sub(x As Object)" System.Console.WriteLine(x) End Sub, System.Action(Of Integer)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Identity", conv.Kind.ToString()) Assert.True(conv.Exists) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Integer)" IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0024: ldc.i4.2 IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: box "Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentIsVbOrBoxWidening4() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Integer) x1 = TryCast(Sub(x As Object) 'BIND1:"Sub(x As Object)" System.Console.WriteLine(x) End Sub, System.Action(Of Integer)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Identity", conv.Kind.ToString()) Assert.True(conv.Exists) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Integer)" IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0024: ldc.i4.2 IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: box "Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentIsNarrowing() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Object) = Sub(x As Integer) 'BIND1:"Sub(x As Integer)" System.Console.WriteLine(x) End Sub x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Object)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Object)" IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0024: ldc.i4.2 IL_0025: box "Integer" IL_002a: callvirt "Sub System.Action(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Integer)" IL_0006: ret } ]]>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) If True Then Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Object)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42016: Implicit conversion from 'Object' to 'Integer'. Dim x1 As System.Action(Of Object) = Sub(x As Integer) 'BIND1:"Sub(x As Integer)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) If True Then Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Object)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Dim x1 As System.Action(Of Object) = Sub(x As Integer) 'BIND1:"Sub(x As Integer)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(543114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543114")> <Fact()> Public Sub ArgumentIsNarrowing2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Object) = CType(Sub(x As Integer) System.Console.WriteLine(x) End Sub, System.Action(Of Object)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Object)" IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0024: ldc.i4.2 IL_0025: box "Integer" IL_002a: callvirt "Sub System.Action(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Integer)" IL_0006: ret } ]]>) Next End Sub <WorkItem(543114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543114")> <Fact()> Public Sub ArgumentIsNarrowing3() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Object) = DirectCast(Sub(x As Integer) System.Console.WriteLine(x) End Sub, System.Action(Of Object)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Object)" IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0024: ldc.i4.2 IL_0025: box "Integer" IL_002a: callvirt "Sub System.Action(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Integer)" IL_0006: ret } ]]>) Next End Sub <WorkItem(543114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543114")> <Fact()> Public Sub ArgumentIsNarrowing4() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Object) = TryCast(Sub(x As Integer) System.Console.WriteLine(x) End Sub, System.Action(Of Object)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Object)" IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0024: ldc.i4.2 IL_0025: box "Integer" IL_002a: callvirt "Sub System.Action(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Integer)" IL_0006: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentIsClrWidening() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action(Of System.Collections.Generic.IEnumerable(Of Integer)) = Sub(x As System.Collections.IEnumerable) 'BIND1:"Sub(x As System.Collections.IEnumerable)" System.Console.WriteLine(x) End Sub x1(New Integer() {}) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Collections.Generic.IEnumerable(Of System.Int32))", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWidening", conv.Kind.ToString()) Assert.True(conv.Exists) Dim verifier = CompileAndVerify(compilation, expectedOutput:="System.Int32[]") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As System.Action(Of System.Collections.Generic.IEnumerable(Of Integer))" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As System.Action(Of System.Collections.Generic.IEnumerable(Of Integer))" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(System.Collections.IEnumerable)" IL_0019: newobj "Sub System.Action(Of System.Collections.Generic.IEnumerable(Of Integer))..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As System.Action(Of System.Collections.Generic.IEnumerable(Of Integer))" IL_0024: ldc.i4.0 IL_0025: newarr "Integer" IL_002a: callvirt "Sub System.Action(Of System.Collections.Generic.IEnumerable(Of Integer)).Invoke(System.Collections.Generic.IEnumerable(Of Integer))" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Object)" IL_0006: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentConversionError() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action(Of Integer) = Sub(x As System.Guid) 'BIND1:"Sub(x As System.Guid)" End Sub End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of Integer)'. Dim x1 As Action(Of Integer) = Sub(x As System.Guid) 'BIND1:"Sub(x As System.Guid)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ArgumentConversionError2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action(Of Integer) = ((Sub(x As System.Guid) 'BIND1:"Sub(x As System.Guid)" End Sub)) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of Integer)'. Dim x1 As Action(Of Integer) = ((Sub(x As System.Guid) 'BIND1:"Sub(x As System.Guid)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ReturnValueIsDropped1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action = Function() 1 'BIND1:"Function()" Dim x2 As Action = Function() 'BIND2:"Function()" System.Console.WriteLine("x2") Return 2 End Function x1() x2() End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWideningDropReturnOrArgs", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWideningDropReturnOrArgs", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="x2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 85 (0x55) .maxstack 2 .locals init (System.Action V_0) //x1 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1()" IL_0019: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action" IL_0024: stloc.0 IL_0025: ldsfld "Program._Closure$__.$IR0-2 As System.Action" IL_002a: brfalse.s IL_0033 IL_002c: ldsfld "Program._Closure$__.$IR0-2 As System.Action" IL_0031: br.s IL_0049 IL_0033: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0038: ldftn "Sub Program._Closure$__._Lambda$__R0-2()" IL_003e: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_0043: dup IL_0044: stsfld "Program._Closure$__.$IR0-2 As System.Action" IL_0049: ldloc.0 IL_004a: callvirt "Sub System.Action.Invoke()" IL_004f: callvirt "Sub System.Action.Invoke()" IL_0054: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-0() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: pop IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-2", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-1() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: pop IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldstr "x2" IL_0005: call "Sub System.Console.WriteLine(String)" IL_000a: ldc.i4.2 IL_000b: ret } ]]>) Next End Sub <Fact()> Public Sub ReturnValueIsDropped2_ReturnTypeInferenceError() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action = Function() AddressOf Main 'BIND1:"Function()" Dim x2 As Action = Function() 'BIND2:"Function()" Return AddressOf Main End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30581: 'AddressOf' expression cannot be converted to 'Object' because 'Object' is not a delegate type. Dim x1 As Action = Function() AddressOf Main 'BIND1:"Function()" ~~~~~~~~~~~~~~ BC36751: Cannot infer a return type. Consider adding an 'As' clause to specify the return type. Dim x2 As Action = Function() 'BIND2:"Function()" ~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub SubToFunction() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer) = Sub() 'BIND1:"Sub()" End Sub End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36670: Nested sub does not have a signature that is compatible with delegate 'Func(Of Integer)'. Dim x1 As Func(Of Integer) = Sub() 'BIND1:"Sub()" ~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ReturnIsWidening() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer) = Function() CObj(1) 'BIND1:"Function()" Dim x2 As Func(Of Integer) = Function() As Object 'BIND2:"Function() As Object" Return 2 End Function System.Console.WriteLine(x1()) System.Console.WriteLine(x2()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 95 (0x5f) .maxstack 2 .locals init (System.Func(Of Integer) V_0) //x1 IL_0000: ldsfld "Program._Closure$__.$I0-0 As System.Func(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As System.Func(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-0() As Integer" IL_0019: newobj "Sub System.Func(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As System.Func(Of Integer)" IL_0024: stloc.0 IL_0025: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer)" IL_002a: brfalse.s IL_0033 IL_002c: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer)" IL_0031: br.s IL_0049 IL_0033: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0038: ldftn "Function Program._Closure$__._Lambda$__R0-1() As Integer" IL_003e: newobj "Sub System.Func(Of Integer)..ctor(Object, System.IntPtr)" IL_0043: dup IL_0044: stsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer)" IL_0049: ldloc.0 IL_004a: callvirt "Function System.Func(Of Integer).Invoke() As Integer" IL_004f: call "Sub System.Console.WriteLine(Integer)" IL_0054: callvirt "Function System.Func(Of Integer).Invoke() As Integer" IL_0059: call "Sub System.Console.WriteLine(Integer)" IL_005e: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: box "Integer" IL_0006: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_000b: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 47 (0x2f) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-1() As Object" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Object).Invoke() As Object" IL_0029: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002e: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: ret } ]]>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If End If CompileAndVerify(compilation, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42016: Implicit conversion from 'Object' to 'Integer'. Dim x1 As Func(Of Integer) = Function() CObj(1) 'BIND1:"Function()" ~~~~~~~ BC42016: Implicit conversion from 'Object' to 'Integer'. Dim x2 As Func(Of Integer) = Function() As Object 'BIND2:"Function() As Object" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Dim x1 As Func(Of Integer) = Function() CObj(1) 'BIND1:"Function()" ~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Dim x2 As Func(Of Integer) = Function() As Object 'BIND2:"Function() As Object" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub ReturnIsIsVbOrBoxNarrowing1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Object) = Function() As Integer 'BIND1:"Function() As Integer" Return 2 End Function System.Console.WriteLine(x1()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Object)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWidening", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 52 (0x34) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__R0-1() As Object" IL_0019: newobj "Sub System.Func(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Func(Of Object)" IL_0024: callvirt "Function System.Func(Of Object).Invoke() As Object" IL_0029: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002e: call "Sub System.Console.WriteLine(Object)" IL_0033: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 47 (0x2f) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-0() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: box "Integer" IL_002e: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: ret } ]]>) Next End Sub <Fact()> Public Sub ReturnIsClrNarrowing() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Collections.IEnumerable) = Function() As Collections.Generic.IEnumerable(Of Integer) 'BIND1:"Function() As Collections.Generic.IEnumerable(Of Integer)" Return New Integer() {} End Function System.Console.WriteLine(x1()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Collections.IEnumerable)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWidening", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="System.Int32[]") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 47 (0x2f) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As System.Func(Of System.Collections.IEnumerable)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As System.Func(Of System.Collections.IEnumerable)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-0() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0019: newobj "Sub System.Func(Of System.Collections.IEnumerable)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As System.Func(Of System.Collections.IEnumerable)" IL_0024: callvirt "Function System.Func(Of System.Collections.IEnumerable).Invoke() As System.Collections.IEnumerable" IL_0029: call "Sub System.Console.WriteLine(Object)" IL_002e: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: newarr "Integer" IL_0006: ret } ]]>) Next End Sub <Fact()> Public Sub ReturnNoConversion() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Guid) = Function() As Integer 'BIND1:"Function() As Integer" Return 1 End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Guid)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36532: Nested function does not have the same signature as delegate 'Func(Of Guid)'. Dim x1 As Func(Of Guid) = Function() As Integer 'BIND1:"Function() As Integer" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub AllArgumentsIgnored() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer, Integer) = Function() 1 'BIND1:"Function()" Dim x2 As Func(Of Integer, Integer) = Function() As Integer 'BIND2:"Function() As Integer" Return 2 End Function System.Console.WriteLine(x1(12)) System.Console.WriteLine(x2(13)) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWideningDropReturnOrArgs", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWideningDropReturnOrArgs", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 99 (0x63) .maxstack 3 .locals init (System.Func(Of Integer, Integer) V_0) //x1 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer, Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer, Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__R0-1(Integer) As Integer" IL_0019: newobj "Sub System.Func(Of Integer, Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer, Integer)" IL_0024: stloc.0 IL_0025: ldsfld "Program._Closure$__.$IR0-2 As System.Func(Of Integer, Integer)" IL_002a: brfalse.s IL_0033 IL_002c: ldsfld "Program._Closure$__.$IR0-2 As System.Func(Of Integer, Integer)" IL_0031: br.s IL_0049 IL_0033: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0038: ldftn "Function Program._Closure$__._Lambda$__R0-2(Integer) As Integer" IL_003e: newobj "Sub System.Func(Of Integer, Integer)..ctor(Object, System.IntPtr)" IL_0043: dup IL_0044: stsfld "Program._Closure$__.$IR0-2 As System.Func(Of Integer, Integer)" IL_0049: ldloc.0 IL_004a: ldc.i4.s 12 IL_004c: callvirt "Function System.Func(Of Integer, Integer).Invoke(Integer) As Integer" IL_0051: call "Sub System.Console.WriteLine(Integer)" IL_0056: ldc.i4.s 13 IL_0058: callvirt "Function System.Func(Of Integer, Integer).Invoke(Integer) As Integer" IL_005d: call "Sub System.Console.WriteLine(Integer)" IL_0062: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 42 (0x2a) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-0() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-2", <![CDATA[ { // Code size 42 (0x2a) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-1() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: ret } ]]>) Next End Sub <Fact()> Public Sub ParameterCountMismatch() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer) = Function(y As Integer) 1 'BIND1:"Function(y As Integer)" Dim x2 As Func(Of Integer) = Function(y As Integer) As Integer 'BIND2:"Function(y As Integer) As Integer" Return 2 End Function Dim x3 As Func(Of Integer, Integer, Integer) = Function(y) 1 'BIND3:"Function(y)" Dim x4 As Func(Of Integer, Integer, Integer) = Function(y) As Integer 'BIND4:"Function(y) As Integer" Return 2 End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node3 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 3) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node3.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node3.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node4 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 4) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node4.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node4.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer)'. Dim x1 As Func(Of Integer) = Function(y As Integer) 1 'BIND1:"Function(y As Integer)" ~~~~~~~~~~~~~~~~~~~~~~~~ BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer)'. Dim x2 As Func(Of Integer) = Function(y As Integer) As Integer 'BIND2:"Function(y As Integer) As Integer" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer, Integer)'. Dim x3 As Func(Of Integer, Integer, Integer) = Function(y) 1 'BIND3:"Function(y)" ~~~~~~~~~~~~~ BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer, Integer)'. Dim x4 As Func(Of Integer, Integer, Integer) = Function(y) As Integer 'BIND4:"Function(y) As Integer" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ByRefMismatch() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer, Integer) = Function(ByRef y As Integer) 1 'BIND1:"Function(ByRef y As Integer)" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'. Dim x1 As Func(Of Integer, Integer) = Function(ByRef y As Integer) 1 'BIND1:"Function(ByRef y As Integer)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ByRefArgumentIsWidening() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Delegate Sub d1(ByRef a As String) Module Program Sub Main() Dim x1 As d1 = Sub(ByRef y As Object) 'BIND1:"Sub(ByRef y As Object)" System.Console.WriteLine(y) y = "2" End Sub Dim x2 As String = "1" x1(x2) System.Console.WriteLine(x2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("d1", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 56 (0x38) .maxstack 2 .locals init (String V_0) //x2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As d1" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As d1" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(ByRef String)" IL_0019: newobj "Sub d1..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As d1" IL_0024: ldstr "1" IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: callvirt "Sub d1.Invoke(ByRef String)" IL_0031: ldloc.0 IL_0032: call "Sub System.Console.WriteLine(String)" IL_0037: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 55 (0x37) .maxstack 2 .locals init (Object V_0) IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(ByRef Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: ldind.ref IL_0026: stloc.0 IL_0027: ldloca.s V_0 IL_0029: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(ByRef Object)" IL_002e: ldarg.1 IL_002f: ldloc.0 IL_0030: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object) As String" IL_0035: stind.ref IL_0036: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldind.ref IL_0002: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0007: call "Sub System.Console.WriteLine(Object)" IL_000c: ldarg.1 IL_000d: ldstr "2" IL_0012: stind.ref IL_0013: ret } ]]>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("d1", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If CompileAndVerify(compilation, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC41999: Implicit conversion from 'Object' to 'String' in copying the value of 'ByRef' parameter 'y' back to the matching argument. Dim x1 As d1 = Sub(ByRef y As Object) 'BIND1:"Sub(ByRef y As Object)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("d1", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32029: Option Strict On disallows narrowing from type 'Object' to type 'String' in copying the value of 'ByRef' parameter 'y' back to the matching argument. Dim x1 As d1 = Sub(ByRef y As Object) 'BIND1:"Sub(ByRef y As Object)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub NoRelaxation() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Delegate Sub d1(ByRef a As Object) Module Program Sub Main() Dim x1 As d1 = Sub(ByRef y As Object) 'BIND1:"Sub(ByRef y As Object)" System.Console.WriteLine(y) y = "2" End Sub Dim x2 As Object = "1" x1(x2) System.Console.WriteLine(x2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("d1", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 61 (0x3d) .maxstack 2 .locals init (Object V_0) //x2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As d1" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As d1" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(ByRef Object)" IL_0019: newobj "Sub d1..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As d1" IL_0024: ldstr "1" IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: callvirt "Sub d1.Invoke(ByRef Object)" IL_0031: ldloc.0 IL_0032: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0037: call "Sub System.Console.WriteLine(Object)" IL_003c: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldind.ref IL_0002: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0007: call "Sub System.Console.WriteLine(Object)" IL_000c: ldarg.1 IL_000d: ldstr "2" IL_0012: stind.ref IL_0013: ret } ]]>) Next End Sub <Fact()> Public Sub RestrictedTypes1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Delegate Sub d5(a1 As Object, a2 As ArgIterator) Class Program Sub Main() Dim x1 As d5 = Sub(y1 As Object, y2 As ArgIterator) End Sub Dim x2 As d5 = Sub(y1 As String, y2 As ArgIterator) End Sub End Sub Sub Test123(y2 As ArgIterator) Dim x1 As Action(Of Object) = Function(y1 As Object) As ArgIterator Return y2 '1 End Function '1 Dim x2 As Action(Of Object) = Function(y1 As Object) As ArgIterator End Function '2 Dim x3 As Action(Of Object) = Function(y1 As Object) Return y2 '3 End Function '3 Dim x4 As d6 = Function() Nothing End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(compilationDef, <![CDATA[ .class public auto ansi sealed d6 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object TargetObject, native int TargetMethod) runtime managed { } // end of method d6::.ctor .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(int32 x, class [mscorlib]System.AsyncCallback DelegateCallback, object DelegateAsyncState) runtime managed { } // end of method d6::BeginInvoke .method public newslot strict virtual instance valuetype [mscorlib]System.ArgIterator EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed { } // end of method d6::EndInvoke .method public newslot strict virtual instance valuetype [mscorlib]System.ArgIterator Invoke(int32 x) runtime managed { } // end of method d6::Invoke } // end of class d6 ]]>) 'Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, OptionsExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> <![CDATA[ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x2 As d5 = Sub(y1 As String, y2 As ArgIterator) ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x1 As Action(Of Object) = Function(y1 As Object) As ArgIterator ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x2 As Action(Of Object) = Function(y1 As Object) As ArgIterator ~~~~~~~~~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function '2 ~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x3 As Action(Of Object) = Function(y1 As Object) ~~~~~~~~~~~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x4 As d6 = Function() Nothing ~~~~~~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub OverloadResolution1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Test1(x As Func(Of Func(Of Object, Integer))) System.Console.WriteLine(x) End Sub Sub Test1(x As Func(Of Func(Of Integer, Integer))) System.Console.WriteLine(x) End Sub Function Test2(a As Object) As Integer Return 1 End Function Sub Main() 10: Test1(Function() Function(a As Object) 1) 20: Test1(Function() Return Function(a As Object) 1 End Function) 30: Test1(Function() Return Function(a As Object) Return 1 End Function End Function) 40: Test1(Function() Return Function(a As Object) As Integer Return 1 End Function End Function) 50: Test1(Function() As Func(Of Object, Integer) Return Function(a As Object) Return 1 End Function End Function) Test1(Function() AddressOf Test2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. 10: Test1(Function() Function(a As Object) 1) ~~~~~ BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. 20: Test1(Function() ~~~~~ BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. 30: Test1(Function() ~~~~~ BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. 40: Test1(Function() ~~~~~ BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. Test1(Function() AddressOf Test2) ~~~~~ </expected>) End Sub <Fact()> Public Sub OverloadResolution2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Test1(x As Func(Of Object, Integer)) System.Console.WriteLine(x) End Sub Sub Test1(x As Func(Of Integer, Integer)) System.Console.WriteLine(x) End Sub Sub Main() Test1(Function(x As Object) 1) Test1(Function(x As Integer) 1) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ System.Func`2[System.Object,System.Int32] System.Func`2[System.Int32,System.Int32] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub OverloadResolution3() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Test2(x As Func(Of Object, Integer)) System.Console.WriteLine(x) End Sub Sub Test2(x As Func(Of Integer, Integer)) System.Console.WriteLine(x) End Sub Sub Main() Test2(Function(x As String) 1) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30519: Overload resolution failed because no accessible 'Test2' can be called without a narrowing conversion: 'Public Sub Test2(x As Func(Of Object, Integer))': Argument matching parameter 'x' narrows to 'Func(Of Object, Integer)'. 'Public Sub Test2(x As Func(Of Integer, Integer))': Argument matching parameter 'x' narrows to 'Func(Of Integer, Integer)'. Test2(Function(x As String) 1) ~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30518: Overload resolution failed because no accessible 'Test2' can be called with these arguments: 'Public Sub Test2(x As Func(Of Object, Integer))': Option Strict On disallows implicit conversions from 'Object' to 'String'. 'Public Sub Test2(x As Func(Of Integer, Integer))': Option Strict On disallows implicit conversions from 'Integer' to 'String'. Test2(Function(x As String) 1) ~~~~~ </expected>) End Sub <Fact()> Public Sub OverloadResolution4() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Test3(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test4(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test3(x As Func(Of Integer)) System.Console.WriteLine(x) End Sub Sub Test5(x As Func(Of Integer)) System.Console.WriteLine(x) End Sub Sub Main() Test3(Function() "a") Test4(Function() "a") Test5(Function() "a") Test3(Function() Return "b" End Function) Test4(Function() Return "b" End Function) Test5(Function() Return "b" End Function) Test3(Function() As String Return "b" End Function) Test4(Function() As String Return "b" End Function) Test5(Function() As String Return "b" End Function) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42016: Implicit conversion from 'String' to 'Integer'. Test5(Function() "a") ~~~ BC42016: Implicit conversion from 'String' to 'Integer'. Return "b" ~~~ BC42016: Implicit conversion from 'String' to 'Integer'. Test5(Function() As String ~~~~~~~~~~~~~~~~~~~~~ </expected>) CompileAndVerify(compilation, <![CDATA[ System.Func`1[System.Object] System.Func`1[System.Object] System.Func`1[System.Int32] System.Func`1[System.Object] System.Func`1[System.Object] System.Func`1[System.Int32] System.Func`1[System.Object] System.Func`1[System.Object] System.Func`1[System.Int32] ]]>) End Sub <Fact()> Public Sub OverloadResolution5() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Option Strict On Imports System Module Program Sub Test6(x As Object) System.Console.WriteLine(x) End Sub Sub Test7(x As Object) System.Console.WriteLine(x) End Sub Sub Test6(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test8(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test9(x As Func(Of String)) System.Console.WriteLine(x) End Sub Sub Test10(x As Func(Of String)) System.Console.WriteLine(x) End Sub Sub Test9(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test11(x As Func(Of String)) System.Console.WriteLine(x) End Sub Sub Main() Test6(Function() "a") Test7(Function() "a") Test8(Function() "a") Test6(Function() Return "b" End Function) Test7(Function() Return "b" End Function) Test8(Function() Return "b" End Function) Test6(Function() As String Return "b" End Function) Test7(Function() As String Return "b" End Function) Test8(Function() As String Return "b" End Function) Test9(Function() "a") Test10(Function() "a") Test11(Function() "a") Test9(Function() Return "b" End Function) Test10(Function() Return "b" End Function) Test11(Function() Return "b" End Function) Test9(Function() As String Return "c" End Function) Test10(Function() As String Return "c" End Function) Test11(Function() As String Return "c" End Function) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) CompileAndVerify(compilation, <![CDATA[ System.Func`1[System.Object] VB$AnonymousDelegate_0`1[System.String] System.Func`1[System.Object] System.Func`1[System.Object] VB$AnonymousDelegate_0`1[System.String] System.Func`1[System.Object] System.Func`1[System.Object] VB$AnonymousDelegate_0`1[System.String] System.Func`1[System.Object] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] ]]>) End Sub <Fact()> Public Sub ArgumentIsVbOrBoxWidening5() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim val As Integer = 1 Dim x1 As System.Action(Of Integer) = Sub(x As Object) System.Console.WriteLine("{0}{1}",val,x) End Sub x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="12") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 30 (0x1e) .maxstack 3 IL_0000: newobj "Sub Program._Closure$__0-0..ctor()" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: stfld "Program._Closure$__0-0.$VB$Local_val As Integer" IL_000c: ldftn "Sub Program._Closure$__0-0._Lambda$__R1(Integer)" IL_0012: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_0017: ldc.i4.2 IL_0018: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_001d: ret } ]]>) verifier.VerifyIL("Program._Closure$__0-0._Lambda$__R1", <![CDATA[ { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: box "Integer" IL_0007: call "Sub Program._Closure$__0-0._Lambda$__0(Object)" IL_000c: ret } ]]>) verifier.VerifyIL("Program._Closure$__0-0._Lambda$__0", <![CDATA[ { // Code size 28 (0x1c) .maxstack 3 IL_0000: ldstr "{0}{1}" IL_0005: ldarg.0 IL_0006: ldfld "Program._Closure$__0-0.$VB$Local_val As Integer" IL_000b: box "Integer" IL_0010: ldarg.1 IL_0011: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0016: call "Sub System.Console.WriteLine(String, Object, Object)" IL_001b: ret } ]]>) End Sub <Fact()> Public Sub CustomModifiers1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Class Program Shared Sub Main() Dim d As TestCustomModifiers Dim a(-1) As Integer d = AddressOf F1 d(a) d = Function(x) System.Console.WriteLine("L1") Return x End Function d(a) d = Function(x As Integer()) As Integer() System.Console.WriteLine("L2") Return x End Function d(a) End Sub Shared Function F1(x As Integer()) As Integer() System.Console.WriteLine("F1") Return x End Function End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(compilationDef, <![CDATA[ .class public auto ansi sealed TestCustomModifiers extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object TargetObject, native int TargetMethod) runtime managed { } // end of method TestCustomModifiers::.ctor .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) [] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) x, class [mscorlib]System.AsyncCallback DelegateCallback, object DelegateAsyncState) runtime managed { } // end of method TestCustomModifiers::BeginInvoke .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) [] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed { } // end of method TestCustomModifiers::EndInvoke .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) [] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) Invoke(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) [] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) x) runtime managed { } // end of method TestCustomModifiers::Invoke } // end of class TestCustomModifiers ]]>.Value, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) CompileAndVerify(compilation, expectedOutput:="F1" & Environment.NewLine & "L1" & Environment.NewLine & "L2") End Sub <WorkItem(543647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543647")> <Fact()> Public Sub BaseMethodParamIntegerDelegateParamShort() Dim compilationDef = <compilation name="Test"> <file name="a.vb"> Imports System Delegate Function DelShort(ByVal s As Short) As String MustInherit Class BaseClass Overridable Function MethodThatIsVirtual(ByVal i As Integer) As String Return "Base Method" End Function End Class Class DerivedClass Inherits BaseClass Overrides Function MethodThatIsVirtual(ByVal i As Integer) As String Return "Derived Method" End Function Function TC2() As String Dim dS As DelShort = AddressOf MyBase.MethodThatIsVirtual Return dS(1) End Function End Class Module Program Sub Main(args As String()) Dim d = New DerivedClass() Console.WriteLine(d.TC2()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation, expectedOutput:="Base Method") End Sub <WorkItem(531532, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531532")> <Fact()> Public Sub Bug18258() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.CompilerServices Friend Module Program <Extension> Sub Bar(Of T)(x As T) Dim d As New Action(Of Action(Of T))(Sub(y) End Sub) d.Invoke(AddressOf x.Bar) End Sub Sub Main() End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, {TestMetadata.Net40.SystemCore}, TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation) End Sub <WorkItem(1096576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1096576")> <Fact()> Public Sub Bug1096576() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Imports System Class Thing Sub Goo() End Sub Public t As New Thing Public tcb As AsyncCallback = AddressOf t.Goo End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(compilationDef, options:=TestOptions.DebugDll) Dim verifier = CompileAndVerify(compilation).VerifyDiagnostics() End Sub End Class End Namespace
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class Lambda_Relaxation Inherits BasicTestBase <Fact()> Public Sub ArgumentIsVbOrBoxWidening() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Integer) = Sub(x As Object) 'BIND1:"Sub(x As Object)" System.Console.WriteLine(x) End Sub x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWidening", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Integer)" IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0024: ldc.i4.2 IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: box "Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub ArgumentIsVbOrBoxWidening2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Integer) x1 = CType(Sub(x As Object) 'BIND1:"Sub(x As Object)" System.Console.WriteLine(x) End Sub, System.Action(Of Integer)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Identity", conv.Kind.ToString()) Assert.True(conv.Exists) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Integer)" IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0024: ldc.i4.2 IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: box "Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentIsVbOrBoxWidening3() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Integer) x1 = DirectCast(Sub(x As Object) 'BIND1:"Sub(x As Object)" System.Console.WriteLine(x) End Sub, System.Action(Of Integer)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Identity", conv.Kind.ToString()) Assert.True(conv.Exists) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Integer)" IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0024: ldc.i4.2 IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: box "Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentIsVbOrBoxWidening4() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Integer) x1 = TryCast(Sub(x As Object) 'BIND1:"Sub(x As Object)" System.Console.WriteLine(x) End Sub, System.Action(Of Integer)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Identity", conv.Kind.ToString()) Assert.True(conv.Exists) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Integer)" IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0024: ldc.i4.2 IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: box "Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentIsNarrowing() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Object) = Sub(x As Integer) 'BIND1:"Sub(x As Integer)" System.Console.WriteLine(x) End Sub x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Object)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Object)" IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0024: ldc.i4.2 IL_0025: box "Integer" IL_002a: callvirt "Sub System.Action(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Integer)" IL_0006: ret } ]]>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) If True Then Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Object)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42016: Implicit conversion from 'Object' to 'Integer'. Dim x1 As System.Action(Of Object) = Sub(x As Integer) 'BIND1:"Sub(x As Integer)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) If True Then Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Object)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Dim x1 As System.Action(Of Object) = Sub(x As Integer) 'BIND1:"Sub(x As Integer)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(543114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543114")> <Fact()> Public Sub ArgumentIsNarrowing2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Object) = CType(Sub(x As Integer) System.Console.WriteLine(x) End Sub, System.Action(Of Object)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Object)" IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0024: ldc.i4.2 IL_0025: box "Integer" IL_002a: callvirt "Sub System.Action(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Integer)" IL_0006: ret } ]]>) Next End Sub <WorkItem(543114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543114")> <Fact()> Public Sub ArgumentIsNarrowing3() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Object) = DirectCast(Sub(x As Integer) System.Console.WriteLine(x) End Sub, System.Action(Of Object)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Object)" IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0024: ldc.i4.2 IL_0025: box "Integer" IL_002a: callvirt "Sub System.Action(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Integer)" IL_0006: ret } ]]>) Next End Sub <WorkItem(543114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543114")> <Fact()> Public Sub ArgumentIsNarrowing4() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Object) = TryCast(Sub(x As Integer) System.Console.WriteLine(x) End Sub, System.Action(Of Object)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Object)" IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0024: ldc.i4.2 IL_0025: box "Integer" IL_002a: callvirt "Sub System.Action(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Integer)" IL_0006: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentIsClrWidening() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action(Of System.Collections.Generic.IEnumerable(Of Integer)) = Sub(x As System.Collections.IEnumerable) 'BIND1:"Sub(x As System.Collections.IEnumerable)" System.Console.WriteLine(x) End Sub x1(New Integer() {}) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Collections.Generic.IEnumerable(Of System.Int32))", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWidening", conv.Kind.ToString()) Assert.True(conv.Exists) Dim verifier = CompileAndVerify(compilation, expectedOutput:="System.Int32[]") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As System.Action(Of System.Collections.Generic.IEnumerable(Of Integer))" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As System.Action(Of System.Collections.Generic.IEnumerable(Of Integer))" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(System.Collections.IEnumerable)" IL_0019: newobj "Sub System.Action(Of System.Collections.Generic.IEnumerable(Of Integer))..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As System.Action(Of System.Collections.Generic.IEnumerable(Of Integer))" IL_0024: ldc.i4.0 IL_0025: newarr "Integer" IL_002a: callvirt "Sub System.Action(Of System.Collections.Generic.IEnumerable(Of Integer)).Invoke(System.Collections.Generic.IEnumerable(Of Integer))" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Object)" IL_0006: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentConversionError() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action(Of Integer) = Sub(x As System.Guid) 'BIND1:"Sub(x As System.Guid)" End Sub End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of Integer)'. Dim x1 As Action(Of Integer) = Sub(x As System.Guid) 'BIND1:"Sub(x As System.Guid)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ArgumentConversionError2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action(Of Integer) = ((Sub(x As System.Guid) 'BIND1:"Sub(x As System.Guid)" End Sub)) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of Integer)'. Dim x1 As Action(Of Integer) = ((Sub(x As System.Guid) 'BIND1:"Sub(x As System.Guid)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ReturnValueIsDropped1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action = Function() 1 'BIND1:"Function()" Dim x2 As Action = Function() 'BIND2:"Function()" System.Console.WriteLine("x2") Return 2 End Function x1() x2() End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWideningDropReturnOrArgs", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWideningDropReturnOrArgs", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="x2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 85 (0x55) .maxstack 2 .locals init (System.Action V_0) //x1 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1()" IL_0019: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action" IL_0024: stloc.0 IL_0025: ldsfld "Program._Closure$__.$IR0-2 As System.Action" IL_002a: brfalse.s IL_0033 IL_002c: ldsfld "Program._Closure$__.$IR0-2 As System.Action" IL_0031: br.s IL_0049 IL_0033: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0038: ldftn "Sub Program._Closure$__._Lambda$__R0-2()" IL_003e: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_0043: dup IL_0044: stsfld "Program._Closure$__.$IR0-2 As System.Action" IL_0049: ldloc.0 IL_004a: callvirt "Sub System.Action.Invoke()" IL_004f: callvirt "Sub System.Action.Invoke()" IL_0054: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-0() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: pop IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-2", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-1() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: pop IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldstr "x2" IL_0005: call "Sub System.Console.WriteLine(String)" IL_000a: ldc.i4.2 IL_000b: ret } ]]>) Next End Sub <Fact()> Public Sub ReturnValueIsDropped2_ReturnTypeInferenceError() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action = Function() AddressOf Main 'BIND1:"Function()" Dim x2 As Action = Function() 'BIND2:"Function()" Return AddressOf Main End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30581: 'AddressOf' expression cannot be converted to 'Object' because 'Object' is not a delegate type. Dim x1 As Action = Function() AddressOf Main 'BIND1:"Function()" ~~~~~~~~~~~~~~ BC36751: Cannot infer a return type. Consider adding an 'As' clause to specify the return type. Dim x2 As Action = Function() 'BIND2:"Function()" ~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub SubToFunction() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer) = Sub() 'BIND1:"Sub()" End Sub End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36670: Nested sub does not have a signature that is compatible with delegate 'Func(Of Integer)'. Dim x1 As Func(Of Integer) = Sub() 'BIND1:"Sub()" ~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ReturnIsWidening() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer) = Function() CObj(1) 'BIND1:"Function()" Dim x2 As Func(Of Integer) = Function() As Object 'BIND2:"Function() As Object" Return 2 End Function System.Console.WriteLine(x1()) System.Console.WriteLine(x2()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 95 (0x5f) .maxstack 2 .locals init (System.Func(Of Integer) V_0) //x1 IL_0000: ldsfld "Program._Closure$__.$I0-0 As System.Func(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As System.Func(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-0() As Integer" IL_0019: newobj "Sub System.Func(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As System.Func(Of Integer)" IL_0024: stloc.0 IL_0025: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer)" IL_002a: brfalse.s IL_0033 IL_002c: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer)" IL_0031: br.s IL_0049 IL_0033: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0038: ldftn "Function Program._Closure$__._Lambda$__R0-1() As Integer" IL_003e: newobj "Sub System.Func(Of Integer)..ctor(Object, System.IntPtr)" IL_0043: dup IL_0044: stsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer)" IL_0049: ldloc.0 IL_004a: callvirt "Function System.Func(Of Integer).Invoke() As Integer" IL_004f: call "Sub System.Console.WriteLine(Integer)" IL_0054: callvirt "Function System.Func(Of Integer).Invoke() As Integer" IL_0059: call "Sub System.Console.WriteLine(Integer)" IL_005e: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: box "Integer" IL_0006: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_000b: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 47 (0x2f) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-1() As Object" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Object).Invoke() As Object" IL_0029: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002e: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: ret } ]]>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If End If CompileAndVerify(compilation, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42016: Implicit conversion from 'Object' to 'Integer'. Dim x1 As Func(Of Integer) = Function() CObj(1) 'BIND1:"Function()" ~~~~~~~ BC42016: Implicit conversion from 'Object' to 'Integer'. Dim x2 As Func(Of Integer) = Function() As Object 'BIND2:"Function() As Object" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Dim x1 As Func(Of Integer) = Function() CObj(1) 'BIND1:"Function()" ~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Dim x2 As Func(Of Integer) = Function() As Object 'BIND2:"Function() As Object" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub ReturnIsIsVbOrBoxNarrowing1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Object) = Function() As Integer 'BIND1:"Function() As Integer" Return 2 End Function System.Console.WriteLine(x1()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Object)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWidening", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 52 (0x34) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__R0-1() As Object" IL_0019: newobj "Sub System.Func(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Func(Of Object)" IL_0024: callvirt "Function System.Func(Of Object).Invoke() As Object" IL_0029: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002e: call "Sub System.Console.WriteLine(Object)" IL_0033: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 47 (0x2f) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-0() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: box "Integer" IL_002e: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: ret } ]]>) Next End Sub <Fact()> Public Sub ReturnIsClrNarrowing() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Collections.IEnumerable) = Function() As Collections.Generic.IEnumerable(Of Integer) 'BIND1:"Function() As Collections.Generic.IEnumerable(Of Integer)" Return New Integer() {} End Function System.Console.WriteLine(x1()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Collections.IEnumerable)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWidening", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="System.Int32[]") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 47 (0x2f) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As System.Func(Of System.Collections.IEnumerable)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As System.Func(Of System.Collections.IEnumerable)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-0() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0019: newobj "Sub System.Func(Of System.Collections.IEnumerable)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As System.Func(Of System.Collections.IEnumerable)" IL_0024: callvirt "Function System.Func(Of System.Collections.IEnumerable).Invoke() As System.Collections.IEnumerable" IL_0029: call "Sub System.Console.WriteLine(Object)" IL_002e: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: newarr "Integer" IL_0006: ret } ]]>) Next End Sub <Fact()> Public Sub ReturnNoConversion() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Guid) = Function() As Integer 'BIND1:"Function() As Integer" Return 1 End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Guid)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36532: Nested function does not have the same signature as delegate 'Func(Of Guid)'. Dim x1 As Func(Of Guid) = Function() As Integer 'BIND1:"Function() As Integer" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub AllArgumentsIgnored() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer, Integer) = Function() 1 'BIND1:"Function()" Dim x2 As Func(Of Integer, Integer) = Function() As Integer 'BIND2:"Function() As Integer" Return 2 End Function System.Console.WriteLine(x1(12)) System.Console.WriteLine(x2(13)) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWideningDropReturnOrArgs", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWideningDropReturnOrArgs", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 99 (0x63) .maxstack 3 .locals init (System.Func(Of Integer, Integer) V_0) //x1 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer, Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer, Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__R0-1(Integer) As Integer" IL_0019: newobj "Sub System.Func(Of Integer, Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer, Integer)" IL_0024: stloc.0 IL_0025: ldsfld "Program._Closure$__.$IR0-2 As System.Func(Of Integer, Integer)" IL_002a: brfalse.s IL_0033 IL_002c: ldsfld "Program._Closure$__.$IR0-2 As System.Func(Of Integer, Integer)" IL_0031: br.s IL_0049 IL_0033: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0038: ldftn "Function Program._Closure$__._Lambda$__R0-2(Integer) As Integer" IL_003e: newobj "Sub System.Func(Of Integer, Integer)..ctor(Object, System.IntPtr)" IL_0043: dup IL_0044: stsfld "Program._Closure$__.$IR0-2 As System.Func(Of Integer, Integer)" IL_0049: ldloc.0 IL_004a: ldc.i4.s 12 IL_004c: callvirt "Function System.Func(Of Integer, Integer).Invoke(Integer) As Integer" IL_0051: call "Sub System.Console.WriteLine(Integer)" IL_0056: ldc.i4.s 13 IL_0058: callvirt "Function System.Func(Of Integer, Integer).Invoke(Integer) As Integer" IL_005d: call "Sub System.Console.WriteLine(Integer)" IL_0062: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 42 (0x2a) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-0() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-2", <![CDATA[ { // Code size 42 (0x2a) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-1() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: ret } ]]>) Next End Sub <Fact()> Public Sub ParameterCountMismatch() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer) = Function(y As Integer) 1 'BIND1:"Function(y As Integer)" Dim x2 As Func(Of Integer) = Function(y As Integer) As Integer 'BIND2:"Function(y As Integer) As Integer" Return 2 End Function Dim x3 As Func(Of Integer, Integer, Integer) = Function(y) 1 'BIND3:"Function(y)" Dim x4 As Func(Of Integer, Integer, Integer) = Function(y) As Integer 'BIND4:"Function(y) As Integer" Return 2 End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node3 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 3) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node3.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node3.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node4 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 4) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node4.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node4.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer)'. Dim x1 As Func(Of Integer) = Function(y As Integer) 1 'BIND1:"Function(y As Integer)" ~~~~~~~~~~~~~~~~~~~~~~~~ BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer)'. Dim x2 As Func(Of Integer) = Function(y As Integer) As Integer 'BIND2:"Function(y As Integer) As Integer" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer, Integer)'. Dim x3 As Func(Of Integer, Integer, Integer) = Function(y) 1 'BIND3:"Function(y)" ~~~~~~~~~~~~~ BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer, Integer)'. Dim x4 As Func(Of Integer, Integer, Integer) = Function(y) As Integer 'BIND4:"Function(y) As Integer" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ByRefMismatch() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer, Integer) = Function(ByRef y As Integer) 1 'BIND1:"Function(ByRef y As Integer)" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'. Dim x1 As Func(Of Integer, Integer) = Function(ByRef y As Integer) 1 'BIND1:"Function(ByRef y As Integer)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ByRefArgumentIsWidening() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Delegate Sub d1(ByRef a As String) Module Program Sub Main() Dim x1 As d1 = Sub(ByRef y As Object) 'BIND1:"Sub(ByRef y As Object)" System.Console.WriteLine(y) y = "2" End Sub Dim x2 As String = "1" x1(x2) System.Console.WriteLine(x2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("d1", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 56 (0x38) .maxstack 2 .locals init (String V_0) //x2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As d1" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As d1" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(ByRef String)" IL_0019: newobj "Sub d1..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As d1" IL_0024: ldstr "1" IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: callvirt "Sub d1.Invoke(ByRef String)" IL_0031: ldloc.0 IL_0032: call "Sub System.Console.WriteLine(String)" IL_0037: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 55 (0x37) .maxstack 2 .locals init (Object V_0) IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(ByRef Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldarg.1 IL_0025: ldind.ref IL_0026: stloc.0 IL_0027: ldloca.s V_0 IL_0029: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(ByRef Object)" IL_002e: ldarg.1 IL_002f: ldloc.0 IL_0030: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object) As String" IL_0035: stind.ref IL_0036: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldind.ref IL_0002: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0007: call "Sub System.Console.WriteLine(Object)" IL_000c: ldarg.1 IL_000d: ldstr "2" IL_0012: stind.ref IL_0013: ret } ]]>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("d1", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If CompileAndVerify(compilation, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC41999: Implicit conversion from 'Object' to 'String' in copying the value of 'ByRef' parameter 'y' back to the matching argument. Dim x1 As d1 = Sub(ByRef y As Object) 'BIND1:"Sub(ByRef y As Object)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("d1", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32029: Option Strict On disallows narrowing from type 'Object' to type 'String' in copying the value of 'ByRef' parameter 'y' back to the matching argument. Dim x1 As d1 = Sub(ByRef y As Object) 'BIND1:"Sub(ByRef y As Object)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub NoRelaxation() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Delegate Sub d1(ByRef a As Object) Module Program Sub Main() Dim x1 As d1 = Sub(ByRef y As Object) 'BIND1:"Sub(ByRef y As Object)" System.Console.WriteLine(y) y = "2" End Sub Dim x2 As Object = "1" x1(x2) System.Console.WriteLine(x2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("d1", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 61 (0x3d) .maxstack 2 .locals init (Object V_0) //x2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As d1" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As d1" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(ByRef Object)" IL_0019: newobj "Sub d1..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As d1" IL_0024: ldstr "1" IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: callvirt "Sub d1.Invoke(ByRef Object)" IL_0031: ldloc.0 IL_0032: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0037: call "Sub System.Console.WriteLine(Object)" IL_003c: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-0", <![CDATA[ { // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldind.ref IL_0002: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0007: call "Sub System.Console.WriteLine(Object)" IL_000c: ldarg.1 IL_000d: ldstr "2" IL_0012: stind.ref IL_0013: ret } ]]>) Next End Sub <Fact()> Public Sub RestrictedTypes1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Delegate Sub d5(a1 As Object, a2 As ArgIterator) Class Program Sub Main() Dim x1 As d5 = Sub(y1 As Object, y2 As ArgIterator) End Sub Dim x2 As d5 = Sub(y1 As String, y2 As ArgIterator) End Sub End Sub Sub Test123(y2 As ArgIterator) Dim x1 As Action(Of Object) = Function(y1 As Object) As ArgIterator Return y2 '1 End Function '1 Dim x2 As Action(Of Object) = Function(y1 As Object) As ArgIterator End Function '2 Dim x3 As Action(Of Object) = Function(y1 As Object) Return y2 '3 End Function '3 Dim x4 As d6 = Function() Nothing End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(compilationDef, <![CDATA[ .class public auto ansi sealed d6 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object TargetObject, native int TargetMethod) runtime managed { } // end of method d6::.ctor .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(int32 x, class [mscorlib]System.AsyncCallback DelegateCallback, object DelegateAsyncState) runtime managed { } // end of method d6::BeginInvoke .method public newslot strict virtual instance valuetype [mscorlib]System.ArgIterator EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed { } // end of method d6::EndInvoke .method public newslot strict virtual instance valuetype [mscorlib]System.ArgIterator Invoke(int32 x) runtime managed { } // end of method d6::Invoke } // end of class d6 ]]>) 'Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, OptionsExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> <![CDATA[ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x2 As d5 = Sub(y1 As String, y2 As ArgIterator) ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x1 As Action(Of Object) = Function(y1 As Object) As ArgIterator ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x2 As Action(Of Object) = Function(y1 As Object) As ArgIterator ~~~~~~~~~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function '2 ~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x3 As Action(Of Object) = Function(y1 As Object) ~~~~~~~~~~~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x4 As d6 = Function() Nothing ~~~~~~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub OverloadResolution1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Test1(x As Func(Of Func(Of Object, Integer))) System.Console.WriteLine(x) End Sub Sub Test1(x As Func(Of Func(Of Integer, Integer))) System.Console.WriteLine(x) End Sub Function Test2(a As Object) As Integer Return 1 End Function Sub Main() 10: Test1(Function() Function(a As Object) 1) 20: Test1(Function() Return Function(a As Object) 1 End Function) 30: Test1(Function() Return Function(a As Object) Return 1 End Function End Function) 40: Test1(Function() Return Function(a As Object) As Integer Return 1 End Function End Function) 50: Test1(Function() As Func(Of Object, Integer) Return Function(a As Object) Return 1 End Function End Function) Test1(Function() AddressOf Test2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. 10: Test1(Function() Function(a As Object) 1) ~~~~~ BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. 20: Test1(Function() ~~~~~ BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. 30: Test1(Function() ~~~~~ BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. 40: Test1(Function() ~~~~~ BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. Test1(Function() AddressOf Test2) ~~~~~ </expected>) End Sub <Fact()> Public Sub OverloadResolution2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Test1(x As Func(Of Object, Integer)) System.Console.WriteLine(x) End Sub Sub Test1(x As Func(Of Integer, Integer)) System.Console.WriteLine(x) End Sub Sub Main() Test1(Function(x As Object) 1) Test1(Function(x As Integer) 1) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ System.Func`2[System.Object,System.Int32] System.Func`2[System.Int32,System.Int32] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub OverloadResolution3() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Test2(x As Func(Of Object, Integer)) System.Console.WriteLine(x) End Sub Sub Test2(x As Func(Of Integer, Integer)) System.Console.WriteLine(x) End Sub Sub Main() Test2(Function(x As String) 1) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30519: Overload resolution failed because no accessible 'Test2' can be called without a narrowing conversion: 'Public Sub Test2(x As Func(Of Object, Integer))': Argument matching parameter 'x' narrows to 'Func(Of Object, Integer)'. 'Public Sub Test2(x As Func(Of Integer, Integer))': Argument matching parameter 'x' narrows to 'Func(Of Integer, Integer)'. Test2(Function(x As String) 1) ~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30518: Overload resolution failed because no accessible 'Test2' can be called with these arguments: 'Public Sub Test2(x As Func(Of Object, Integer))': Option Strict On disallows implicit conversions from 'Object' to 'String'. 'Public Sub Test2(x As Func(Of Integer, Integer))': Option Strict On disallows implicit conversions from 'Integer' to 'String'. Test2(Function(x As String) 1) ~~~~~ </expected>) End Sub <Fact()> Public Sub OverloadResolution4() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Test3(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test4(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test3(x As Func(Of Integer)) System.Console.WriteLine(x) End Sub Sub Test5(x As Func(Of Integer)) System.Console.WriteLine(x) End Sub Sub Main() Test3(Function() "a") Test4(Function() "a") Test5(Function() "a") Test3(Function() Return "b" End Function) Test4(Function() Return "b" End Function) Test5(Function() Return "b" End Function) Test3(Function() As String Return "b" End Function) Test4(Function() As String Return "b" End Function) Test5(Function() As String Return "b" End Function) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42016: Implicit conversion from 'String' to 'Integer'. Test5(Function() "a") ~~~ BC42016: Implicit conversion from 'String' to 'Integer'. Return "b" ~~~ BC42016: Implicit conversion from 'String' to 'Integer'. Test5(Function() As String ~~~~~~~~~~~~~~~~~~~~~ </expected>) CompileAndVerify(compilation, <![CDATA[ System.Func`1[System.Object] System.Func`1[System.Object] System.Func`1[System.Int32] System.Func`1[System.Object] System.Func`1[System.Object] System.Func`1[System.Int32] System.Func`1[System.Object] System.Func`1[System.Object] System.Func`1[System.Int32] ]]>) End Sub <Fact()> Public Sub OverloadResolution5() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Option Strict On Imports System Module Program Sub Test6(x As Object) System.Console.WriteLine(x) End Sub Sub Test7(x As Object) System.Console.WriteLine(x) End Sub Sub Test6(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test8(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test9(x As Func(Of String)) System.Console.WriteLine(x) End Sub Sub Test10(x As Func(Of String)) System.Console.WriteLine(x) End Sub Sub Test9(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test11(x As Func(Of String)) System.Console.WriteLine(x) End Sub Sub Main() Test6(Function() "a") Test7(Function() "a") Test8(Function() "a") Test6(Function() Return "b" End Function) Test7(Function() Return "b" End Function) Test8(Function() Return "b" End Function) Test6(Function() As String Return "b" End Function) Test7(Function() As String Return "b" End Function) Test8(Function() As String Return "b" End Function) Test9(Function() "a") Test10(Function() "a") Test11(Function() "a") Test9(Function() Return "b" End Function) Test10(Function() Return "b" End Function) Test11(Function() Return "b" End Function) Test9(Function() As String Return "c" End Function) Test10(Function() As String Return "c" End Function) Test11(Function() As String Return "c" End Function) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) CompileAndVerify(compilation, <![CDATA[ System.Func`1[System.Object] VB$AnonymousDelegate_0`1[System.String] System.Func`1[System.Object] System.Func`1[System.Object] VB$AnonymousDelegate_0`1[System.String] System.Func`1[System.Object] System.Func`1[System.Object] VB$AnonymousDelegate_0`1[System.String] System.Func`1[System.Object] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] ]]>) End Sub <Fact()> Public Sub ArgumentIsVbOrBoxWidening5() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim val As Integer = 1 Dim x1 As System.Action(Of Integer) = Sub(x As Object) System.Console.WriteLine("{0}{1}",val,x) End Sub x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="12") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 30 (0x1e) .maxstack 3 IL_0000: newobj "Sub Program._Closure$__0-0..ctor()" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: stfld "Program._Closure$__0-0.$VB$Local_val As Integer" IL_000c: ldftn "Sub Program._Closure$__0-0._Lambda$__R1(Integer)" IL_0012: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_0017: ldc.i4.2 IL_0018: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_001d: ret } ]]>) verifier.VerifyIL("Program._Closure$__0-0._Lambda$__R1", <![CDATA[ { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: box "Integer" IL_0007: call "Sub Program._Closure$__0-0._Lambda$__0(Object)" IL_000c: ret } ]]>) verifier.VerifyIL("Program._Closure$__0-0._Lambda$__0", <![CDATA[ { // Code size 28 (0x1c) .maxstack 3 IL_0000: ldstr "{0}{1}" IL_0005: ldarg.0 IL_0006: ldfld "Program._Closure$__0-0.$VB$Local_val As Integer" IL_000b: box "Integer" IL_0010: ldarg.1 IL_0011: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0016: call "Sub System.Console.WriteLine(String, Object, Object)" IL_001b: ret } ]]>) End Sub <Fact()> Public Sub CustomModifiers1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Class Program Shared Sub Main() Dim d As TestCustomModifiers Dim a(-1) As Integer d = AddressOf F1 d(a) d = Function(x) System.Console.WriteLine("L1") Return x End Function d(a) d = Function(x As Integer()) As Integer() System.Console.WriteLine("L2") Return x End Function d(a) End Sub Shared Function F1(x As Integer()) As Integer() System.Console.WriteLine("F1") Return x End Function End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(compilationDef, <![CDATA[ .class public auto ansi sealed TestCustomModifiers extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object TargetObject, native int TargetMethod) runtime managed { } // end of method TestCustomModifiers::.ctor .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) [] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) x, class [mscorlib]System.AsyncCallback DelegateCallback, object DelegateAsyncState) runtime managed { } // end of method TestCustomModifiers::BeginInvoke .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) [] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed { } // end of method TestCustomModifiers::EndInvoke .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) [] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) Invoke(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) [] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) x) runtime managed { } // end of method TestCustomModifiers::Invoke } // end of class TestCustomModifiers ]]>.Value, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) CompileAndVerify(compilation, expectedOutput:="F1" & Environment.NewLine & "L1" & Environment.NewLine & "L2") End Sub <WorkItem(543647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543647")> <Fact()> Public Sub BaseMethodParamIntegerDelegateParamShort() Dim compilationDef = <compilation name="Test"> <file name="a.vb"> Imports System Delegate Function DelShort(ByVal s As Short) As String MustInherit Class BaseClass Overridable Function MethodThatIsVirtual(ByVal i As Integer) As String Return "Base Method" End Function End Class Class DerivedClass Inherits BaseClass Overrides Function MethodThatIsVirtual(ByVal i As Integer) As String Return "Derived Method" End Function Function TC2() As String Dim dS As DelShort = AddressOf MyBase.MethodThatIsVirtual Return dS(1) End Function End Class Module Program Sub Main(args As String()) Dim d = New DerivedClass() Console.WriteLine(d.TC2()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation, expectedOutput:="Base Method") End Sub <WorkItem(531532, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531532")> <Fact()> Public Sub Bug18258() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.CompilerServices Friend Module Program <Extension> Sub Bar(Of T)(x As T) Dim d As New Action(Of Action(Of T))(Sub(y) End Sub) d.Invoke(AddressOf x.Bar) End Sub Sub Main() End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, {TestMetadata.Net40.SystemCore}, TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation) End Sub <WorkItem(1096576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1096576")> <Fact()> Public Sub Bug1096576() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Imports System Class Thing Sub Goo() End Sub Public t As New Thing Public tcb As AsyncCallback = AddressOf t.Goo End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(compilationDef, options:=TestOptions.DebugDll) Dim verifier = CompileAndVerify(compilation).VerifyDiagnostics() End Sub End Class End Namespace
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Semantic/SourceGeneration/StateTableTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class StateTableTests { [Fact] public void Node_Table_Entries_Can_Be_Enumerated() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); builder.AddEntries(ImmutableArray.Create(2), EntryState.Added); builder.AddEntries(ImmutableArray.Create(3), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Table_Entries_Are_Flattened_When_Enumerated() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Added); builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added), (5, EntryState.Added), (6, EntryState.Added), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Table_Entries_Can_Be_The_Same_Object() { var o = new object(); var builder = NodeStateTable<object>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(o, o, o), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((o, EntryState.Added), (o, EntryState.Added), (o, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Table_Entries_Can_Be_Null() { object? o = new object(); var builder = NodeStateTable<object?>.Empty.ToBuilder(); builder.AddEntry(o, EntryState.Added); builder.AddEntry(null, EntryState.Added); builder.AddEntry(o, EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((o, EntryState.Added), (null, EntryState.Added), (o, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Builder_Can_Add_Entries_From_Previous_Table() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); builder.AddEntries(ImmutableArray.Create(2, 3), EntryState.Cached); builder.AddEntries(ImmutableArray.Create(4, 5), EntryState.Modified); builder.AddEntries(ImmutableArray.Create(6), EntryState.Added); var previousTable = builder.ToImmutableAndFree(); builder = previousTable.ToBuilder(); builder.AddEntries(ImmutableArray.Create(10, 11), EntryState.Added); builder.TryUseCachedEntries(); // ((2, EntryState.Cached), (3, EntryState.Cached)) builder.AddEntries(ImmutableArray.Create(20, 21, 22), EntryState.Modified); builder.RemoveEntries(); //((6, EntryState.Removed))); var newTable = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((10, EntryState.Added), (11, EntryState.Added), (2, EntryState.Cached), (3, EntryState.Cached), (20, EntryState.Modified), (21, EntryState.Modified), (22, EntryState.Modified), (6, EntryState.Removed)); AssertTableEntries(newTable, expected); } [Fact] public void Node_Table_Entries_Are_Cached_Or_Dropped_When_Cached() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Removed); builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Removed), (5, EntryState.Removed), (6, EntryState.Removed), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added)); AssertTableEntries(table, expected); var compactedTable = table.AsCached(); expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (7, EntryState.Cached), (8, EntryState.Cached), (9, EntryState.Cached)); AssertTableEntries(compactedTable, expected); } [Fact] public void Node_Table_AsCached_Occurs_Only_Once() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Removed); builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Removed), (5, EntryState.Removed), (6, EntryState.Removed), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added)); AssertTableEntries(table, expected); var compactedTable = table.AsCached(); expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (7, EntryState.Cached), (8, EntryState.Cached), (9, EntryState.Cached)); AssertTableEntries(compactedTable, expected); // calling as cached a second time just returns the same instance var compactedTable2 = compactedTable.AsCached(); Assert.Same(compactedTable, compactedTable2); } [Fact] public void Node_Table_Single_Returns_First_Item() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); var table = builder.ToImmutableAndFree(); Assert.Equal(1, table.Single()); } [Fact] public void Node_Table_Single_Returns_Second_Item_When_First_Is_Removed() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); var table = builder.ToImmutableAndFree(); AssertTableEntries(table, new[] { (1, EntryState.Added) }); // remove the first item and replace it in the table builder = table.ToBuilder(); builder.RemoveEntries(); builder.AddEntries(ImmutableArray.Create(2), EntryState.Added); table = builder.ToImmutableAndFree(); AssertTableEntries(table, new[] { (1, EntryState.Removed), (2, EntryState.Added) }); Assert.Equal(2, table.Single()); } [Fact] public void Node_Builder_Handles_Modification_When_Both_Tables_Have_Empty_Entries() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2), EntryState.Added); builder.AddEntries(ImmutableArray<int>.Empty, EntryState.Added); builder.AddEntries(ImmutableArray.Create(3, 4), EntryState.Added); var previousTable = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added)); AssertTableEntries(previousTable, expected); builder = previousTable.ToBuilder(); Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 2), EqualityComparer<int>.Default)); // ((3, EntryState.Modified), (2, EntryState.Cached)) Assert.True(builder.TryModifyEntries(ImmutableArray<int>.Empty, EqualityComparer<int>.Default)); // nothing Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 5), EqualityComparer<int>.Default)); // ((3, EntryState.Cached), (5, EntryState.Modified)) var newTable = builder.ToImmutableAndFree(); expected = ImmutableArray.Create((3, EntryState.Modified), (2, EntryState.Cached), (3, EntryState.Cached), (5, EntryState.Modified)); AssertTableEntries(newTable, expected); } [Fact] public void Node_Table_Doesnt_Modify_Single_Item_Multiple_Times_When_Same() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); builder.AddEntries(ImmutableArray.Create(2), EntryState.Added); builder.AddEntries(ImmutableArray.Create(3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4), EntryState.Added); var previousTable = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added)); AssertTableEntries(previousTable, expected); builder = previousTable.ToBuilder(); Assert.True(builder.TryModifyEntry(1, EqualityComparer<int>.Default)); // ((1, EntryState.Cached)) Assert.True(builder.TryModifyEntry(2, EqualityComparer<int>.Default)); // ((2, EntryState.Cached)) Assert.True(builder.TryModifyEntry(5, EqualityComparer<int>.Default)); // ((5, EntryState.Modified)) Assert.True(builder.TryModifyEntry(4, EqualityComparer<int>.Default)); // ((4, EntryState.Cached)) var newTable = builder.ToImmutableAndFree(); expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (5, EntryState.Modified), (4, EntryState.Cached)); AssertTableEntries(newTable, expected); } [Fact] public void Driver_Table_Calls_Into_Node_With_Self() { DriverStateTable.Builder? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = b; return s; }); DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(builder, passedIn); } [Fact] public void Driver_Table_Calls_Into_Node_With_EmptyState_FirstTime() { NodeStateTable<int>? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = s; return s; }); DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(NodeStateTable<int>.Empty, passedIn); } [Fact] public void Driver_Table_Calls_Into_Node_With_PreviousTable() { var nodeBuilder = NodeStateTable<int>.Empty.ToBuilder(); nodeBuilder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Cached); var newTable = nodeBuilder.ToImmutableAndFree(); NodeStateTable<int>? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = s; return newTable; }); // empty first time DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(NodeStateTable<int>.Empty, passedIn); // gives the returned table the second time around DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable()); builder2.GetLatestStateTableForNode(callbackNode); Assert.NotNull(passedIn); AssertTableEntries(passedIn!, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached) }); } [Fact] public void Driver_Table_Compacts_State_Tables_When_Made_Immutable() { var nodeBuilder = NodeStateTable<int>.Empty.ToBuilder(); nodeBuilder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); nodeBuilder.AddEntries(ImmutableArray.Create(4), EntryState.Removed); nodeBuilder.AddEntries(ImmutableArray.Create(5, 6), EntryState.Modified); var newTable = nodeBuilder.ToImmutableAndFree(); NodeStateTable<int>? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = s; return newTable; }); // empty first time DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(NodeStateTable<int>.Empty, passedIn); // gives the returned table the second time around DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable()); builder2.GetLatestStateTableForNode(callbackNode); // table returned from the first instance was compacted by the builder Assert.NotNull(passedIn); AssertTableEntries(passedIn!, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (5, EntryState.Cached), (6, EntryState.Cached) }); } [Fact] public void Driver_Table_Builder_Doesnt_Build_Twice() { int callCount = 0; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { callCount++; return s; }); // multiple gets will only call it once DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); builder.GetLatestStateTableForNode(callbackNode); builder.GetLatestStateTableForNode(callbackNode); Assert.Equal(1, callCount); // second time around we'll call it once, but no more DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable()); builder2.GetLatestStateTableForNode(callbackNode); builder2.GetLatestStateTableForNode(callbackNode); builder2.GetLatestStateTableForNode(callbackNode); Assert.Equal(2, callCount); } [Fact] public void Batch_Node_Is_Cached_If_All_Inputs_Are_Cached() { var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, 3)); BatchNode<int> batchNode = new BatchNode<int>(inputNode); // first time through will always be added (because it's not been run before) DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty); _ = dstBuilder.GetLatestStateTableForNode(batchNode); // second time through should show as cached dstBuilder = GetBuilder(dstBuilder.ToImmutable()); var table = dstBuilder.GetLatestStateTableForNode(batchNode); AssertTableEntries(table, new[] { (ImmutableArray.Create(1, 2, 3), EntryState.Cached) }); } [Fact] public void Batch_Node_Is_Not_Cached_When_Inputs_Are_Changed() { int third = 3; var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, third++)); BatchNode<int> batchNode = new BatchNode<int>(inputNode); // first time through will always be added (because it's not been run before) DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty); _ = dstBuilder.GetLatestStateTableForNode(batchNode); // second time through should show as modified dstBuilder = GetBuilder(dstBuilder.ToImmutable()); var table = dstBuilder.GetLatestStateTableForNode(batchNode); AssertTableEntries(table, new[] { (ImmutableArray.Create(1, 2, 4), EntryState.Modified) }); } [Fact] public void User_Comparer_Is_Not_Used_To_Determine_Inputs() { var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, 3)) .WithComparer(new LambdaComparer<int>((a, b) => false)); // first time through will always be added (because it's not been run before) DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty); _ = dstBuilder.GetLatestStateTableForNode(inputNode); // second time through should show as cached, even though we supplied a comparer (comparer should only used to turn modified => cached) dstBuilder = GetBuilder(dstBuilder.ToImmutable()); var table = dstBuilder.GetLatestStateTableForNode(inputNode); AssertTableEntries(table, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached) }); } private void AssertTableEntries<T>(NodeStateTable<T> table, IList<(T item, EntryState state)> expected) { int index = 0; foreach (var entry in table) { Assert.Equal(expected[index].item, entry.item); Assert.Equal(expected[index].state, entry.state); index++; } } private void AssertTableEntries<T>(NodeStateTable<ImmutableArray<T>> table, IList<(ImmutableArray<T> item, EntryState state)> expected) { int index = 0; foreach (var entry in table) { AssertEx.Equal(expected[index].item, entry.item); Assert.Equal(expected[index].state, entry.state); index++; } } private DriverStateTable.Builder GetBuilder(DriverStateTable previous) { var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10); var c = CSharpCompilation.Create("empty"); var state = new GeneratorDriverState(options, CompilerAnalyzerConfigOptionsProvider.Empty, ImmutableArray<ISourceGenerator>.Empty, ImmutableArray<IIncrementalGenerator>.Empty, ImmutableArray<AdditionalText>.Empty, ImmutableArray<GeneratorState>.Empty, previous, disabledOutputs: IncrementalGeneratorOutputKind.None); return new DriverStateTable.Builder(c, state, ImmutableArray<ISyntaxInputNode>.Empty); } private class CallbackNode<T> : IIncrementalGeneratorNode<T> { private readonly Func<DriverStateTable.Builder, NodeStateTable<T>, NodeStateTable<T>> _callback; public CallbackNode(Func<DriverStateTable.Builder, NodeStateTable<T>, NodeStateTable<T>> callback) { _callback = callback; } public NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken) { return _callback(graphState, previousTable); } public IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer) => this; public void RegisterOutput(IIncrementalGeneratorOutputNode output) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class StateTableTests { [Fact] public void Node_Table_Entries_Can_Be_Enumerated() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); builder.AddEntries(ImmutableArray.Create(2), EntryState.Added); builder.AddEntries(ImmutableArray.Create(3), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Table_Entries_Are_Flattened_When_Enumerated() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Added); builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added), (5, EntryState.Added), (6, EntryState.Added), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Table_Entries_Can_Be_The_Same_Object() { var o = new object(); var builder = NodeStateTable<object>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(o, o, o), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((o, EntryState.Added), (o, EntryState.Added), (o, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Table_Entries_Can_Be_Null() { object? o = new object(); var builder = NodeStateTable<object?>.Empty.ToBuilder(); builder.AddEntry(o, EntryState.Added); builder.AddEntry(null, EntryState.Added); builder.AddEntry(o, EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((o, EntryState.Added), (null, EntryState.Added), (o, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Builder_Can_Add_Entries_From_Previous_Table() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); builder.AddEntries(ImmutableArray.Create(2, 3), EntryState.Cached); builder.AddEntries(ImmutableArray.Create(4, 5), EntryState.Modified); builder.AddEntries(ImmutableArray.Create(6), EntryState.Added); var previousTable = builder.ToImmutableAndFree(); builder = previousTable.ToBuilder(); builder.AddEntries(ImmutableArray.Create(10, 11), EntryState.Added); builder.TryUseCachedEntries(); // ((2, EntryState.Cached), (3, EntryState.Cached)) builder.AddEntries(ImmutableArray.Create(20, 21, 22), EntryState.Modified); builder.RemoveEntries(); //((6, EntryState.Removed))); var newTable = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((10, EntryState.Added), (11, EntryState.Added), (2, EntryState.Cached), (3, EntryState.Cached), (20, EntryState.Modified), (21, EntryState.Modified), (22, EntryState.Modified), (6, EntryState.Removed)); AssertTableEntries(newTable, expected); } [Fact] public void Node_Table_Entries_Are_Cached_Or_Dropped_When_Cached() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Removed); builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Removed), (5, EntryState.Removed), (6, EntryState.Removed), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added)); AssertTableEntries(table, expected); var compactedTable = table.AsCached(); expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (7, EntryState.Cached), (8, EntryState.Cached), (9, EntryState.Cached)); AssertTableEntries(compactedTable, expected); } [Fact] public void Node_Table_AsCached_Occurs_Only_Once() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Removed); builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Removed), (5, EntryState.Removed), (6, EntryState.Removed), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added)); AssertTableEntries(table, expected); var compactedTable = table.AsCached(); expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (7, EntryState.Cached), (8, EntryState.Cached), (9, EntryState.Cached)); AssertTableEntries(compactedTable, expected); // calling as cached a second time just returns the same instance var compactedTable2 = compactedTable.AsCached(); Assert.Same(compactedTable, compactedTable2); } [Fact] public void Node_Table_Single_Returns_First_Item() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); var table = builder.ToImmutableAndFree(); Assert.Equal(1, table.Single()); } [Fact] public void Node_Table_Single_Returns_Second_Item_When_First_Is_Removed() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); var table = builder.ToImmutableAndFree(); AssertTableEntries(table, new[] { (1, EntryState.Added) }); // remove the first item and replace it in the table builder = table.ToBuilder(); builder.RemoveEntries(); builder.AddEntries(ImmutableArray.Create(2), EntryState.Added); table = builder.ToImmutableAndFree(); AssertTableEntries(table, new[] { (1, EntryState.Removed), (2, EntryState.Added) }); Assert.Equal(2, table.Single()); } [Fact] public void Node_Builder_Handles_Modification_When_Both_Tables_Have_Empty_Entries() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2), EntryState.Added); builder.AddEntries(ImmutableArray<int>.Empty, EntryState.Added); builder.AddEntries(ImmutableArray.Create(3, 4), EntryState.Added); var previousTable = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added)); AssertTableEntries(previousTable, expected); builder = previousTable.ToBuilder(); Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 2), EqualityComparer<int>.Default)); // ((3, EntryState.Modified), (2, EntryState.Cached)) Assert.True(builder.TryModifyEntries(ImmutableArray<int>.Empty, EqualityComparer<int>.Default)); // nothing Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 5), EqualityComparer<int>.Default)); // ((3, EntryState.Cached), (5, EntryState.Modified)) var newTable = builder.ToImmutableAndFree(); expected = ImmutableArray.Create((3, EntryState.Modified), (2, EntryState.Cached), (3, EntryState.Cached), (5, EntryState.Modified)); AssertTableEntries(newTable, expected); } [Fact] public void Node_Table_Doesnt_Modify_Single_Item_Multiple_Times_When_Same() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); builder.AddEntries(ImmutableArray.Create(2), EntryState.Added); builder.AddEntries(ImmutableArray.Create(3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4), EntryState.Added); var previousTable = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added)); AssertTableEntries(previousTable, expected); builder = previousTable.ToBuilder(); Assert.True(builder.TryModifyEntry(1, EqualityComparer<int>.Default)); // ((1, EntryState.Cached)) Assert.True(builder.TryModifyEntry(2, EqualityComparer<int>.Default)); // ((2, EntryState.Cached)) Assert.True(builder.TryModifyEntry(5, EqualityComparer<int>.Default)); // ((5, EntryState.Modified)) Assert.True(builder.TryModifyEntry(4, EqualityComparer<int>.Default)); // ((4, EntryState.Cached)) var newTable = builder.ToImmutableAndFree(); expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (5, EntryState.Modified), (4, EntryState.Cached)); AssertTableEntries(newTable, expected); } [Fact] public void Driver_Table_Calls_Into_Node_With_Self() { DriverStateTable.Builder? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = b; return s; }); DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(builder, passedIn); } [Fact] public void Driver_Table_Calls_Into_Node_With_EmptyState_FirstTime() { NodeStateTable<int>? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = s; return s; }); DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(NodeStateTable<int>.Empty, passedIn); } [Fact] public void Driver_Table_Calls_Into_Node_With_PreviousTable() { var nodeBuilder = NodeStateTable<int>.Empty.ToBuilder(); nodeBuilder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Cached); var newTable = nodeBuilder.ToImmutableAndFree(); NodeStateTable<int>? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = s; return newTable; }); // empty first time DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(NodeStateTable<int>.Empty, passedIn); // gives the returned table the second time around DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable()); builder2.GetLatestStateTableForNode(callbackNode); Assert.NotNull(passedIn); AssertTableEntries(passedIn!, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached) }); } [Fact] public void Driver_Table_Compacts_State_Tables_When_Made_Immutable() { var nodeBuilder = NodeStateTable<int>.Empty.ToBuilder(); nodeBuilder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); nodeBuilder.AddEntries(ImmutableArray.Create(4), EntryState.Removed); nodeBuilder.AddEntries(ImmutableArray.Create(5, 6), EntryState.Modified); var newTable = nodeBuilder.ToImmutableAndFree(); NodeStateTable<int>? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = s; return newTable; }); // empty first time DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(NodeStateTable<int>.Empty, passedIn); // gives the returned table the second time around DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable()); builder2.GetLatestStateTableForNode(callbackNode); // table returned from the first instance was compacted by the builder Assert.NotNull(passedIn); AssertTableEntries(passedIn!, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (5, EntryState.Cached), (6, EntryState.Cached) }); } [Fact] public void Driver_Table_Builder_Doesnt_Build_Twice() { int callCount = 0; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { callCount++; return s; }); // multiple gets will only call it once DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); builder.GetLatestStateTableForNode(callbackNode); builder.GetLatestStateTableForNode(callbackNode); Assert.Equal(1, callCount); // second time around we'll call it once, but no more DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable()); builder2.GetLatestStateTableForNode(callbackNode); builder2.GetLatestStateTableForNode(callbackNode); builder2.GetLatestStateTableForNode(callbackNode); Assert.Equal(2, callCount); } [Fact] public void Batch_Node_Is_Cached_If_All_Inputs_Are_Cached() { var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, 3)); BatchNode<int> batchNode = new BatchNode<int>(inputNode); // first time through will always be added (because it's not been run before) DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty); _ = dstBuilder.GetLatestStateTableForNode(batchNode); // second time through should show as cached dstBuilder = GetBuilder(dstBuilder.ToImmutable()); var table = dstBuilder.GetLatestStateTableForNode(batchNode); AssertTableEntries(table, new[] { (ImmutableArray.Create(1, 2, 3), EntryState.Cached) }); } [Fact] public void Batch_Node_Is_Not_Cached_When_Inputs_Are_Changed() { int third = 3; var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, third++)); BatchNode<int> batchNode = new BatchNode<int>(inputNode); // first time through will always be added (because it's not been run before) DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty); _ = dstBuilder.GetLatestStateTableForNode(batchNode); // second time through should show as modified dstBuilder = GetBuilder(dstBuilder.ToImmutable()); var table = dstBuilder.GetLatestStateTableForNode(batchNode); AssertTableEntries(table, new[] { (ImmutableArray.Create(1, 2, 4), EntryState.Modified) }); } [Fact] public void User_Comparer_Is_Not_Used_To_Determine_Inputs() { var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, 3)) .WithComparer(new LambdaComparer<int>((a, b) => false)); // first time through will always be added (because it's not been run before) DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty); _ = dstBuilder.GetLatestStateTableForNode(inputNode); // second time through should show as cached, even though we supplied a comparer (comparer should only used to turn modified => cached) dstBuilder = GetBuilder(dstBuilder.ToImmutable()); var table = dstBuilder.GetLatestStateTableForNode(inputNode); AssertTableEntries(table, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached) }); } private void AssertTableEntries<T>(NodeStateTable<T> table, IList<(T item, EntryState state)> expected) { int index = 0; foreach (var entry in table) { Assert.Equal(expected[index].item, entry.item); Assert.Equal(expected[index].state, entry.state); index++; } } private void AssertTableEntries<T>(NodeStateTable<ImmutableArray<T>> table, IList<(ImmutableArray<T> item, EntryState state)> expected) { int index = 0; foreach (var entry in table) { AssertEx.Equal(expected[index].item, entry.item); Assert.Equal(expected[index].state, entry.state); index++; } } private DriverStateTable.Builder GetBuilder(DriverStateTable previous) { var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10); var c = CSharpCompilation.Create("empty"); var state = new GeneratorDriverState(options, CompilerAnalyzerConfigOptionsProvider.Empty, ImmutableArray<ISourceGenerator>.Empty, ImmutableArray<IIncrementalGenerator>.Empty, ImmutableArray<AdditionalText>.Empty, ImmutableArray<GeneratorState>.Empty, previous, disabledOutputs: IncrementalGeneratorOutputKind.None, runtime: TimeSpan.Zero); return new DriverStateTable.Builder(c, state, ImmutableArray<ISyntaxInputNode>.Empty); } private class CallbackNode<T> : IIncrementalGeneratorNode<T> { private readonly Func<DriverStateTable.Builder, NodeStateTable<T>, NodeStateTable<T>> _callback; public CallbackNode(Func<DriverStateTable.Builder, NodeStateTable<T>, NodeStateTable<T>> callback) { _callback = callback; } public NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken) { return _callback(graphState, previousTable); } public IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer) => this; public void RegisterOutput(IIncrementalGeneratorOutputNode output) { } } } }
1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/DiagnosticAnalyzer/DefaultAnalyzerAssemblyLoader.Core.cs
// 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. #if NETCOREAPP using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; namespace Microsoft.CodeAnalysis { internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { /// <summary> /// <p>Typically a user analyzer has a reference to the compiler and some of the compiler's /// dependencies such as System.Collections.Immutable. For the analyzer to correctly /// interoperate with the compiler that created it, we need to ensure that we always use the /// compiler's version of a given assembly over the analyzer's version.</p> /// /// <p>If we neglect to do this, then in the case where the user ships the compiler or its /// dependencies in the analyzer's bin directory, we could end up loading a separate /// instance of those assemblies in the process of loading the analyzer, which will surface /// as a failure to load the analyzer.</p> /// </summary> internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames = ImmutableHashSet.Create( StringComparer.OrdinalIgnoreCase, "Microsoft.CodeAnalysis", "Microsoft.CodeAnalysis.CSharp", "Microsoft.CodeAnalysis.VisualBasic", "System.Collections", "System.Collections.Concurrent", "System.Collections.Immutable", "System.Console", "System.Diagnostics.Debug", "System.Diagnostics.StackTrace", "System.IO.Compression", "System.IO.FileSystem", "System.Linq", "System.Linq.Expressions", "System.Memory", "System.Reflection.Metadata", "System.Reflection.Primitives", "System.Resources.ResourceManager", "System.Runtime", "System.Runtime.CompilerServices.Unsafe", "System.Runtime.Extensions", "System.Runtime.InteropServices", "System.Runtime.Loader", "System.Runtime.Numerics", "System.Runtime.Serialization.Primitives", "System.Security.Cryptography.Algorithms", "System.Security.Cryptography.Primitives", "System.Text.Encoding.CodePages", "System.Text.Encoding.Extensions", "System.Text.RegularExpressions", "System.Threading", "System.Threading.Tasks", "System.Threading.Tasks.Parallel", "System.Threading.Thread", "System.Threading.ThreadPool", "System.Xml.ReaderWriter", "System.Xml.XDocument", "System.Xml.XPath.XDocument"); private readonly object _guard = new object(); private readonly Dictionary<string, DirectoryLoadContext> _loadContextByDirectory = new Dictionary<string, DirectoryLoadContext>(StringComparer.Ordinal); protected override Assembly LoadFromPathImpl(string fullPath) { DirectoryLoadContext? loadContext; var fullDirectoryPath = Path.GetDirectoryName(fullPath) ?? throw new ArgumentException(message: null, paramName: nameof(fullPath)); lock (_guard) { if (!_loadContextByDirectory.TryGetValue(fullDirectoryPath, out loadContext)) { loadContext = new DirectoryLoadContext(fullDirectoryPath, this); _loadContextByDirectory[fullDirectoryPath] = loadContext; } } var name = AssemblyName.GetAssemblyName(fullPath); return loadContext.LoadFromAssemblyName(name); } internal static class TestAccessor { public static AssemblyLoadContext[] GetOrderedLoadContexts(DefaultAnalyzerAssemblyLoader loader) { return loader._loadContextByDirectory.Values.OrderBy(v => v.Directory).ToArray(); } } private sealed class DirectoryLoadContext : AssemblyLoadContext { internal string Directory { get; } private readonly DefaultAnalyzerAssemblyLoader _loader; public DirectoryLoadContext(string directory, DefaultAnalyzerAssemblyLoader loader) { Directory = directory; _loader = loader; } protected override Assembly? Load(AssemblyName assemblyName) { var simpleName = assemblyName.Name!; if (CompilerAssemblySimpleNames.Contains(simpleName)) { // Delegate to the compiler's load context to load the compiler or anything // referenced by the compiler return null; } var assemblyPath = Path.Combine(Directory, simpleName + ".dll"); if (!_loader.IsKnownDependencyLocation(assemblyPath)) { // The analyzer didn't explicitly register this dependency. Most likely the // assembly we're trying to load here is netstandard or a similar framework // assembly. We assume that if that is not the case, then the parent ALC will // fail to load this. return null; } var pathToLoad = _loader.GetPathToLoad(assemblyPath); return LoadFromAssemblyPath(pathToLoad); } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { var assemblyPath = Path.Combine(Directory, unmanagedDllName + ".dll"); if (!_loader.IsKnownDependencyLocation(assemblyPath)) { return IntPtr.Zero; } var pathToLoad = _loader.GetPathToLoad(assemblyPath); return LoadUnmanagedDllFromPath(pathToLoad); } } } } #endif
// 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. #if NETCOREAPP using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; namespace Microsoft.CodeAnalysis { internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { /// <summary> /// <p>Typically a user analyzer has a reference to the compiler and some of the compiler's /// dependencies such as System.Collections.Immutable. For the analyzer to correctly /// interoperate with the compiler that created it, we need to ensure that we always use the /// compiler's version of a given assembly over the analyzer's version.</p> /// /// <p>If we neglect to do this, then in the case where the user ships the compiler or its /// dependencies in the analyzer's bin directory, we could end up loading a separate /// instance of those assemblies in the process of loading the analyzer, which will surface /// as a failure to load the analyzer.</p> /// </summary> internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames = ImmutableHashSet.Create( StringComparer.OrdinalIgnoreCase, "Microsoft.CodeAnalysis", "Microsoft.CodeAnalysis.CSharp", "Microsoft.CodeAnalysis.VisualBasic", "System.Collections", "System.Collections.Concurrent", "System.Collections.Immutable", "System.Console", "System.Diagnostics.Debug", "System.Diagnostics.StackTrace", "System.Diagnostics.Tracing", "System.IO.Compression", "System.IO.FileSystem", "System.Linq", "System.Linq.Expressions", "System.Memory", "System.Reflection.Metadata", "System.Reflection.Primitives", "System.Resources.ResourceManager", "System.Runtime", "System.Runtime.CompilerServices.Unsafe", "System.Runtime.Extensions", "System.Runtime.InteropServices", "System.Runtime.Loader", "System.Runtime.Numerics", "System.Runtime.Serialization.Primitives", "System.Security.Cryptography.Algorithms", "System.Security.Cryptography.Primitives", "System.Text.Encoding.CodePages", "System.Text.Encoding.Extensions", "System.Text.RegularExpressions", "System.Threading", "System.Threading.Tasks", "System.Threading.Tasks.Parallel", "System.Threading.Thread", "System.Threading.ThreadPool", "System.Xml.ReaderWriter", "System.Xml.XDocument", "System.Xml.XPath.XDocument"); private readonly object _guard = new object(); private readonly Dictionary<string, DirectoryLoadContext> _loadContextByDirectory = new Dictionary<string, DirectoryLoadContext>(StringComparer.Ordinal); protected override Assembly LoadFromPathImpl(string fullPath) { DirectoryLoadContext? loadContext; var fullDirectoryPath = Path.GetDirectoryName(fullPath) ?? throw new ArgumentException(message: null, paramName: nameof(fullPath)); lock (_guard) { if (!_loadContextByDirectory.TryGetValue(fullDirectoryPath, out loadContext)) { loadContext = new DirectoryLoadContext(fullDirectoryPath, this); _loadContextByDirectory[fullDirectoryPath] = loadContext; } } var name = AssemblyName.GetAssemblyName(fullPath); return loadContext.LoadFromAssemblyName(name); } internal static class TestAccessor { public static AssemblyLoadContext[] GetOrderedLoadContexts(DefaultAnalyzerAssemblyLoader loader) { return loader._loadContextByDirectory.Values.OrderBy(v => v.Directory).ToArray(); } } private sealed class DirectoryLoadContext : AssemblyLoadContext { internal string Directory { get; } private readonly DefaultAnalyzerAssemblyLoader _loader; public DirectoryLoadContext(string directory, DefaultAnalyzerAssemblyLoader loader) { Directory = directory; _loader = loader; } protected override Assembly? Load(AssemblyName assemblyName) { var simpleName = assemblyName.Name!; if (CompilerAssemblySimpleNames.Contains(simpleName)) { // Delegate to the compiler's load context to load the compiler or anything // referenced by the compiler return null; } var assemblyPath = Path.Combine(Directory, simpleName + ".dll"); if (!_loader.IsKnownDependencyLocation(assemblyPath)) { // The analyzer didn't explicitly register this dependency. Most likely the // assembly we're trying to load here is netstandard or a similar framework // assembly. We assume that if that is not the case, then the parent ALC will // fail to load this. return null; } var pathToLoad = _loader.GetPathToLoad(assemblyPath); return LoadFromAssemblyPath(pathToLoad); } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { var assemblyPath = Path.Combine(Directory, unmanagedDllName + ".dll"); if (!_loader.IsKnownDependencyLocation(assemblyPath)) { return IntPtr.Zero; } var pathToLoad = _loader.GetPathToLoad(assemblyPath); return LoadUnmanagedDllFromPath(pathToLoad); } } } } #endif
1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/SourceGeneration/GeneratorDriver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Responsible for orchestrating a source generation pass /// </summary> /// <remarks> /// GeneratorDriver is an immutable class that can be manipulated by returning a mutated copy of itself. /// In the compiler we only ever create a single instance and ignore the mutated copy. The IDE may perform /// multiple edits, or generation passes of the same driver, re-using the state as needed. /// </remarks> public abstract class GeneratorDriver { internal readonly GeneratorDriverState _state; internal GeneratorDriver(GeneratorDriverState state) { Debug.Assert(state.Generators.GroupBy(s => s.GetGeneratorType()).Count() == state.Generators.Length); // ensure we don't have duplicate generator types _state = state; } internal GeneratorDriver(ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts, GeneratorDriverOptions driverOptions) { (var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators, SourceExtension); _state = new GeneratorDriverState(parseOptions, optionsProvider, filteredGenerators, incrementalGenerators, additionalTexts, ImmutableArray.Create(new GeneratorState[filteredGenerators.Length]), DriverStateTable.Empty, driverOptions.DisabledOutputs); } public GeneratorDriver RunGenerators(Compilation compilation, CancellationToken cancellationToken = default) { var state = RunGeneratorsCore(compilation, diagnosticsBag: null, cancellationToken); //don't directly collect diagnostics on this path return FromState(state); } public GeneratorDriver RunGeneratorsAndUpdateCompilation(Compilation compilation, out Compilation outputCompilation, out ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken = default) { var diagnosticsBag = DiagnosticBag.GetInstance(); var state = RunGeneratorsCore(compilation, diagnosticsBag, cancellationToken); // build the output compilation diagnostics = diagnosticsBag.ToReadOnlyAndFree(); ArrayBuilder<SyntaxTree> trees = ArrayBuilder<SyntaxTree>.GetInstance(); foreach (var generatorState in state.GeneratorStates) { trees.AddRange(generatorState.PostInitTrees.Select(t => t.Tree)); trees.AddRange(generatorState.GeneratedTrees.Select(t => t.Tree)); } outputCompilation = compilation.AddSyntaxTrees(trees); trees.Free(); return FromState(state); } public GeneratorDriver AddGenerators(ImmutableArray<ISourceGenerator> generators) { (var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators, SourceExtension); var newState = _state.With(sourceGenerators: _state.Generators.AddRange(filteredGenerators), incrementalGenerators: _state.IncrementalGenerators.AddRange(incrementalGenerators), generatorStates: _state.GeneratorStates.AddRange(new GeneratorState[filteredGenerators.Length])); return FromState(newState); } public GeneratorDriver RemoveGenerators(ImmutableArray<ISourceGenerator> generators) { var newGenerators = _state.Generators; var newStates = _state.GeneratorStates; var newIncrementalGenerators = _state.IncrementalGenerators; for (int i = 0; i < newGenerators.Length; i++) { if (generators.Contains(newGenerators[i])) { newGenerators = newGenerators.RemoveAt(i); newStates = newStates.RemoveAt(i); newIncrementalGenerators = newIncrementalGenerators.RemoveAt(i); i--; } } return FromState(_state.With(sourceGenerators: newGenerators, incrementalGenerators: newIncrementalGenerators, generatorStates: newStates)); } public GeneratorDriver AddAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts) { var newState = _state.With(additionalTexts: _state.AdditionalTexts.AddRange(additionalTexts)); return FromState(newState); } public GeneratorDriver RemoveAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts) { var newState = _state.With(additionalTexts: _state.AdditionalTexts.RemoveRange(additionalTexts)); return FromState(newState); } public GeneratorDriver ReplaceAdditionalText(AdditionalText oldText, AdditionalText newText) { if (oldText is null) { throw new ArgumentNullException(nameof(oldText)); } if (newText is null) { throw new ArgumentNullException(nameof(newText)); } var newState = _state.With(additionalTexts: _state.AdditionalTexts.Replace(oldText, newText)); return FromState(newState); } public GeneratorDriver WithUpdatedParseOptions(ParseOptions newOptions) => newOptions is object ? FromState(_state.With(parseOptions: newOptions)) : throw new ArgumentNullException(nameof(newOptions)); public GeneratorDriver WithUpdatedAnalyzerConfigOptions(AnalyzerConfigOptionsProvider newOptions) => newOptions is object ? FromState(_state.With(optionsProvider: newOptions)) : throw new ArgumentNullException(nameof(newOptions)); public GeneratorDriverRunResult GetRunResult() { var results = _state.Generators.ZipAsArray( _state.GeneratorStates, (generator, generatorState) => new GeneratorRunResult(generator, diagnostics: generatorState.Diagnostics, exception: generatorState.Exception, generatedSources: getGeneratorSources(generatorState))); return new GeneratorDriverRunResult(results); static ImmutableArray<GeneratedSourceResult> getGeneratorSources(GeneratorState generatorState) { ArrayBuilder<GeneratedSourceResult> sources = ArrayBuilder<GeneratedSourceResult>.GetInstance(generatorState.PostInitTrees.Length + generatorState.GeneratedTrees.Length); foreach (var tree in generatorState.PostInitTrees) { sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName)); } foreach (var tree in generatorState.GeneratedTrees) { sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName)); } return sources.ToImmutableAndFree(); } } internal GeneratorDriverState RunGeneratorsCore(Compilation compilation, DiagnosticBag? diagnosticsBag, CancellationToken cancellationToken = default) { // with no generators, there is no work to do if (_state.Generators.IsEmpty) { return _state.With(stateTable: DriverStateTable.Empty); } // run the actual generation var state = _state; var stateBuilder = ArrayBuilder<GeneratorState>.GetInstance(state.Generators.Length); var constantSourcesBuilder = ArrayBuilder<SyntaxTree>.GetInstance(); var syntaxInputNodes = ArrayBuilder<ISyntaxInputNode>.GetInstance(); for (int i = 0; i < state.IncrementalGenerators.Length; i++) { var generator = state.IncrementalGenerators[i]; var generatorState = state.GeneratorStates[i]; var sourceGenerator = state.Generators[i]; // initialize the generator if needed if (!generatorState.Initialized) { var outputBuilder = ArrayBuilder<IIncrementalGeneratorOutputNode>.GetInstance(); var inputBuilder = ArrayBuilder<ISyntaxInputNode>.GetInstance(); var postInitSources = ImmutableArray<GeneratedSyntaxTree>.Empty; var pipelineContext = new IncrementalGeneratorInitializationContext(inputBuilder, outputBuilder, SourceExtension); Exception? ex = null; try { generator.Initialize(pipelineContext); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { ex = e; } var outputNodes = outputBuilder.ToImmutableAndFree(); var inputNodes = inputBuilder.ToImmutableAndFree(); // run post init if (ex is null) { try { IncrementalExecutionContext context = UpdateOutputs(outputNodes, IncrementalGeneratorOutputKind.PostInit, cancellationToken); postInitSources = ParseAdditionalSources(sourceGenerator, context.ToImmutableAndFree().sources, cancellationToken); } catch (UserFunctionException e) { ex = e.InnerException; } } generatorState = ex is null ? new GeneratorState(generatorState.Info, postInitSources, inputNodes, outputNodes) : SetGeneratorException(MessageProvider, generatorState, sourceGenerator, ex, diagnosticsBag, isInit: true); } // if the pipeline registered any syntax input nodes, record them if (!generatorState.InputNodes.IsEmpty) { syntaxInputNodes.AddRange(generatorState.InputNodes); } // record any constant sources if (generatorState.Exception is null && generatorState.PostInitTrees.Length > 0) { constantSourcesBuilder.AddRange(generatorState.PostInitTrees.Select(t => t.Tree)); } stateBuilder.Add(generatorState); } // update the compilation with any constant sources if (constantSourcesBuilder.Count > 0) { compilation = compilation.AddSyntaxTrees(constantSourcesBuilder); } constantSourcesBuilder.Free(); var driverStateBuilder = new DriverStateTable.Builder(compilation, _state, syntaxInputNodes.ToImmutableAndFree(), cancellationToken); for (int i = 0; i < state.IncrementalGenerators.Length; i++) { var generatorState = stateBuilder[i]; if (generatorState.Exception is object) { continue; } try { var context = UpdateOutputs(generatorState.OutputNodes, IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation, cancellationToken, driverStateBuilder); (var sources, var generatorDiagnostics) = context.ToImmutableAndFree(); generatorDiagnostics = FilterDiagnostics(compilation, generatorDiagnostics, driverDiagnostics: diagnosticsBag, cancellationToken); stateBuilder[i] = new GeneratorState(generatorState.Info, generatorState.PostInitTrees, generatorState.InputNodes, generatorState.OutputNodes, ParseAdditionalSources(state.Generators[i], sources, cancellationToken), generatorDiagnostics); } catch (UserFunctionException ufe) { stateBuilder[i] = SetGeneratorException(MessageProvider, stateBuilder[i], state.Generators[i], ufe.InnerException, diagnosticsBag); } } state = state.With(stateTable: driverStateBuilder.ToImmutable(), generatorStates: stateBuilder.ToImmutableAndFree()); return state; } private IncrementalExecutionContext UpdateOutputs(ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, IncrementalGeneratorOutputKind outputKind, CancellationToken cancellationToken, DriverStateTable.Builder? driverStateBuilder = null) { Debug.Assert(outputKind != IncrementalGeneratorOutputKind.None); IncrementalExecutionContext context = new IncrementalExecutionContext(driverStateBuilder, new AdditionalSourcesCollection(SourceExtension)); foreach (var outputNode in outputNodes) { // if we're looking for this output kind, and it has not been explicitly disabled if (outputKind.HasFlag(outputNode.Kind) && !_state.DisabledOutputs.HasFlag(outputNode.Kind)) { outputNode.AppendOutputs(context, cancellationToken); } } return context; } private ImmutableArray<GeneratedSyntaxTree> ParseAdditionalSources(ISourceGenerator generator, ImmutableArray<GeneratedSourceText> generatedSources, CancellationToken cancellationToken) { var trees = ArrayBuilder<GeneratedSyntaxTree>.GetInstance(generatedSources.Length); var type = generator.GetGeneratorType(); var prefix = GetFilePathPrefixForGenerator(generator); foreach (var source in generatedSources) { var tree = ParseGeneratedSourceText(source, Path.Combine(prefix, source.HintName), cancellationToken); trees.Add(new GeneratedSyntaxTree(source.HintName, source.Text, tree)); } return trees.ToImmutableAndFree(); } private static GeneratorState SetGeneratorException(CommonMessageProvider provider, GeneratorState generatorState, ISourceGenerator generator, Exception e, DiagnosticBag? diagnosticBag, bool isInit = false) { var errorCode = isInit ? provider.WRN_GeneratorFailedDuringInitialization : provider.WRN_GeneratorFailedDuringGeneration; // ISSUE: Diagnostics don't currently allow descriptions with arguments, so we have to manually create the diagnostic description // ISSUE: Exceptions also don't support IFormattable, so will always be in the current UI Culture. // ISSUE: See https://github.com/dotnet/roslyn/issues/46939 var description = string.Format(provider.GetDescription(errorCode).ToString(CultureInfo.CurrentUICulture), e); var descriptor = new DiagnosticDescriptor( provider.GetIdForErrorCode(errorCode), provider.GetTitle(errorCode), provider.GetMessageFormat(errorCode), description: description, category: "Compiler", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: WellKnownDiagnosticTags.AnalyzerException); var diagnostic = Diagnostic.Create(descriptor, Location.None, generator.GetGeneratorType().Name, e.GetType().Name, e.Message); diagnosticBag?.Add(diagnostic); return new GeneratorState(generatorState.Info, e, diagnostic); } private static ImmutableArray<Diagnostic> FilterDiagnostics(Compilation compilation, ImmutableArray<Diagnostic> generatorDiagnostics, DiagnosticBag? driverDiagnostics, CancellationToken cancellationToken) { ArrayBuilder<Diagnostic> filteredDiagnostics = ArrayBuilder<Diagnostic>.GetInstance(); foreach (var diag in generatorDiagnostics) { var filtered = compilation.Options.FilterDiagnostic(diag, cancellationToken); if (filtered is object) { filteredDiagnostics.Add(filtered); driverDiagnostics?.Add(filtered); } } return filteredDiagnostics.ToImmutableAndFree(); } internal static string GetFilePathPrefixForGenerator(ISourceGenerator generator) { var type = generator.GetGeneratorType(); return Path.Combine(type.Assembly.GetName().Name ?? string.Empty, type.FullName!); } private static (ImmutableArray<ISourceGenerator>, ImmutableArray<IIncrementalGenerator>) GetIncrementalGenerators(ImmutableArray<ISourceGenerator> generators, string sourceExtension) { return (generators, generators.SelectAsArray(g => g switch { IncrementalGeneratorWrapper igw => igw.Generator, IIncrementalGenerator ig => ig, _ => new SourceGeneratorAdaptor(g, sourceExtension) })); } internal abstract CommonMessageProvider MessageProvider { get; } internal abstract GeneratorDriver FromState(GeneratorDriverState state); internal abstract SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken); internal abstract string SourceExtension { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Responsible for orchestrating a source generation pass /// </summary> /// <remarks> /// GeneratorDriver is an immutable class that can be manipulated by returning a mutated copy of itself. /// In the compiler we only ever create a single instance and ignore the mutated copy. The IDE may perform /// multiple edits, or generation passes of the same driver, re-using the state as needed. /// </remarks> public abstract class GeneratorDriver { internal readonly GeneratorDriverState _state; internal GeneratorDriver(GeneratorDriverState state) { Debug.Assert(state.Generators.GroupBy(s => s.GetGeneratorType()).Count() == state.Generators.Length); // ensure we don't have duplicate generator types _state = state; } internal GeneratorDriver(ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts, GeneratorDriverOptions driverOptions) { (var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators, SourceExtension); _state = new GeneratorDriverState(parseOptions, optionsProvider, filteredGenerators, incrementalGenerators, additionalTexts, ImmutableArray.Create(new GeneratorState[filteredGenerators.Length]), DriverStateTable.Empty, driverOptions.DisabledOutputs, runtime: TimeSpan.Zero); } public GeneratorDriver RunGenerators(Compilation compilation, CancellationToken cancellationToken = default) { var state = RunGeneratorsCore(compilation, diagnosticsBag: null, cancellationToken); //don't directly collect diagnostics on this path return FromState(state); } public GeneratorDriver RunGeneratorsAndUpdateCompilation(Compilation compilation, out Compilation outputCompilation, out ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken = default) { var diagnosticsBag = DiagnosticBag.GetInstance(); var state = RunGeneratorsCore(compilation, diagnosticsBag, cancellationToken); // build the output compilation diagnostics = diagnosticsBag.ToReadOnlyAndFree(); ArrayBuilder<SyntaxTree> trees = ArrayBuilder<SyntaxTree>.GetInstance(); foreach (var generatorState in state.GeneratorStates) { trees.AddRange(generatorState.PostInitTrees.Select(t => t.Tree)); trees.AddRange(generatorState.GeneratedTrees.Select(t => t.Tree)); } outputCompilation = compilation.AddSyntaxTrees(trees); trees.Free(); return FromState(state); } public GeneratorDriver AddGenerators(ImmutableArray<ISourceGenerator> generators) { (var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators, SourceExtension); var newState = _state.With(sourceGenerators: _state.Generators.AddRange(filteredGenerators), incrementalGenerators: _state.IncrementalGenerators.AddRange(incrementalGenerators), generatorStates: _state.GeneratorStates.AddRange(new GeneratorState[filteredGenerators.Length])); return FromState(newState); } public GeneratorDriver RemoveGenerators(ImmutableArray<ISourceGenerator> generators) { var newGenerators = _state.Generators; var newStates = _state.GeneratorStates; var newIncrementalGenerators = _state.IncrementalGenerators; for (int i = 0; i < newGenerators.Length; i++) { if (generators.Contains(newGenerators[i])) { newGenerators = newGenerators.RemoveAt(i); newStates = newStates.RemoveAt(i); newIncrementalGenerators = newIncrementalGenerators.RemoveAt(i); i--; } } return FromState(_state.With(sourceGenerators: newGenerators, incrementalGenerators: newIncrementalGenerators, generatorStates: newStates)); } public GeneratorDriver AddAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts) { var newState = _state.With(additionalTexts: _state.AdditionalTexts.AddRange(additionalTexts)); return FromState(newState); } public GeneratorDriver RemoveAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts) { var newState = _state.With(additionalTexts: _state.AdditionalTexts.RemoveRange(additionalTexts)); return FromState(newState); } public GeneratorDriver ReplaceAdditionalText(AdditionalText oldText, AdditionalText newText) { if (oldText is null) { throw new ArgumentNullException(nameof(oldText)); } if (newText is null) { throw new ArgumentNullException(nameof(newText)); } var newState = _state.With(additionalTexts: _state.AdditionalTexts.Replace(oldText, newText)); return FromState(newState); } public GeneratorDriver WithUpdatedParseOptions(ParseOptions newOptions) => newOptions is object ? FromState(_state.With(parseOptions: newOptions)) : throw new ArgumentNullException(nameof(newOptions)); public GeneratorDriver WithUpdatedAnalyzerConfigOptions(AnalyzerConfigOptionsProvider newOptions) => newOptions is object ? FromState(_state.With(optionsProvider: newOptions)) : throw new ArgumentNullException(nameof(newOptions)); public GeneratorDriverRunResult GetRunResult() { var results = _state.Generators.ZipAsArray( _state.GeneratorStates, (generator, generatorState) => new GeneratorRunResult(generator, diagnostics: generatorState.Diagnostics, exception: generatorState.Exception, generatedSources: getGeneratorSources(generatorState), elapsedTime: generatorState.ElapsedTime)); return new GeneratorDriverRunResult(results, _state.RunTime); static ImmutableArray<GeneratedSourceResult> getGeneratorSources(GeneratorState generatorState) { ArrayBuilder<GeneratedSourceResult> sources = ArrayBuilder<GeneratedSourceResult>.GetInstance(generatorState.PostInitTrees.Length + generatorState.GeneratedTrees.Length); foreach (var tree in generatorState.PostInitTrees) { sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName)); } foreach (var tree in generatorState.GeneratedTrees) { sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName)); } return sources.ToImmutableAndFree(); } } internal GeneratorDriverState RunGeneratorsCore(Compilation compilation, DiagnosticBag? diagnosticsBag, CancellationToken cancellationToken = default) { // with no generators, there is no work to do if (_state.Generators.IsEmpty) { return _state.With(stateTable: DriverStateTable.Empty, runTime: TimeSpan.Zero); } // run the actual generation using var timer = CodeAnalysisEventSource.Log.CreateGeneratorDriverRunTimer(); var state = _state; var stateBuilder = ArrayBuilder<GeneratorState>.GetInstance(state.Generators.Length); var constantSourcesBuilder = ArrayBuilder<SyntaxTree>.GetInstance(); var syntaxInputNodes = ArrayBuilder<ISyntaxInputNode>.GetInstance(); for (int i = 0; i < state.IncrementalGenerators.Length; i++) { var generator = state.IncrementalGenerators[i]; var generatorState = state.GeneratorStates[i]; var sourceGenerator = state.Generators[i]; // initialize the generator if needed if (!generatorState.Initialized) { var outputBuilder = ArrayBuilder<IIncrementalGeneratorOutputNode>.GetInstance(); var inputBuilder = ArrayBuilder<ISyntaxInputNode>.GetInstance(); var postInitSources = ImmutableArray<GeneratedSyntaxTree>.Empty; var pipelineContext = new IncrementalGeneratorInitializationContext(inputBuilder, outputBuilder, SourceExtension); Exception? ex = null; try { generator.Initialize(pipelineContext); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { ex = e; } var outputNodes = outputBuilder.ToImmutableAndFree(); var inputNodes = inputBuilder.ToImmutableAndFree(); // run post init if (ex is null) { try { IncrementalExecutionContext context = UpdateOutputs(outputNodes, IncrementalGeneratorOutputKind.PostInit, cancellationToken); postInitSources = ParseAdditionalSources(sourceGenerator, context.ToImmutableAndFree().sources, cancellationToken); } catch (UserFunctionException e) { ex = e.InnerException; } } generatorState = ex is null ? new GeneratorState(generatorState.Info, postInitSources, inputNodes, outputNodes) : SetGeneratorException(MessageProvider, generatorState, sourceGenerator, ex, diagnosticsBag, isInit: true); } // if the pipeline registered any syntax input nodes, record them if (!generatorState.InputNodes.IsEmpty) { syntaxInputNodes.AddRange(generatorState.InputNodes); } // record any constant sources if (generatorState.Exception is null && generatorState.PostInitTrees.Length > 0) { constantSourcesBuilder.AddRange(generatorState.PostInitTrees.Select(t => t.Tree)); } stateBuilder.Add(generatorState); } // update the compilation with any constant sources if (constantSourcesBuilder.Count > 0) { compilation = compilation.AddSyntaxTrees(constantSourcesBuilder); } constantSourcesBuilder.Free(); var driverStateBuilder = new DriverStateTable.Builder(compilation, _state, syntaxInputNodes.ToImmutableAndFree(), cancellationToken); for (int i = 0; i < state.IncrementalGenerators.Length; i++) { var generatorState = stateBuilder[i]; if (generatorState.Exception is object) { continue; } using var generatorTimer = CodeAnalysisEventSource.Log.CreateSingleGeneratorRunTimer(state.Generators[i]); try { var context = UpdateOutputs(generatorState.OutputNodes, IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation, cancellationToken, driverStateBuilder); (var sources, var generatorDiagnostics) = context.ToImmutableAndFree(); generatorDiagnostics = FilterDiagnostics(compilation, generatorDiagnostics, driverDiagnostics: diagnosticsBag, cancellationToken); stateBuilder[i] = new GeneratorState(generatorState.Info, generatorState.PostInitTrees, generatorState.InputNodes, generatorState.OutputNodes, ParseAdditionalSources(state.Generators[i], sources, cancellationToken), generatorDiagnostics, generatorTimer.Elapsed); } catch (UserFunctionException ufe) { stateBuilder[i] = SetGeneratorException(MessageProvider, stateBuilder[i], state.Generators[i], ufe.InnerException, diagnosticsBag, generatorTimer.Elapsed); } } state = state.With(stateTable: driverStateBuilder.ToImmutable(), generatorStates: stateBuilder.ToImmutableAndFree(), runTime: timer.Elapsed); return state; } private IncrementalExecutionContext UpdateOutputs(ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, IncrementalGeneratorOutputKind outputKind, CancellationToken cancellationToken, DriverStateTable.Builder? driverStateBuilder = null) { Debug.Assert(outputKind != IncrementalGeneratorOutputKind.None); IncrementalExecutionContext context = new IncrementalExecutionContext(driverStateBuilder, new AdditionalSourcesCollection(SourceExtension)); foreach (var outputNode in outputNodes) { // if we're looking for this output kind, and it has not been explicitly disabled if (outputKind.HasFlag(outputNode.Kind) && !_state.DisabledOutputs.HasFlag(outputNode.Kind)) { outputNode.AppendOutputs(context, cancellationToken); } } return context; } private ImmutableArray<GeneratedSyntaxTree> ParseAdditionalSources(ISourceGenerator generator, ImmutableArray<GeneratedSourceText> generatedSources, CancellationToken cancellationToken) { var trees = ArrayBuilder<GeneratedSyntaxTree>.GetInstance(generatedSources.Length); var type = generator.GetGeneratorType(); var prefix = GetFilePathPrefixForGenerator(generator); foreach (var source in generatedSources) { var tree = ParseGeneratedSourceText(source, Path.Combine(prefix, source.HintName), cancellationToken); trees.Add(new GeneratedSyntaxTree(source.HintName, source.Text, tree)); } return trees.ToImmutableAndFree(); } private static GeneratorState SetGeneratorException(CommonMessageProvider provider, GeneratorState generatorState, ISourceGenerator generator, Exception e, DiagnosticBag? diagnosticBag, TimeSpan? runTime = null, bool isInit = false) { var errorCode = isInit ? provider.WRN_GeneratorFailedDuringInitialization : provider.WRN_GeneratorFailedDuringGeneration; // ISSUE: Diagnostics don't currently allow descriptions with arguments, so we have to manually create the diagnostic description // ISSUE: Exceptions also don't support IFormattable, so will always be in the current UI Culture. // ISSUE: See https://github.com/dotnet/roslyn/issues/46939 var description = string.Format(provider.GetDescription(errorCode).ToString(CultureInfo.CurrentUICulture), e); var descriptor = new DiagnosticDescriptor( provider.GetIdForErrorCode(errorCode), provider.GetTitle(errorCode), provider.GetMessageFormat(errorCode), description: description, category: "Compiler", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: WellKnownDiagnosticTags.AnalyzerException); var diagnostic = Diagnostic.Create(descriptor, Location.None, generator.GetGeneratorType().Name, e.GetType().Name, e.Message); diagnosticBag?.Add(diagnostic); return new GeneratorState(generatorState.Info, e, diagnostic, runTime ?? TimeSpan.Zero); } private static ImmutableArray<Diagnostic> FilterDiagnostics(Compilation compilation, ImmutableArray<Diagnostic> generatorDiagnostics, DiagnosticBag? driverDiagnostics, CancellationToken cancellationToken) { ArrayBuilder<Diagnostic> filteredDiagnostics = ArrayBuilder<Diagnostic>.GetInstance(); foreach (var diag in generatorDiagnostics) { var filtered = compilation.Options.FilterDiagnostic(diag, cancellationToken); if (filtered is object) { filteredDiagnostics.Add(filtered); driverDiagnostics?.Add(filtered); } } return filteredDiagnostics.ToImmutableAndFree(); } internal static string GetFilePathPrefixForGenerator(ISourceGenerator generator) { var type = generator.GetGeneratorType(); return Path.Combine(type.Assembly.GetName().Name ?? string.Empty, type.FullName!); } private static (ImmutableArray<ISourceGenerator>, ImmutableArray<IIncrementalGenerator>) GetIncrementalGenerators(ImmutableArray<ISourceGenerator> generators, string sourceExtension) { return (generators, generators.SelectAsArray(g => g switch { IncrementalGeneratorWrapper igw => igw.Generator, IIncrementalGenerator ig => ig, _ => new SourceGeneratorAdaptor(g, sourceExtension) })); } internal abstract CommonMessageProvider MessageProvider { get; } internal abstract GeneratorDriver FromState(GeneratorDriverState state); internal abstract SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken); internal abstract string SourceExtension { get; } } }
1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/SourceGeneration/GeneratorDriverState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis { internal readonly struct GeneratorDriverState { internal GeneratorDriverState(ParseOptions parseOptions, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<ISourceGenerator> sourceGenerators, ImmutableArray<IIncrementalGenerator> incrementalGenerators, ImmutableArray<AdditionalText> additionalTexts, ImmutableArray<GeneratorState> generatorStates, DriverStateTable stateTable, IncrementalGeneratorOutputKind disabledOutputs) { Generators = sourceGenerators; IncrementalGenerators = incrementalGenerators; GeneratorStates = generatorStates; AdditionalTexts = additionalTexts; ParseOptions = parseOptions; OptionsProvider = optionsProvider; StateTable = stateTable; DisabledOutputs = disabledOutputs; Debug.Assert(Generators.Length == GeneratorStates.Length); Debug.Assert(IncrementalGenerators.Length == GeneratorStates.Length); } /// <summary> /// The set of <see cref="ISourceGenerator"/>s associated with this state. /// </summary> /// <remarks> /// This is the set of generators that will run on next generation. /// If there are any states present in <see cref="GeneratorStates" />, they were produced by a subset of these generators. /// </remarks> internal readonly ImmutableArray<ISourceGenerator> Generators; /// <summary> /// The set of <see cref="IIncrementalGenerator"/>s associated with this state. /// </summary> /// <remarks> /// This is the 'internal' representation of the <see cref="Generators"/> collection. There is a 1-to-1 mapping /// where each entry is either the unwrapped incremental generator or a wrapped <see cref="ISourceGenerator"/> /// </remarks> internal readonly ImmutableArray<IIncrementalGenerator> IncrementalGenerators; /// <summary> /// The last run state of each generator, by the generator that created it /// </summary> /// <remarks> /// There will be a 1-to-1 mapping for each generator. If a generator has yet to /// be initialized or failed during initialization it's state will be <c>default(GeneratorState)</c> /// </remarks> internal readonly ImmutableArray<GeneratorState> GeneratorStates; /// <summary> /// The set of <see cref="AdditionalText"/>s available to source generators during a run /// </summary> internal readonly ImmutableArray<AdditionalText> AdditionalTexts; /// <summary> /// Gets a provider for analyzer options /// </summary> internal readonly AnalyzerConfigOptionsProvider OptionsProvider; /// <summary> /// ParseOptions to use when parsing generator provided source. /// </summary> internal readonly ParseOptions ParseOptions; internal readonly DriverStateTable StateTable; /// <summary> /// A bit field containing the output kinds that should not be produced by this generator driver. /// </summary> internal readonly IncrementalGeneratorOutputKind DisabledOutputs; internal GeneratorDriverState With( ImmutableArray<ISourceGenerator>? sourceGenerators = null, ImmutableArray<IIncrementalGenerator>? incrementalGenerators = null, ImmutableArray<GeneratorState>? generatorStates = null, ImmutableArray<AdditionalText>? additionalTexts = null, DriverStateTable? stateTable = null, ParseOptions? parseOptions = null, AnalyzerConfigOptionsProvider? optionsProvider = null, IncrementalGeneratorOutputKind? disabledOutputs = null) { return new GeneratorDriverState( parseOptions ?? this.ParseOptions, optionsProvider ?? this.OptionsProvider, sourceGenerators ?? this.Generators, incrementalGenerators ?? this.IncrementalGenerators, additionalTexts ?? this.AdditionalTexts, generatorStates ?? this.GeneratorStates, stateTable ?? this.StateTable, disabledOutputs ?? this.DisabledOutputs ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis { internal readonly struct GeneratorDriverState { internal GeneratorDriverState(ParseOptions parseOptions, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<ISourceGenerator> sourceGenerators, ImmutableArray<IIncrementalGenerator> incrementalGenerators, ImmutableArray<AdditionalText> additionalTexts, ImmutableArray<GeneratorState> generatorStates, DriverStateTable stateTable, IncrementalGeneratorOutputKind disabledOutputs, TimeSpan runtime) { Generators = sourceGenerators; IncrementalGenerators = incrementalGenerators; GeneratorStates = generatorStates; AdditionalTexts = additionalTexts; ParseOptions = parseOptions; OptionsProvider = optionsProvider; StateTable = stateTable; DisabledOutputs = disabledOutputs; RunTime = runtime; Debug.Assert(Generators.Length == GeneratorStates.Length); Debug.Assert(IncrementalGenerators.Length == GeneratorStates.Length); } /// <summary> /// The set of <see cref="ISourceGenerator"/>s associated with this state. /// </summary> /// <remarks> /// This is the set of generators that will run on next generation. /// If there are any states present in <see cref="GeneratorStates" />, they were produced by a subset of these generators. /// </remarks> internal readonly ImmutableArray<ISourceGenerator> Generators; /// <summary> /// The set of <see cref="IIncrementalGenerator"/>s associated with this state. /// </summary> /// <remarks> /// This is the 'internal' representation of the <see cref="Generators"/> collection. There is a 1-to-1 mapping /// where each entry is either the unwrapped incremental generator or a wrapped <see cref="ISourceGenerator"/> /// </remarks> internal readonly ImmutableArray<IIncrementalGenerator> IncrementalGenerators; /// <summary> /// The last run state of each generator, by the generator that created it /// </summary> /// <remarks> /// There will be a 1-to-1 mapping for each generator. If a generator has yet to /// be initialized or failed during initialization it's state will be <c>default(GeneratorState)</c> /// </remarks> internal readonly ImmutableArray<GeneratorState> GeneratorStates; /// <summary> /// The set of <see cref="AdditionalText"/>s available to source generators during a run /// </summary> internal readonly ImmutableArray<AdditionalText> AdditionalTexts; /// <summary> /// Gets a provider for analyzer options /// </summary> internal readonly AnalyzerConfigOptionsProvider OptionsProvider; /// <summary> /// ParseOptions to use when parsing generator provided source. /// </summary> internal readonly ParseOptions ParseOptions; internal readonly DriverStateTable StateTable; /// <summary> /// A bit field containing the output kinds that should not be produced by this generator driver. /// </summary> internal readonly IncrementalGeneratorOutputKind DisabledOutputs; internal readonly TimeSpan RunTime; internal GeneratorDriverState With( ImmutableArray<ISourceGenerator>? sourceGenerators = null, ImmutableArray<IIncrementalGenerator>? incrementalGenerators = null, ImmutableArray<GeneratorState>? generatorStates = null, ImmutableArray<AdditionalText>? additionalTexts = null, DriverStateTable? stateTable = null, ParseOptions? parseOptions = null, AnalyzerConfigOptionsProvider? optionsProvider = null, IncrementalGeneratorOutputKind? disabledOutputs = null, TimeSpan? runTime = null) { return new GeneratorDriverState( parseOptions ?? this.ParseOptions, optionsProvider ?? this.OptionsProvider, sourceGenerators ?? this.Generators, incrementalGenerators ?? this.IncrementalGenerators, additionalTexts ?? this.AdditionalTexts, generatorStates ?? this.GeneratorStates, stateTable ?? this.StateTable, disabledOutputs ?? this.DisabledOutputs, runTime ?? this.RunTime ); } } }
1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/SourceGeneration/GeneratorState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents the current state of a generator /// </summary> internal readonly struct GeneratorState { /// <summary> /// Creates a new generator state that just contains information /// </summary> public GeneratorState(GeneratorInfo info) : this(info, ImmutableArray<GeneratedSyntaxTree>.Empty) { } /// <summary> /// Creates a new generator state that contains information and constant trees /// </summary> public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees) : this(info, postInitTrees, ImmutableArray<ISyntaxInputNode>.Empty, ImmutableArray<IIncrementalGeneratorOutputNode>.Empty) { } /// <summary> /// Creates a new generator state that contains information, constant trees and an execution pipeline /// </summary> public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes) : this(info, postInitTrees, inputNodes, outputNodes, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray<Diagnostic>.Empty, exception: null) { } /// <summary> /// Creates a new generator state that contains an exception and the associated diagnostic /// </summary> public GeneratorState(GeneratorInfo info, Exception e, Diagnostic error) : this(info, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray<ISyntaxInputNode>.Empty, ImmutableArray<IIncrementalGeneratorOutputNode>.Empty, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray.Create(error), exception: e) { } /// <summary> /// Creates a generator state that contains results /// </summary> public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, ImmutableArray<GeneratedSyntaxTree> generatedTrees, ImmutableArray<Diagnostic> diagnostics) : this(info, postInitTrees, inputNodes, outputNodes, generatedTrees, diagnostics, exception: null) { } private GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, ImmutableArray<GeneratedSyntaxTree> generatedTrees, ImmutableArray<Diagnostic> diagnostics, Exception? exception) { this.Initialized = true; this.PostInitTrees = postInitTrees; this.InputNodes = inputNodes; this.OutputNodes = outputNodes; this.GeneratedTrees = generatedTrees; this.Info = info; this.Diagnostics = diagnostics; this.Exception = exception; } internal bool Initialized { get; } internal ImmutableArray<GeneratedSyntaxTree> PostInitTrees { get; } internal ImmutableArray<ISyntaxInputNode> InputNodes { get; } internal ImmutableArray<IIncrementalGeneratorOutputNode> OutputNodes { get; } internal ImmutableArray<GeneratedSyntaxTree> GeneratedTrees { get; } internal GeneratorInfo Info { get; } internal Exception? Exception { get; } internal ImmutableArray<Diagnostic> Diagnostics { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents the current state of a generator /// </summary> internal readonly struct GeneratorState { /// <summary> /// Creates a new generator state that just contains information /// </summary> public GeneratorState(GeneratorInfo info) : this(info, ImmutableArray<GeneratedSyntaxTree>.Empty) { } /// <summary> /// Creates a new generator state that contains information and constant trees /// </summary> public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees) : this(info, postInitTrees, ImmutableArray<ISyntaxInputNode>.Empty, ImmutableArray<IIncrementalGeneratorOutputNode>.Empty) { } /// <summary> /// Creates a new generator state that contains information, constant trees and an execution pipeline /// </summary> public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes) : this(info, postInitTrees, inputNodes, outputNodes, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray<Diagnostic>.Empty, exception: null, elapsedTime: TimeSpan.Zero) { } /// <summary> /// Creates a new generator state that contains an exception and the associated diagnostic /// </summary> public GeneratorState(GeneratorInfo info, Exception e, Diagnostic error, TimeSpan elapsedTime) : this(info, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray<ISyntaxInputNode>.Empty, ImmutableArray<IIncrementalGeneratorOutputNode>.Empty, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray.Create(error), exception: e, elapsedTime) { } /// <summary> /// Creates a generator state that contains results /// </summary> public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, ImmutableArray<GeneratedSyntaxTree> generatedTrees, ImmutableArray<Diagnostic> diagnostics, TimeSpan elapsedTime) : this(info, postInitTrees, inputNodes, outputNodes, generatedTrees, diagnostics, exception: null, elapsedTime) { } private GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, ImmutableArray<GeneratedSyntaxTree> generatedTrees, ImmutableArray<Diagnostic> diagnostics, Exception? exception, TimeSpan elapsedTime) { this.Initialized = true; this.PostInitTrees = postInitTrees; this.InputNodes = inputNodes; this.OutputNodes = outputNodes; this.GeneratedTrees = generatedTrees; this.Info = info; this.Diagnostics = diagnostics; this.Exception = exception; this.ElapsedTime = elapsedTime; } internal bool Initialized { get; } internal ImmutableArray<GeneratedSyntaxTree> PostInitTrees { get; } internal ImmutableArray<ISyntaxInputNode> InputNodes { get; } internal ImmutableArray<IIncrementalGeneratorOutputNode> OutputNodes { get; } internal ImmutableArray<GeneratedSyntaxTree> GeneratedTrees { get; } internal GeneratorInfo Info { get; } internal Exception? Exception { get; } internal TimeSpan ElapsedTime { get; } internal ImmutableArray<Diagnostic> Diagnostics { get; } } }
1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/SourceGeneration/RunResults.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents the results of running a generation pass over a set of <see cref="ISourceGenerator"/>s. /// </summary> public class GeneratorDriverRunResult { private ImmutableArray<Diagnostic> _lazyDiagnostics; private ImmutableArray<SyntaxTree> _lazyGeneratedTrees; internal GeneratorDriverRunResult(ImmutableArray<GeneratorRunResult> results) { this.Results = results; } /// <summary> /// The individual result of each <see cref="ISourceGenerator"/> that was run in this generator pass, one per generator. /// </summary> public ImmutableArray<GeneratorRunResult> Results { get; } /// <summary> /// The <see cref="Diagnostic"/>s produced by all generators run during this generation pass. /// </summary> /// <remarks> /// This is equivalent to the union of all <see cref="GeneratorRunResult.Diagnostics"/> in <see cref="Results"/>. /// </remarks> public ImmutableArray<Diagnostic> Diagnostics { get { if (_lazyDiagnostics.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyDiagnostics, Results.SelectMany(r => r.Diagnostics).ToImmutableArray()); } return _lazyDiagnostics; } } /// <summary> /// The <see cref="SyntaxTree"/>s produced during this generation pass by parsing each <see cref="SourceText"/> added by each generator. /// </summary> /// <remarks> /// This is equivalent to the union of all <see cref="GeneratedSourceResult.SyntaxTree"/>s in each <see cref="GeneratorRunResult.GeneratedSources"/> in each <see cref="Results"/> /// </remarks> public ImmutableArray<SyntaxTree> GeneratedTrees { get { if (_lazyGeneratedTrees.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyGeneratedTrees, Results.SelectMany(r => r.GeneratedSources.Select(g => g.SyntaxTree)).ToImmutableArray()); } return _lazyGeneratedTrees; } } } /// <summary> /// Represents the results of a single <see cref="ISourceGenerator"/> generation pass. /// </summary> public readonly struct GeneratorRunResult { internal GeneratorRunResult(ISourceGenerator generator, ImmutableArray<GeneratedSourceResult> generatedSources, ImmutableArray<Diagnostic> diagnostics, Exception? exception) { Debug.Assert(exception is null || (generatedSources.IsEmpty && diagnostics.Length == 1)); this.Generator = generator; this.GeneratedSources = generatedSources; this.Diagnostics = diagnostics; this.Exception = exception; } /// <summary> /// The <see cref="ISourceGenerator"/> that produced this result. /// </summary> public ISourceGenerator Generator { get; } /// <summary> /// The sources that were added by <see cref="Generator"/> during the generation pass this result represents. /// </summary> public ImmutableArray<GeneratedSourceResult> GeneratedSources { get; } /// <summary> /// A collection of <see cref="Diagnostic"/>s reported by <see cref="Generator"/> /// </summary> /// <remarks> /// When generation fails due to an <see cref="Exception"/> being thrown, a single diagnostic is added /// to represent the failure. Any generator reported diagnostics up to the failure point are not included. /// </remarks> public ImmutableArray<Diagnostic> Diagnostics { get; } /// <summary> /// An <see cref="System.Exception"/> instance that was thrown by the generator, or <c>null</c> if the generator completed without error. /// </summary> /// <remarks> /// When this property has a value, <see cref="GeneratedSources"/> property is guaranteed to be empty, and the <see cref="Diagnostics"/> /// collection will contain a single diagnostic indicating that the generator failed. /// </remarks> public Exception? Exception { get; } } /// <summary> /// Represents the results of an <see cref="ISourceGenerator"/> calling <see cref="GeneratorExecutionContext.AddSource(string, SourceText)"/>. /// </summary> /// <remarks> /// This contains the original <see cref="SourceText"/> added by the generator, along with the parsed representation of that text in <see cref="SyntaxTree"/>. /// </remarks> public readonly struct GeneratedSourceResult { internal GeneratedSourceResult(SyntaxTree tree, SourceText text, string hintName) { this.SyntaxTree = tree; this.SourceText = text; this.HintName = hintName; } /// <summary> /// The <see cref="SyntaxTree"/> that was produced from parsing the <see cref="GeneratedSourceResult.SourceText"/>. /// </summary> public SyntaxTree SyntaxTree { get; } /// <summary> /// The <see cref="SourceText"/> that was added by the generator. /// </summary> public SourceText SourceText { get; } /// <summary> /// An identifier provided by the generator that identifies the added <see cref="SourceText"/>. /// </summary> public string HintName { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents the results of running a generation pass over a set of <see cref="ISourceGenerator"/>s. /// </summary> public class GeneratorDriverRunResult { private ImmutableArray<Diagnostic> _lazyDiagnostics; private ImmutableArray<SyntaxTree> _lazyGeneratedTrees; internal GeneratorDriverRunResult(ImmutableArray<GeneratorRunResult> results, TimeSpan elapsedTime) { this.Results = results; ElapsedTime = elapsedTime; } /// <summary> /// The individual result of each <see cref="ISourceGenerator"/> that was run in this generator pass, one per generator. /// </summary> public ImmutableArray<GeneratorRunResult> Results { get; } /// <summary> /// The wall clock time that this generator pass took to execute. /// </summary> internal TimeSpan ElapsedTime { get; } /// <summary> /// The <see cref="Diagnostic"/>s produced by all generators run during this generation pass. /// </summary> /// <remarks> /// This is equivalent to the union of all <see cref="GeneratorRunResult.Diagnostics"/> in <see cref="Results"/>. /// </remarks> public ImmutableArray<Diagnostic> Diagnostics { get { if (_lazyDiagnostics.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyDiagnostics, Results.SelectMany(r => r.Diagnostics).ToImmutableArray()); } return _lazyDiagnostics; } } /// <summary> /// The <see cref="SyntaxTree"/>s produced during this generation pass by parsing each <see cref="SourceText"/> added by each generator. /// </summary> /// <remarks> /// This is equivalent to the union of all <see cref="GeneratedSourceResult.SyntaxTree"/>s in each <see cref="GeneratorRunResult.GeneratedSources"/> in each <see cref="Results"/> /// </remarks> public ImmutableArray<SyntaxTree> GeneratedTrees { get { if (_lazyGeneratedTrees.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyGeneratedTrees, Results.SelectMany(r => r.GeneratedSources.Select(g => g.SyntaxTree)).ToImmutableArray()); } return _lazyGeneratedTrees; } } } /// <summary> /// Represents the results of a single <see cref="ISourceGenerator"/> generation pass. /// </summary> public readonly struct GeneratorRunResult { internal GeneratorRunResult(ISourceGenerator generator, ImmutableArray<GeneratedSourceResult> generatedSources, ImmutableArray<Diagnostic> diagnostics, Exception? exception, TimeSpan elapsedTime) { Debug.Assert(exception is null || (generatedSources.IsEmpty && diagnostics.Length == 1)); this.Generator = generator; this.GeneratedSources = generatedSources; this.Diagnostics = diagnostics; this.Exception = exception; this.ElapsedTime = elapsedTime; } /// <summary> /// The <see cref="ISourceGenerator"/> that produced this result. /// </summary> public ISourceGenerator Generator { get; } /// <summary> /// The sources that were added by <see cref="Generator"/> during the generation pass this result represents. /// </summary> public ImmutableArray<GeneratedSourceResult> GeneratedSources { get; } /// <summary> /// A collection of <see cref="Diagnostic"/>s reported by <see cref="Generator"/> /// </summary> /// <remarks> /// When generation fails due to an <see cref="Exception"/> being thrown, a single diagnostic is added /// to represent the failure. Any generator reported diagnostics up to the failure point are not included. /// </remarks> public ImmutableArray<Diagnostic> Diagnostics { get; } /// <summary> /// An <see cref="System.Exception"/> instance that was thrown by the generator, or <c>null</c> if the generator completed without error. /// </summary> /// <remarks> /// When this property has a value, <see cref="GeneratedSources"/> property is guaranteed to be empty, and the <see cref="Diagnostics"/> /// collection will contain a single diagnostic indicating that the generator failed. /// </remarks> public Exception? Exception { get; } /// <summary> /// The wall clock time that elapsed while this generator was running. /// </summary> internal TimeSpan ElapsedTime { get; } } /// <summary> /// Represents the results of an <see cref="ISourceGenerator"/> calling <see cref="GeneratorExecutionContext.AddSource(string, SourceText)"/>. /// </summary> /// <remarks> /// This contains the original <see cref="SourceText"/> added by the generator, along with the parsed representation of that text in <see cref="SyntaxTree"/>. /// </remarks> public readonly struct GeneratedSourceResult { internal GeneratedSourceResult(SyntaxTree tree, SourceText text, string hintName) { this.SyntaxTree = tree; this.SourceText = text; this.HintName = hintName; } /// <summary> /// The <see cref="SyntaxTree"/> that was produced from parsing the <see cref="GeneratedSourceResult.SourceText"/>. /// </summary> public SyntaxTree SyntaxTree { get; } /// <summary> /// The <see cref="SourceText"/> that was added by the generator. /// </summary> public SourceText SourceText { get; } /// <summary> /// An identifier provided by the generator that identifies the added <see cref="SourceText"/>. /// </summary> public string HintName { get; } } }
1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Server/VBCSCompiler/NamedPipeClientConnection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Runtime.CompilerServices; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using System.Security.AccessControl; namespace Microsoft.CodeAnalysis.CompilerServer { internal sealed class NamedPipeClientConnection : IClientConnection { private CancellationTokenSource DisconnectCancellationTokenSource { get; } = new CancellationTokenSource(); private TaskCompletionSource<object> DisconnectTaskCompletionSource { get; } = new TaskCompletionSource<object>(); public NamedPipeServerStream Stream { get; } public ICompilerServerLogger Logger { get; } public bool IsDisposed { get; private set; } public Task DisconnectTask => DisconnectTaskCompletionSource.Task; internal NamedPipeClientConnection(NamedPipeServerStream stream, ICompilerServerLogger logger) { Stream = stream; Logger = logger; } public void Dispose() { if (!IsDisposed) { try { DisconnectTaskCompletionSource.TrySetResult(new object()); DisconnectCancellationTokenSource.Cancel(); Stream.Close(); } catch (Exception ex) { Logger.LogException(ex, $"Error closing client connection"); } IsDisposed = true; } } public async Task<BuildRequest> ReadBuildRequestAsync(CancellationToken cancellationToken) { var request = await BuildRequest.ReadAsync(Stream, cancellationToken).ConfigureAwait(false); // Now that we've read data from the stream we can validate the identity. if (!NamedPipeUtil.CheckClientElevationMatches(Stream)) { throw new Exception("Client identity does not match server identity."); } // The result is deliberately discarded here. The idea is to kick off the monitor code and // when it completes it will trigger the task. Don't want to block on that here. _ = MonitorDisconnect(); return request; async Task MonitorDisconnect() { try { await BuildServerConnection.MonitorDisconnectAsync(Stream, request.RequestId, Logger, DisconnectCancellationTokenSource.Token).ConfigureAwait(false); } catch (Exception ex) { Logger.LogException(ex, $"Error monitoring disconnect {request.RequestId}"); } finally { DisconnectTaskCompletionSource.TrySetResult(this); } } } public Task WriteBuildResponseAsync(BuildResponse response, CancellationToken cancellationToken) => response.WriteAsync(Stream, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Runtime.CompilerServices; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using System.Security.AccessControl; namespace Microsoft.CodeAnalysis.CompilerServer { internal sealed class NamedPipeClientConnection : IClientConnection { private CancellationTokenSource DisconnectCancellationTokenSource { get; } = new CancellationTokenSource(); private TaskCompletionSource<object> DisconnectTaskCompletionSource { get; } = new TaskCompletionSource<object>(); public NamedPipeServerStream Stream { get; } public ICompilerServerLogger Logger { get; } public bool IsDisposed { get; private set; } public Task DisconnectTask => DisconnectTaskCompletionSource.Task; internal NamedPipeClientConnection(NamedPipeServerStream stream, ICompilerServerLogger logger) { Stream = stream; Logger = logger; } public void Dispose() { if (!IsDisposed) { try { DisconnectTaskCompletionSource.TrySetResult(new object()); DisconnectCancellationTokenSource.Cancel(); Stream.Close(); } catch (Exception ex) { Logger.LogException(ex, $"Error closing client connection"); } IsDisposed = true; } } public async Task<BuildRequest> ReadBuildRequestAsync(CancellationToken cancellationToken) { var request = await BuildRequest.ReadAsync(Stream, cancellationToken).ConfigureAwait(false); // Now that we've read data from the stream we can validate the identity. if (!NamedPipeUtil.CheckClientElevationMatches(Stream)) { throw new Exception("Client identity does not match server identity."); } // The result is deliberately discarded here. The idea is to kick off the monitor code and // when it completes it will trigger the task. Don't want to block on that here. _ = MonitorDisconnect(); return request; async Task MonitorDisconnect() { try { await BuildServerConnection.MonitorDisconnectAsync(Stream, request.RequestId, Logger, DisconnectCancellationTokenSource.Token).ConfigureAwait(false); } catch (Exception ex) { Logger.LogException(ex, $"Error monitoring disconnect {request.RequestId}"); } finally { DisconnectTaskCompletionSource.TrySetResult(this); } } } public Task WriteBuildResponseAsync(BuildResponse response, CancellationToken cancellationToken) => response.WriteAsync(Stream, cancellationToken); } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpSemanticFactsServiceFactory.cs
// 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. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageServiceFactory(typeof(ISemanticFactsService), LanguageNames.CSharp), Shared] internal class CSharpSemanticFactsServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSemanticFactsServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => CSharpSemanticFactsService.Instance; } }
// 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. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageServiceFactory(typeof(ISemanticFactsService), LanguageNames.CSharp), Shared] internal class CSharpSemanticFactsServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSemanticFactsServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => CSharpSemanticFactsService.Instance; } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/FlowAnalysis/AbstractRegionControlFlowPass.cs
// 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. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class AbstractRegionControlFlowPass : ControlFlowPass { internal AbstractRegionControlFlowPass( CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) : base(compilation, member, node, firstInRegion, lastInRegion) { } public override BoundNode Visit(BoundNode node) { VisitAlways(node); return null; } // Control flow analysis does not normally scan the body of a lambda, but region analysis does. public override BoundNode VisitLambda(BoundLambda node) { var oldPending = SavePending(); // We do not support branches *into* a lambda. LocalState finalState = this.State; this.State = TopState(); var oldPending2 = SavePending(); VisitAlways(node.Body); RestorePending(oldPending2); // process any forward branches within the lambda body ImmutableArray<PendingBranch> pendingReturns = RemoveReturns(); RestorePending(oldPending); Join(ref finalState, ref this.State); foreach (PendingBranch returnBranch in pendingReturns) { this.State = returnBranch.State; Join(ref finalState, ref this.State); } this.State = finalState; return null; } } }
// 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. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class AbstractRegionControlFlowPass : ControlFlowPass { internal AbstractRegionControlFlowPass( CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) : base(compilation, member, node, firstInRegion, lastInRegion) { } public override BoundNode Visit(BoundNode node) { VisitAlways(node); return null; } // Control flow analysis does not normally scan the body of a lambda, but region analysis does. public override BoundNode VisitLambda(BoundLambda node) { var oldPending = SavePending(); // We do not support branches *into* a lambda. LocalState finalState = this.State; this.State = TopState(); var oldPending2 = SavePending(); VisitAlways(node.Body); RestorePending(oldPending2); // process any forward branches within the lambda body ImmutableArray<PendingBranch> pendingReturns = RemoveReturns(); RestorePending(oldPending); Join(ref finalState, ref this.State); foreach (PendingBranch returnBranch in pendingReturns) { this.State = returnBranch.State; Join(ref finalState, ref this.State); } this.State = finalState; return null; } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/TestUtilities/Async/Checkpoint.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Roslyn.Test.Utilities { public class Checkpoint { private readonly TaskCompletionSource<object> _tcs = new TaskCompletionSource<object>(); public Task Task => _tcs.Task; public void Release() => _tcs.SetResult(null); } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Roslyn.Test.Utilities { public class Checkpoint { private readonly TaskCompletionSource<object> _tcs = new TaskCompletionSource<object>(); public Task Task => _tcs.Task; public void Release() => _tcs.SetResult(null); } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/CSharp/Portable/CodeFixes/RemoveNewModifier/RemoveNewModifierCodeFixProvider.cs
// 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. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.RemoveNewModifier { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveNew), Shared] internal class RemoveNewModifierCodeFixProvider : CodeFixProvider { private const string CS0109 = nameof(CS0109); // The member 'SomeClass.SomeMember' does not hide an accessible member. The new keyword is not required. [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public RemoveNewModifierCodeFixProvider() { } public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS0109); public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var diagnostic = context.Diagnostics.First(); var diagnosticSpan = diagnostic.Location.SourceSpan; var token = root.FindToken(diagnosticSpan.Start); var memberDeclarationSyntax = token.GetAncestor<MemberDeclarationSyntax>(); if (memberDeclarationSyntax == null) return; var generator = context.Document.GetRequiredLanguageService<SyntaxGenerator>(); if (!generator.GetModifiers(memberDeclarationSyntax).IsNew) return; context.RegisterCodeFix( new MyCodeAction(ct => FixAsync(context.Document, generator, memberDeclarationSyntax, ct)), context.Diagnostics); } private static async Task<Document> FixAsync( Document document, SyntaxGenerator generator, MemberDeclarationSyntax memberDeclaration, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return document.WithSyntaxRoot(root.ReplaceNode( memberDeclaration, generator.WithModifiers( memberDeclaration, generator.GetModifiers(memberDeclaration).WithIsNew(false)))); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Remove_new_modifier, createChangedDocument, CSharpFeaturesResources.Remove_new_modifier) { } } } }
// 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. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.RemoveNewModifier { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveNew), Shared] internal class RemoveNewModifierCodeFixProvider : CodeFixProvider { private const string CS0109 = nameof(CS0109); // The member 'SomeClass.SomeMember' does not hide an accessible member. The new keyword is not required. [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public RemoveNewModifierCodeFixProvider() { } public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS0109); public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var diagnostic = context.Diagnostics.First(); var diagnosticSpan = diagnostic.Location.SourceSpan; var token = root.FindToken(diagnosticSpan.Start); var memberDeclarationSyntax = token.GetAncestor<MemberDeclarationSyntax>(); if (memberDeclarationSyntax == null) return; var generator = context.Document.GetRequiredLanguageService<SyntaxGenerator>(); if (!generator.GetModifiers(memberDeclarationSyntax).IsNew) return; context.RegisterCodeFix( new MyCodeAction(ct => FixAsync(context.Document, generator, memberDeclarationSyntax, ct)), context.Diagnostics); } private static async Task<Document> FixAsync( Document document, SyntaxGenerator generator, MemberDeclarationSyntax memberDeclaration, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return document.WithSyntaxRoot(root.ReplaceNode( memberDeclaration, generator.WithModifiers( memberDeclaration, generator.GetModifiers(memberDeclaration).WithIsNew(false)))); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Remove_new_modifier, createChangedDocument, CSharpFeaturesResources.Remove_new_modifier) { } } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/Navigation/IDocumentNavigationService.cs
// 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. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Navigation { internal interface IDocumentNavigationService : IWorkspaceService { /// <summary> /// Determines whether it is possible to navigate to the given position in the specified document. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given position in the specified document. /// </summary> /// <remarks>Legal to call from any thread.</remarks> Task<bool> CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given line/offset in the specified document. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given virtual position in the specified document. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken); /// <summary> /// Navigates to the given position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken); /// <summary> /// Navigates to the given position in the specified document, opening it if necessary. /// </summary> Task<bool> TryNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken); /// <summary> /// Navigates to the given line/offset in the specified document, opening it if necessary. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken); /// <summary> /// Navigates to the given virtual position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken); } internal static class IDocumentNavigationServiceExtensions { /// <remarks>Only legal to call on the UI thread.</remarks> public static bool CanNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.CanNavigateToPosition(workspace, documentId, position, virtualSpace: 0, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options: null, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options, allowInvalidSpan: false, cancellationToken); /// <remarks>Legal to call from any thread.</remarks> public static Task<bool> TryNavigateToSpanAsync(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) => service.TryNavigateToSpanAsync(workspace, documentId, textSpan, options, allowInvalidSpan: false, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToLineAndOffset(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => service.TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options: null, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.TryNavigateToPosition(workspace, documentId, position, virtualSpace: 0, options: null, cancellationToken); } }
// 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. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Navigation { internal interface IDocumentNavigationService : IWorkspaceService { /// <summary> /// Determines whether it is possible to navigate to the given position in the specified document. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given position in the specified document. /// </summary> /// <remarks>Legal to call from any thread.</remarks> Task<bool> CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given line/offset in the specified document. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given virtual position in the specified document. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken); /// <summary> /// Navigates to the given position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken); /// <summary> /// Navigates to the given position in the specified document, opening it if necessary. /// </summary> Task<bool> TryNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken); /// <summary> /// Navigates to the given line/offset in the specified document, opening it if necessary. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken); /// <summary> /// Navigates to the given virtual position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken); } internal static class IDocumentNavigationServiceExtensions { /// <remarks>Only legal to call on the UI thread.</remarks> public static bool CanNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.CanNavigateToPosition(workspace, documentId, position, virtualSpace: 0, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options: null, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options, allowInvalidSpan: false, cancellationToken); /// <remarks>Legal to call from any thread.</remarks> public static Task<bool> TryNavigateToSpanAsync(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) => service.TryNavigateToSpanAsync(workspace, documentId, textSpan, options, allowInvalidSpan: false, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToLineAndOffset(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => service.TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options: null, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.TryNavigateToPosition(workspace, documentId, position, virtualSpace: 0, options: null, cancellationToken); } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/MetadataReferences/VisualStudioMetadataReferenceProviderServiceFactory.cs
// 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. #nullable disable using System; using System.Composition; using System.Diagnostics; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { [ExportWorkspaceServiceFactory(typeof(IMetadataService), ServiceLayer.Host), Shared] internal sealed class VsMetadataServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VsMetadataServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new Service(workspaceServices); private sealed class Service : IMetadataService { private readonly Lazy<VisualStudioMetadataReferenceManager> _manager; public Service(HostWorkspaceServices workspaceServices) { // We will defer creation of this reference manager until we have to to avoid it being constructed too // early and potentially causing deadlocks. We do initialize it on the UI thread in the // VisualStudioWorkspaceImpl.DeferredState constructor to ensure it gets created there. _manager = new Lazy<VisualStudioMetadataReferenceManager>( () => workspaceServices.GetRequiredService<VisualStudioMetadataReferenceManager>()); } public PortableExecutableReference GetReference(string resolvedPath, MetadataReferenceProperties properties) => _manager.Value.CreateMetadataReferenceSnapshot(resolvedPath, properties); } } }
// 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. #nullable disable using System; using System.Composition; using System.Diagnostics; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { [ExportWorkspaceServiceFactory(typeof(IMetadataService), ServiceLayer.Host), Shared] internal sealed class VsMetadataServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VsMetadataServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new Service(workspaceServices); private sealed class Service : IMetadataService { private readonly Lazy<VisualStudioMetadataReferenceManager> _manager; public Service(HostWorkspaceServices workspaceServices) { // We will defer creation of this reference manager until we have to to avoid it being constructed too // early and potentially causing deadlocks. We do initialize it on the UI thread in the // VisualStudioWorkspaceImpl.DeferredState constructor to ensure it gets created there. _manager = new Lazy<VisualStudioMetadataReferenceManager>( () => workspaceServices.GetRequiredService<VisualStudioMetadataReferenceManager>()); } public PortableExecutableReference GetReference(string resolvedPath, MetadataReferenceProperties properties) => _manager.Value.CreateMetadataReferenceSnapshot(resolvedPath, properties); } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/BatchFixAllProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Helper class for "Fix all occurrences" code fix providers. /// </summary> internal sealed class BatchFixAllProvider : FixAllProvider { public static readonly FixAllProvider Instance = new BatchFixAllProvider(); private BatchFixAllProvider() { } public override Task<CodeAction?> GetFixAsync(FixAllContext fixAllContext) => DefaultFixAllProviderHelpers.GetFixAsync( FixAllContextHelper.GetDefaultFixAllTitle(fixAllContext), fixAllContext, FixAllContextsAsync); private async Task<Solution?> FixAllContextsAsync( FixAllContext originalFixAllContext, ImmutableArray<FixAllContext> fixAllContexts) { var cancellationToken = originalFixAllContext.CancellationToken; var progressTracker = originalFixAllContext.GetProgressTracker(); progressTracker.Description = FixAllContextHelper.GetDefaultFixAllTitle(originalFixAllContext); // We have 2*P + 1 pieces of work. Computing diagnostics and fixes/changes per context, and then one pass // applying fixes. progressTracker.AddItems(fixAllContexts.Length * 2 + 1); // Mapping from document to the cumulative text changes created for that document. var docIdToTextMerger = new Dictionary<DocumentId, TextChangeMerger>(); // Process each context one at a time, allowing us to dump most of the information we computed for each once // done with it. The only information we need to preserve is the data we store in docIdToTextMerger foreach (var fixAllContext in fixAllContexts) { Contract.ThrowIfFalse(fixAllContext.Scope is FixAllScope.Document or FixAllScope.Project); await FixSingleContextAsync(fixAllContext, progressTracker, docIdToTextMerger).ConfigureAwait(false); } // Finally, merge in all text changes into the solution. We can't do this per-project as we have to have // process *all* diagnostics in the solution to find the changes made to all documents. using (progressTracker.ItemCompletedScope()) { if (docIdToTextMerger.Count == 0) return null; var currentSolution = originalFixAllContext.Solution; foreach (var group in docIdToTextMerger.GroupBy(kvp => kvp.Key.ProjectId)) currentSolution = await ApplyChangesAsync(currentSolution, group.SelectAsArray(kvp => (kvp.Key, kvp.Value)), cancellationToken).ConfigureAwait(false); return currentSolution; } } private static async Task FixSingleContextAsync( FixAllContext fixAllContext, IProgressTracker progressTracker, Dictionary<DocumentId, TextChangeMerger> docIdToTextMerger) { // First, determine the diagnostics to fix for that context. var documentToDiagnostics = await DetermineDiagnosticsAsync(fixAllContext, progressTracker).ConfigureAwait(false); // Second, process all those diagnostics, merging the cumulative set of text changes per document into docIdToTextMerger. await AddDocumentChangesAsync(fixAllContext, progressTracker, docIdToTextMerger, documentToDiagnostics).ConfigureAwait(false); } private static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> DetermineDiagnosticsAsync(FixAllContext fixAllContext, IProgressTracker progressTracker) { using var _ = progressTracker.ItemCompletedScope(); var documentToDiagnostics = await fixAllContext.GetDocumentDiagnosticsToFixAsync().ConfigureAwait(false); var filtered = documentToDiagnostics.Where(kvp => { if (kvp.Key.Project != fixAllContext.Project) return false; if (fixAllContext.Document != null && fixAllContext.Document != kvp.Key) return false; return true; }); return filtered.ToImmutableDictionary(); } private static async Task AddDocumentChangesAsync( FixAllContext fixAllContext, IProgressTracker progressTracker, Dictionary<DocumentId, TextChangeMerger> docIdToTextMerger, ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentToDiagnostics) { using var _ = progressTracker.ItemCompletedScope(); // First, order the diagnostics so we process them in a consistent manner and get the same results given the // same input solution. var orderedDiagnostics = documentToDiagnostics.SelectMany(kvp => kvp.Value) .Where(d => d.Location.IsInSource) .OrderBy(d => d.Location.SourceTree!.FilePath) .ThenBy(d => d.Location.SourceSpan.Start) .ToImmutableArray(); // Now determine all the document changes caused from these diagnostics. var allChangedDocumentsInDiagnosticsOrder = await GetAllChangedDocumentsInDiagnosticsOrderAsync(fixAllContext, orderedDiagnostics).ConfigureAwait(false); // Finally, take all the changes made to each document and merge them together into docIdToTextMerger to // keep track of the total set of changes to any particular document. await MergeTextChangesAsync(fixAllContext, allChangedDocumentsInDiagnosticsOrder, docIdToTextMerger).ConfigureAwait(false); } /// <summary> /// Returns all the changed documents produced by fixing the list of provided <paramref /// name="orderedDiagnostics"/>. The documents will be returned such that fixed documents for a later /// diagnostic will appear later than those for an earlier diagnostic. /// </summary> private static async Task<ImmutableArray<Document>> GetAllChangedDocumentsInDiagnosticsOrderAsync( FixAllContext fixAllContext, ImmutableArray<Diagnostic> orderedDiagnostics) { var solution = fixAllContext.Solution; var cancellationToken = fixAllContext.CancellationToken; // Process each diagnostic, determine the code actions to fix it, then figure out the document changes // produced by that code action. using var _1 = ArrayBuilder<Task<ImmutableArray<Document>>>.GetInstance(out var tasks); foreach (var diagnostic in orderedDiagnostics) { var document = solution.GetRequiredDocument(diagnostic.Location.SourceTree!); cancellationToken.ThrowIfCancellationRequested(); tasks.Add(Task.Run(async () => { // Create a context that will add the reported code actions into this using var _2 = ArrayBuilder<CodeAction>.GetInstance(out var codeActions); var context = new CodeFixContext(document, diagnostic, GetRegisterCodeFixAction(fixAllContext.CodeActionEquivalenceKey, codeActions), cancellationToken); // Wait for the all the code actions to be reported for this diagnostic. var registerTask = fixAllContext.CodeFixProvider.RegisterCodeFixesAsync(context) ?? Task.CompletedTask; await registerTask.ConfigureAwait(false); // Now, process each code action and find out all the document changes caused by it. using var _3 = ArrayBuilder<Document>.GetInstance(out var changedDocuments); foreach (var codeAction in codeActions) { var changedSolution = await codeAction.GetChangedSolutionInternalAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (changedSolution != null) { var changedDocumentIds = new SolutionChanges(changedSolution, solution).GetProjectChanges().SelectMany(p => p.GetChangedDocuments()); changedDocuments.AddRange(changedDocumentIds.Select(id => changedSolution.GetRequiredDocument(id))); } } return changedDocuments.ToImmutable(); }, cancellationToken)); } // Wait for all that work to finish. await Task.WhenAll(tasks).ConfigureAwait(false); // Flatten the set of changed documents. These will naturally still be ordered by the diagnostic that // caused the change. using var _4 = ArrayBuilder<Document>.GetInstance(out var result); foreach (var task in tasks) result.AddRange(await task.ConfigureAwait(false)); return result.ToImmutable(); } /// <summary> /// Take all the changes made to a particular document and determine the text changes caused by each one. Take /// those individual text changes and attempt to merge them together in order into <paramref /// name="docIdToTextMerger"/>. /// </summary> private static async Task MergeTextChangesAsync( FixAllContext fixAllContext, ImmutableArray<Document> allChangedDocumentsInDiagnosticsOrder, Dictionary<DocumentId, TextChangeMerger> docIdToTextMerger) { var cancellationToken = fixAllContext.CancellationToken; // Now for each document that is changed, grab all the documents it was changed to (remember, many code // actions might have touched that document). Figure out the actual change, and then add that to the // interval tree of changes we're keeping track of for that document. using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var group in allChangedDocumentsInDiagnosticsOrder.GroupBy(d => d.Id)) { var docId = group.Key; var allDocChanges = group.ToImmutableArray(); // If we don't have an text merger for this doc yet, create one to keep track of all the changes. if (!docIdToTextMerger.TryGetValue(docId, out var textMerger)) { var originalDocument = fixAllContext.Solution.GetRequiredDocument(docId); textMerger = new TextChangeMerger(originalDocument); docIdToTextMerger.Add(docId, textMerger); } // Process all document groups in parallel. For each group, merge all the doc changes into an // aggregated set of changes in the TextChangeMerger type. tasks.Add(Task.Run( async () => await textMerger.TryMergeChangesAsync(allDocChanges, cancellationToken).ConfigureAwait(false), cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); } private static Action<CodeAction, ImmutableArray<Diagnostic>> GetRegisterCodeFixAction( string? codeActionEquivalenceKey, ArrayBuilder<CodeAction> codeActions) { return (action, diagnostics) => { using var _ = ArrayBuilder<CodeAction>.GetInstance(out var builder); builder.Push(action); while (builder.Count > 0) { var currentAction = builder.Pop(); if (currentAction is { EquivalenceKey: var equivalenceKey } && codeActionEquivalenceKey == equivalenceKey) { lock (codeActions) codeActions.Add(currentAction); } foreach (var nestedAction in currentAction.NestedCodeActions) builder.Push(nestedAction); } }; } private static async Task<Solution> ApplyChangesAsync( Solution currentSolution, ImmutableArray<(DocumentId, TextChangeMerger)> docIdsAndMerger, CancellationToken cancellationToken) { foreach (var (documentId, textMerger) in docIdsAndMerger) { var newText = await textMerger.GetFinalMergedTextAsync(cancellationToken).ConfigureAwait(false); currentSolution = currentSolution.WithDocumentText(documentId, newText); } return currentSolution; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Helper class for "Fix all occurrences" code fix providers. /// </summary> internal sealed class BatchFixAllProvider : FixAllProvider { public static readonly FixAllProvider Instance = new BatchFixAllProvider(); private BatchFixAllProvider() { } public override Task<CodeAction?> GetFixAsync(FixAllContext fixAllContext) => DefaultFixAllProviderHelpers.GetFixAsync( FixAllContextHelper.GetDefaultFixAllTitle(fixAllContext), fixAllContext, FixAllContextsAsync); private async Task<Solution?> FixAllContextsAsync( FixAllContext originalFixAllContext, ImmutableArray<FixAllContext> fixAllContexts) { var cancellationToken = originalFixAllContext.CancellationToken; var progressTracker = originalFixAllContext.GetProgressTracker(); progressTracker.Description = FixAllContextHelper.GetDefaultFixAllTitle(originalFixAllContext); // We have 2*P + 1 pieces of work. Computing diagnostics and fixes/changes per context, and then one pass // applying fixes. progressTracker.AddItems(fixAllContexts.Length * 2 + 1); // Mapping from document to the cumulative text changes created for that document. var docIdToTextMerger = new Dictionary<DocumentId, TextChangeMerger>(); // Process each context one at a time, allowing us to dump most of the information we computed for each once // done with it. The only information we need to preserve is the data we store in docIdToTextMerger foreach (var fixAllContext in fixAllContexts) { Contract.ThrowIfFalse(fixAllContext.Scope is FixAllScope.Document or FixAllScope.Project); await FixSingleContextAsync(fixAllContext, progressTracker, docIdToTextMerger).ConfigureAwait(false); } // Finally, merge in all text changes into the solution. We can't do this per-project as we have to have // process *all* diagnostics in the solution to find the changes made to all documents. using (progressTracker.ItemCompletedScope()) { if (docIdToTextMerger.Count == 0) return null; var currentSolution = originalFixAllContext.Solution; foreach (var group in docIdToTextMerger.GroupBy(kvp => kvp.Key.ProjectId)) currentSolution = await ApplyChangesAsync(currentSolution, group.SelectAsArray(kvp => (kvp.Key, kvp.Value)), cancellationToken).ConfigureAwait(false); return currentSolution; } } private static async Task FixSingleContextAsync( FixAllContext fixAllContext, IProgressTracker progressTracker, Dictionary<DocumentId, TextChangeMerger> docIdToTextMerger) { // First, determine the diagnostics to fix for that context. var documentToDiagnostics = await DetermineDiagnosticsAsync(fixAllContext, progressTracker).ConfigureAwait(false); // Second, process all those diagnostics, merging the cumulative set of text changes per document into docIdToTextMerger. await AddDocumentChangesAsync(fixAllContext, progressTracker, docIdToTextMerger, documentToDiagnostics).ConfigureAwait(false); } private static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> DetermineDiagnosticsAsync(FixAllContext fixAllContext, IProgressTracker progressTracker) { using var _ = progressTracker.ItemCompletedScope(); var documentToDiagnostics = await fixAllContext.GetDocumentDiagnosticsToFixAsync().ConfigureAwait(false); var filtered = documentToDiagnostics.Where(kvp => { if (kvp.Key.Project != fixAllContext.Project) return false; if (fixAllContext.Document != null && fixAllContext.Document != kvp.Key) return false; return true; }); return filtered.ToImmutableDictionary(); } private static async Task AddDocumentChangesAsync( FixAllContext fixAllContext, IProgressTracker progressTracker, Dictionary<DocumentId, TextChangeMerger> docIdToTextMerger, ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentToDiagnostics) { using var _ = progressTracker.ItemCompletedScope(); // First, order the diagnostics so we process them in a consistent manner and get the same results given the // same input solution. var orderedDiagnostics = documentToDiagnostics.SelectMany(kvp => kvp.Value) .Where(d => d.Location.IsInSource) .OrderBy(d => d.Location.SourceTree!.FilePath) .ThenBy(d => d.Location.SourceSpan.Start) .ToImmutableArray(); // Now determine all the document changes caused from these diagnostics. var allChangedDocumentsInDiagnosticsOrder = await GetAllChangedDocumentsInDiagnosticsOrderAsync(fixAllContext, orderedDiagnostics).ConfigureAwait(false); // Finally, take all the changes made to each document and merge them together into docIdToTextMerger to // keep track of the total set of changes to any particular document. await MergeTextChangesAsync(fixAllContext, allChangedDocumentsInDiagnosticsOrder, docIdToTextMerger).ConfigureAwait(false); } /// <summary> /// Returns all the changed documents produced by fixing the list of provided <paramref /// name="orderedDiagnostics"/>. The documents will be returned such that fixed documents for a later /// diagnostic will appear later than those for an earlier diagnostic. /// </summary> private static async Task<ImmutableArray<Document>> GetAllChangedDocumentsInDiagnosticsOrderAsync( FixAllContext fixAllContext, ImmutableArray<Diagnostic> orderedDiagnostics) { var solution = fixAllContext.Solution; var cancellationToken = fixAllContext.CancellationToken; // Process each diagnostic, determine the code actions to fix it, then figure out the document changes // produced by that code action. using var _1 = ArrayBuilder<Task<ImmutableArray<Document>>>.GetInstance(out var tasks); foreach (var diagnostic in orderedDiagnostics) { var document = solution.GetRequiredDocument(diagnostic.Location.SourceTree!); cancellationToken.ThrowIfCancellationRequested(); tasks.Add(Task.Run(async () => { // Create a context that will add the reported code actions into this using var _2 = ArrayBuilder<CodeAction>.GetInstance(out var codeActions); var context = new CodeFixContext(document, diagnostic, GetRegisterCodeFixAction(fixAllContext.CodeActionEquivalenceKey, codeActions), cancellationToken); // Wait for the all the code actions to be reported for this diagnostic. var registerTask = fixAllContext.CodeFixProvider.RegisterCodeFixesAsync(context) ?? Task.CompletedTask; await registerTask.ConfigureAwait(false); // Now, process each code action and find out all the document changes caused by it. using var _3 = ArrayBuilder<Document>.GetInstance(out var changedDocuments); foreach (var codeAction in codeActions) { var changedSolution = await codeAction.GetChangedSolutionInternalAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (changedSolution != null) { var changedDocumentIds = new SolutionChanges(changedSolution, solution).GetProjectChanges().SelectMany(p => p.GetChangedDocuments()); changedDocuments.AddRange(changedDocumentIds.Select(id => changedSolution.GetRequiredDocument(id))); } } return changedDocuments.ToImmutable(); }, cancellationToken)); } // Wait for all that work to finish. await Task.WhenAll(tasks).ConfigureAwait(false); // Flatten the set of changed documents. These will naturally still be ordered by the diagnostic that // caused the change. using var _4 = ArrayBuilder<Document>.GetInstance(out var result); foreach (var task in tasks) result.AddRange(await task.ConfigureAwait(false)); return result.ToImmutable(); } /// <summary> /// Take all the changes made to a particular document and determine the text changes caused by each one. Take /// those individual text changes and attempt to merge them together in order into <paramref /// name="docIdToTextMerger"/>. /// </summary> private static async Task MergeTextChangesAsync( FixAllContext fixAllContext, ImmutableArray<Document> allChangedDocumentsInDiagnosticsOrder, Dictionary<DocumentId, TextChangeMerger> docIdToTextMerger) { var cancellationToken = fixAllContext.CancellationToken; // Now for each document that is changed, grab all the documents it was changed to (remember, many code // actions might have touched that document). Figure out the actual change, and then add that to the // interval tree of changes we're keeping track of for that document. using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var group in allChangedDocumentsInDiagnosticsOrder.GroupBy(d => d.Id)) { var docId = group.Key; var allDocChanges = group.ToImmutableArray(); // If we don't have an text merger for this doc yet, create one to keep track of all the changes. if (!docIdToTextMerger.TryGetValue(docId, out var textMerger)) { var originalDocument = fixAllContext.Solution.GetRequiredDocument(docId); textMerger = new TextChangeMerger(originalDocument); docIdToTextMerger.Add(docId, textMerger); } // Process all document groups in parallel. For each group, merge all the doc changes into an // aggregated set of changes in the TextChangeMerger type. tasks.Add(Task.Run( async () => await textMerger.TryMergeChangesAsync(allDocChanges, cancellationToken).ConfigureAwait(false), cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); } private static Action<CodeAction, ImmutableArray<Diagnostic>> GetRegisterCodeFixAction( string? codeActionEquivalenceKey, ArrayBuilder<CodeAction> codeActions) { return (action, diagnostics) => { using var _ = ArrayBuilder<CodeAction>.GetInstance(out var builder); builder.Push(action); while (builder.Count > 0) { var currentAction = builder.Pop(); if (currentAction is { EquivalenceKey: var equivalenceKey } && codeActionEquivalenceKey == equivalenceKey) { lock (codeActions) codeActions.Add(currentAction); } foreach (var nestedAction in currentAction.NestedCodeActions) builder.Push(nestedAction); } }; } private static async Task<Solution> ApplyChangesAsync( Solution currentSolution, ImmutableArray<(DocumentId, TextChangeMerger)> docIdsAndMerger, CancellationToken cancellationToken) { foreach (var (documentId, textMerger) in docIdsAndMerger) { var newText = await textMerger.GetFinalMergedTextAsync(cancellationToken).ConfigureAwait(false); currentSolution = currentSolution.WithDocumentText(documentId, newText); } return currentSolution; } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/SymbolKey/SymbolKeyExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; namespace Microsoft.CodeAnalysis { internal static class SymbolKeyExtensions { public static SymbolKey GetSymbolKey(this ISymbol? symbol, CancellationToken cancellationToken = default) => SymbolKey.Create(symbol, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; namespace Microsoft.CodeAnalysis { internal static class SymbolKeyExtensions { public static SymbolKey GetSymbolKey(this ISymbol? symbol, CancellationToken cancellationToken = default) => SymbolKey.Create(symbol, cancellationToken); } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Test/Utilities/CSharp/MockCSharpCompiler.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities { internal class MockCSharpCompiler : CSharpCompiler { private readonly ImmutableArray<DiagnosticAnalyzer> _analyzers; private readonly ImmutableArray<ISourceGenerator> _generators; internal Compilation Compilation; internal AnalyzerOptions AnalyzerOptions; public MockCSharpCompiler(string responseFile, string workingDirectory, string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null) : this(responseFile, CreateBuildPaths(workingDirectory), args, analyzers, generators, loader) { } public MockCSharpCompiler(string responseFile, BuildPaths buildPaths, string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null, GeneratorDriverCache driverCache = null) : base(CSharpCommandLineParser.Default, responseFile, args, buildPaths, Environment.GetEnvironmentVariable("LIB"), loader ?? new DefaultAnalyzerAssemblyLoader(), driverCache) { _analyzers = analyzers.NullToEmpty(); _generators = generators.NullToEmpty(); } private static BuildPaths CreateBuildPaths(string workingDirectory, string sdkDirectory = null) => RuntimeUtilities.CreateBuildPaths(workingDirectory, sdkDirectory); protected override void ResolveAnalyzersFromArguments( List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, bool skipAnalyzers, out ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<ISourceGenerator> generators) { base.ResolveAnalyzersFromArguments(diagnostics, messageProvider, skipAnalyzers, out analyzers, out generators); if (!_analyzers.IsDefaultOrEmpty) { analyzers = analyzers.InsertRange(0, _analyzers); } if (!_generators.IsDefaultOrEmpty) { generators = generators.InsertRange(0, _generators); } } public Compilation CreateCompilation( TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger) => CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, syntaxDiagOptionsOpt: default, globalDiagnosticOptionsOpt: default); public override Compilation CreateCompilation( TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger, ImmutableArray<AnalyzerConfigOptionsResult> syntaxDiagOptionsOpt, AnalyzerConfigOptionsResult globalDiagnosticOptionsOpt) { Compilation = base.CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, syntaxDiagOptionsOpt, globalDiagnosticOptionsOpt); return Compilation; } protected override AnalyzerOptions CreateAnalyzerOptions( ImmutableArray<AdditionalText> additionalTextFiles, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider) { AnalyzerOptions = base.CreateAnalyzerOptions(additionalTextFiles, analyzerConfigOptionsProvider); return AnalyzerOptions; } } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities { internal class MockCSharpCompiler : CSharpCompiler { private readonly ImmutableArray<DiagnosticAnalyzer> _analyzers; private readonly ImmutableArray<ISourceGenerator> _generators; internal Compilation Compilation; internal AnalyzerOptions AnalyzerOptions; public MockCSharpCompiler(string responseFile, string workingDirectory, string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null) : this(responseFile, CreateBuildPaths(workingDirectory), args, analyzers, generators, loader) { } public MockCSharpCompiler(string responseFile, BuildPaths buildPaths, string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null, GeneratorDriverCache driverCache = null) : base(CSharpCommandLineParser.Default, responseFile, args, buildPaths, Environment.GetEnvironmentVariable("LIB"), loader ?? new DefaultAnalyzerAssemblyLoader(), driverCache) { _analyzers = analyzers.NullToEmpty(); _generators = generators.NullToEmpty(); } private static BuildPaths CreateBuildPaths(string workingDirectory, string sdkDirectory = null) => RuntimeUtilities.CreateBuildPaths(workingDirectory, sdkDirectory); protected override void ResolveAnalyzersFromArguments( List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, bool skipAnalyzers, out ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<ISourceGenerator> generators) { base.ResolveAnalyzersFromArguments(diagnostics, messageProvider, skipAnalyzers, out analyzers, out generators); if (!_analyzers.IsDefaultOrEmpty) { analyzers = analyzers.InsertRange(0, _analyzers); } if (!_generators.IsDefaultOrEmpty) { generators = generators.InsertRange(0, _generators); } } public Compilation CreateCompilation( TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger) => CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, syntaxDiagOptionsOpt: default, globalDiagnosticOptionsOpt: default); public override Compilation CreateCompilation( TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger, ImmutableArray<AnalyzerConfigOptionsResult> syntaxDiagOptionsOpt, AnalyzerConfigOptionsResult globalDiagnosticOptionsOpt) { Compilation = base.CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, syntaxDiagOptionsOpt, globalDiagnosticOptionsOpt); return Compilation; } protected override AnalyzerOptions CreateAnalyzerOptions( ImmutableArray<AdditionalText> additionalTextFiles, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider) { AnalyzerOptions = base.CreateAnalyzerOptions(additionalTextFiles, analyzerConfigOptionsProvider); return AnalyzerOptions; } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Remote/Core/ExternalAccess/Pythia/Api/PythiaRemoteHostClient.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal readonly struct PythiaRemoteHostClient { private readonly ServiceHubRemoteHostClient _client; private readonly PythiaServiceDescriptorsWrapper _serviceDescriptors; private readonly PythiaRemoteServiceCallbackDispatcherRegistry _callbackDispatchers; internal PythiaRemoteHostClient(ServiceHubRemoteHostClient client, PythiaServiceDescriptorsWrapper serviceDescriptors, PythiaRemoteServiceCallbackDispatcherRegistry callbackDispatchers) { _client = client; _serviceDescriptors = serviceDescriptors; _callbackDispatchers = callbackDispatchers; } public static async Task<PythiaRemoteHostClient?> TryGetClientAsync(HostWorkspaceServices services, PythiaServiceDescriptorsWrapper serviceDescriptors, PythiaRemoteServiceCallbackDispatcherRegistry callbackDispatchers, CancellationToken cancellationToken = default) { var client = await RemoteHostClient.TryGetClientAsync(services, cancellationToken).ConfigureAwait(false); if (client is null) return null; return new PythiaRemoteHostClient((ServiceHubRemoteHostClient)client, serviceDescriptors, callbackDispatchers); } private PythiaRemoteServiceConnectionWrapper<TService> CreateConnection<TService>(object? callbackTarget) where TService : class => new(_client.CreateConnection<TService>(_serviceDescriptors.UnderlyingObject, _callbackDispatchers, callbackTarget)); // no solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // no solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } // solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal readonly struct PythiaRemoteHostClient { private readonly ServiceHubRemoteHostClient _client; private readonly PythiaServiceDescriptorsWrapper _serviceDescriptors; private readonly PythiaRemoteServiceCallbackDispatcherRegistry _callbackDispatchers; internal PythiaRemoteHostClient(ServiceHubRemoteHostClient client, PythiaServiceDescriptorsWrapper serviceDescriptors, PythiaRemoteServiceCallbackDispatcherRegistry callbackDispatchers) { _client = client; _serviceDescriptors = serviceDescriptors; _callbackDispatchers = callbackDispatchers; } public static async Task<PythiaRemoteHostClient?> TryGetClientAsync(HostWorkspaceServices services, PythiaServiceDescriptorsWrapper serviceDescriptors, PythiaRemoteServiceCallbackDispatcherRegistry callbackDispatchers, CancellationToken cancellationToken = default) { var client = await RemoteHostClient.TryGetClientAsync(services, cancellationToken).ConfigureAwait(false); if (client is null) return null; return new PythiaRemoteHostClient((ServiceHubRemoteHostClient)client, serviceDescriptors, callbackDispatchers); } private PythiaRemoteServiceConnectionWrapper<TService> CreateConnection<TService>(object? callbackTarget) where TService : class => new(_client.CreateConnection<TService>(_serviceDescriptors.UnderlyingObject, _callbackDispatchers, callbackTarget)); // no solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // no solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } // solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/RegexEmbeddedLanguage.cs
// 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. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions.LanguageServices; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions { internal class RegexEmbeddedLanguage : IEmbeddedLanguageFeatures { public readonly EmbeddedLanguageInfo Info; private readonly AbstractEmbeddedLanguageFeaturesProvider _provider; public ISyntaxClassifier Classifier { get; } public IDocumentHighlightsService DocumentHighlightsService { get; } public CompletionProvider CompletionProvider { get; } public RegexEmbeddedLanguage( AbstractEmbeddedLanguageFeaturesProvider provider, EmbeddedLanguageInfo info) { Info = info; Classifier = new RegexSyntaxClassifier(info); _provider = provider; DocumentHighlightsService = new RegexDocumentHighlightsService(this); CompletionProvider = new RegexEmbeddedCompletionProvider(this); } internal async Task<(RegexTree tree, SyntaxToken token)> TryGetTreeAndTokenAtPositionAsync( Document document, int position, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); if (!RegexPatternDetector.IsPossiblyPatternToken(token, syntaxFacts)) return default; var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var detector = RegexPatternDetector.TryGetOrCreate(semanticModel.Compilation, this.Info); var tree = detector?.TryParseRegexPattern(token, semanticModel, cancellationToken); return tree == null ? default : (tree, token); } internal async Task<RegexTree> TryGetTreeAtPositionAsync( Document document, int position, CancellationToken cancellationToken) { var (tree, _) = await TryGetTreeAndTokenAtPositionAsync( document, position, cancellationToken).ConfigureAwait(false); return tree; } public string EscapeText(string text, SyntaxToken token) => _provider.EscapeText(text, token); } }
// 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. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions.LanguageServices; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions { internal class RegexEmbeddedLanguage : IEmbeddedLanguageFeatures { public readonly EmbeddedLanguageInfo Info; private readonly AbstractEmbeddedLanguageFeaturesProvider _provider; public ISyntaxClassifier Classifier { get; } public IDocumentHighlightsService DocumentHighlightsService { get; } public CompletionProvider CompletionProvider { get; } public RegexEmbeddedLanguage( AbstractEmbeddedLanguageFeaturesProvider provider, EmbeddedLanguageInfo info) { Info = info; Classifier = new RegexSyntaxClassifier(info); _provider = provider; DocumentHighlightsService = new RegexDocumentHighlightsService(this); CompletionProvider = new RegexEmbeddedCompletionProvider(this); } internal async Task<(RegexTree tree, SyntaxToken token)> TryGetTreeAndTokenAtPositionAsync( Document document, int position, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); if (!RegexPatternDetector.IsPossiblyPatternToken(token, syntaxFacts)) return default; var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var detector = RegexPatternDetector.TryGetOrCreate(semanticModel.Compilation, this.Info); var tree = detector?.TryParseRegexPattern(token, semanticModel, cancellationToken); return tree == null ? default : (tree, token); } internal async Task<RegexTree> TryGetTreeAtPositionAsync( Document document, int position, CancellationToken cancellationToken) { var (tree, _) = await TryGetTreeAndTokenAtPositionAsync( document, position, cancellationToken).ConfigureAwait(false); return tree; } public string EscapeText(string text, SyntaxToken token) => _provider.EscapeText(text, token); } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/EditAndContinue/DebuggingSessionTelemetry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class DebuggingSessionTelemetry { internal readonly struct Data { public readonly ImmutableArray<EditSessionTelemetry.Data> EditSessionData; public readonly int EmptyEditSessionCount; public readonly int EmptyHotReloadEditSessionCount; public Data(DebuggingSessionTelemetry telemetry) { EditSessionData = telemetry._editSessionData.ToImmutableArray(); EmptyEditSessionCount = telemetry._emptyEditSessionCount; EmptyHotReloadEditSessionCount = telemetry._emptyHotReloadEditSessionCount; } } private readonly object _guard = new(); private readonly List<EditSessionTelemetry.Data> _editSessionData = new(); private int _emptyEditSessionCount; private int _emptyHotReloadEditSessionCount; public Data GetDataAndClear() { lock (_guard) { var data = new Data(this); _editSessionData.Clear(); _emptyEditSessionCount = 0; _emptyHotReloadEditSessionCount = 0; return data; } } public void LogEditSession(EditSessionTelemetry.Data editSessionTelemetryData) { lock (_guard) { if (editSessionTelemetryData.IsEmpty) { if (editSessionTelemetryData.InBreakState) _emptyEditSessionCount++; else _emptyHotReloadEditSessionCount++; } else { _editSessionData.Add(editSessionTelemetryData); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class DebuggingSessionTelemetry { internal readonly struct Data { public readonly ImmutableArray<EditSessionTelemetry.Data> EditSessionData; public readonly int EmptyEditSessionCount; public readonly int EmptyHotReloadEditSessionCount; public Data(DebuggingSessionTelemetry telemetry) { EditSessionData = telemetry._editSessionData.ToImmutableArray(); EmptyEditSessionCount = telemetry._emptyEditSessionCount; EmptyHotReloadEditSessionCount = telemetry._emptyHotReloadEditSessionCount; } } private readonly object _guard = new(); private readonly List<EditSessionTelemetry.Data> _editSessionData = new(); private int _emptyEditSessionCount; private int _emptyHotReloadEditSessionCount; public Data GetDataAndClear() { lock (_guard) { var data = new Data(this); _editSessionData.Clear(); _emptyEditSessionCount = 0; _emptyHotReloadEditSessionCount = 0; return data; } } public void LogEditSession(EditSessionTelemetry.Data editSessionTelemetryData) { lock (_guard) { if (editSessionTelemetryData.IsEmpty) { if (editSessionTelemetryData.InBreakState) _emptyEditSessionCount++; else _emptyHotReloadEditSessionCount++; } else { _editSessionData.Add(editSessionTelemetryData); } } } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/TestUtilities/EditAndContinue/DeclaratorMapDescription.cs
// 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. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { public sealed class SyntaxMapDescription { public readonly ImmutableArray<ImmutableArray<TextSpan>> OldSpans; public readonly ImmutableArray<ImmutableArray<TextSpan>> NewSpans; public SyntaxMapDescription(string oldSource, string newSource) { OldSpans = GetSpans(oldSource); NewSpans = GetSpans(newSource); Assert.Equal(OldSpans.Length, NewSpans.Length); for (var i = 0; i < OldSpans.Length; i++) { Assert.Equal(OldSpans[i].Length, NewSpans[i].Length); } } private static readonly Regex s_statementPattern = new Regex( @"[<]N[:] (?<Id>[0-9]+[.][0-9]+) [>] (?<Node>.*) [<][/]N[:] (\k<Id>) [>]", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); internal static ImmutableArray<ImmutableArray<TextSpan>> GetSpans(string src) { var matches = s_statementPattern.Matches(src); var result = new List<List<TextSpan>>(); for (var i = 0; i < matches.Count; i++) { var stmt = matches[i].Groups["Node"]; var id = matches[i].Groups["Id"].Value.Split('.'); var id0 = int.Parse(id[0]); var id1 = int.Parse(id[1]); EnsureSlot(result, id0); if (result[id0] == null) { result[id0] = new List<TextSpan>(); } EnsureSlot(result[id0], id1); result[id0][id1] = new TextSpan(stmt.Index, stmt.Length); } return result.Select(r => r.AsImmutableOrEmpty()).AsImmutableOrEmpty(); } internal IEnumerable<KeyValuePair<TextSpan, TextSpan>> this[int i] { get { for (var j = 0; j < OldSpans[i].Length; j++) { yield return KeyValuePairUtil.Create(OldSpans[i][j], NewSpans[i][j]); } } } private static void EnsureSlot<T>(List<T> list, int i) { while (i >= list.Count) { list.Add(default); } } } }
// 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. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { public sealed class SyntaxMapDescription { public readonly ImmutableArray<ImmutableArray<TextSpan>> OldSpans; public readonly ImmutableArray<ImmutableArray<TextSpan>> NewSpans; public SyntaxMapDescription(string oldSource, string newSource) { OldSpans = GetSpans(oldSource); NewSpans = GetSpans(newSource); Assert.Equal(OldSpans.Length, NewSpans.Length); for (var i = 0; i < OldSpans.Length; i++) { Assert.Equal(OldSpans[i].Length, NewSpans[i].Length); } } private static readonly Regex s_statementPattern = new Regex( @"[<]N[:] (?<Id>[0-9]+[.][0-9]+) [>] (?<Node>.*) [<][/]N[:] (\k<Id>) [>]", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); internal static ImmutableArray<ImmutableArray<TextSpan>> GetSpans(string src) { var matches = s_statementPattern.Matches(src); var result = new List<List<TextSpan>>(); for (var i = 0; i < matches.Count; i++) { var stmt = matches[i].Groups["Node"]; var id = matches[i].Groups["Id"].Value.Split('.'); var id0 = int.Parse(id[0]); var id1 = int.Parse(id[1]); EnsureSlot(result, id0); if (result[id0] == null) { result[id0] = new List<TextSpan>(); } EnsureSlot(result[id0], id1); result[id0][id1] = new TextSpan(stmt.Index, stmt.Length); } return result.Select(r => r.AsImmutableOrEmpty()).AsImmutableOrEmpty(); } internal IEnumerable<KeyValuePair<TextSpan, TextSpan>> this[int i] { get { for (var j = 0; j < OldSpans[i].Length; j++) { yield return KeyValuePairUtil.Create(OldSpans[i][j], NewSpans[i][j]); } } } private static void EnsureSlot<T>(List<T> list, int i) { while (i >= list.Count) { list.Add(default); } } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/TriviaList.cs
// 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. namespace Microsoft.CodeAnalysis.Formatting { internal readonly struct TriviaList { private readonly SyntaxTriviaList _list1; private readonly SyntaxTriviaList _list2; public TriviaList(SyntaxTriviaList list1, SyntaxTriviaList list2) { _list1 = list1; _list2 = list2; } public int Count => _list1.Count + _list2.Count; public SyntaxTrivia this[int index] => index < _list1.Count ? _list1[index] : _list2[index - _list1.Count]; public Enumerator GetEnumerator() => new(this); public struct Enumerator { private readonly SyntaxTriviaList _list1; private readonly SyntaxTriviaList _list2; private SyntaxTriviaList.Enumerator _enumerator; private int _index; internal Enumerator(TriviaList triviaList) { _list1 = triviaList._list1; _list2 = triviaList._list2; _index = -1; _enumerator = _list1.GetEnumerator(); } public bool MoveNext() { _index++; if (_index == _list1.Count) { _enumerator = _list2.GetEnumerator(); } return _enumerator.MoveNext(); } public SyntaxTrivia Current => _enumerator.Current; } } }
// 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. namespace Microsoft.CodeAnalysis.Formatting { internal readonly struct TriviaList { private readonly SyntaxTriviaList _list1; private readonly SyntaxTriviaList _list2; public TriviaList(SyntaxTriviaList list1, SyntaxTriviaList list2) { _list1 = list1; _list2 = list2; } public int Count => _list1.Count + _list2.Count; public SyntaxTrivia this[int index] => index < _list1.Count ? _list1[index] : _list2[index - _list1.Count]; public Enumerator GetEnumerator() => new(this); public struct Enumerator { private readonly SyntaxTriviaList _list1; private readonly SyntaxTriviaList _list2; private SyntaxTriviaList.Enumerator _enumerator; private int _index; internal Enumerator(TriviaList triviaList) { _list1 = triviaList._list1; _list2 = triviaList._list2; _index = -1; _enumerator = _list1.GetEnumerator(); } public bool MoveNext() { _index++; if (_index == _list1.Count) { _enumerator = _list2.GetEnumerator(); } return _enumerator.MoveNext(); } public SyntaxTrivia Current => _enumerator.Current; } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeImplementsStatement.cs
// 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. #nullable disable using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeElement2))] public sealed class CodeImplementsStatement : AbstractCodeElement { internal static EnvDTE80.CodeElement2 Create( CodeModelState state, AbstractCodeMember parent, string namespaceName, int ordinal) { var element = new CodeImplementsStatement(state, parent, namespaceName, ordinal); var result = (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element); return result; } internal static EnvDTE80.CodeElement2 CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeImplementsStatement(state, fileCodeModel, nodeKind, name); return (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element); } private readonly ParentHandle<AbstractCodeMember> _parentHandle; private readonly string _namespaceName; private readonly int _ordinal; private CodeImplementsStatement( CodeModelState state, AbstractCodeMember parent, string namespaceName, int ordinal) : base(state, parent.FileCodeModel) { _parentHandle = new ParentHandle<AbstractCodeMember>(parent); _namespaceName = namespaceName; _ordinal = ordinal; } private CodeImplementsStatement( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind) { _namespaceName = name; } internal override bool TryLookupNode(out SyntaxNode node) { node = null; var parentNode = _parentHandle.Value.LookupNode(); if (parentNode == null) { return false; } if (!CodeModelService.TryGetImplementsNode(parentNode, _namespaceName, _ordinal, out var implementsNode)) { return false; } node = implementsNode; return node != null; } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementImplementsStmt; } } public override object Parent { get { return _parentHandle.Value; } } public override EnvDTE.CodeElements Children { get { return EmptyCollection.Create(this.State, this); } } protected override void SetName(string value) => throw Exceptions.ThrowENotImpl(); public override void RenameSymbol(string newName) => throw Exceptions.ThrowENotImpl(); } }
// 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. #nullable disable using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeElement2))] public sealed class CodeImplementsStatement : AbstractCodeElement { internal static EnvDTE80.CodeElement2 Create( CodeModelState state, AbstractCodeMember parent, string namespaceName, int ordinal) { var element = new CodeImplementsStatement(state, parent, namespaceName, ordinal); var result = (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element); return result; } internal static EnvDTE80.CodeElement2 CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeImplementsStatement(state, fileCodeModel, nodeKind, name); return (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element); } private readonly ParentHandle<AbstractCodeMember> _parentHandle; private readonly string _namespaceName; private readonly int _ordinal; private CodeImplementsStatement( CodeModelState state, AbstractCodeMember parent, string namespaceName, int ordinal) : base(state, parent.FileCodeModel) { _parentHandle = new ParentHandle<AbstractCodeMember>(parent); _namespaceName = namespaceName; _ordinal = ordinal; } private CodeImplementsStatement( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind) { _namespaceName = name; } internal override bool TryLookupNode(out SyntaxNode node) { node = null; var parentNode = _parentHandle.Value.LookupNode(); if (parentNode == null) { return false; } if (!CodeModelService.TryGetImplementsNode(parentNode, _namespaceName, _ordinal, out var implementsNode)) { return false; } node = implementsNode; return node != null; } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementImplementsStmt; } } public override object Parent { get { return _parentHandle.Value; } } public override EnvDTE.CodeElements Children { get { return EmptyCollection.Create(this.State, this); } } protected override void SetName(string value) => throw Exceptions.ThrowENotImpl(); public override void RenameSymbol(string newName) => throw Exceptions.ThrowENotImpl(); } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest/NavigateTo/NavigateToSearcherTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Moq; using Moq.Language.Flow; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NavigateTo { [UseExportProvider] [Trait(Traits.Feature, Traits.Features.NavigateTo)] public class NavigateToSearcherTests { private static IReturnsResult<INavigateToSearchService> SetupSearchProject( Mock<INavigateToSearchService> searchService, string pattern, bool isFullyLoaded, INavigateToSearchResult? result) { var searchServiceSetup = searchService.Setup(ss => ss.SearchProjectAsync( It.IsAny<Project>(), It.IsAny<ImmutableArray<Document>>(), pattern, ImmutableHashSet<string>.Empty, It.IsAny<Func<INavigateToSearchResult, Task>>(), isFullyLoaded, It.IsAny<CancellationToken>())); var searchServiceCallback = searchServiceSetup.Callback( (Project project, ImmutableArray<Document> priorityDocuments, string pattern2, IImmutableSet<string> kinds, Func<INavigateToSearchResult, Task> onResultFound2, bool isFullyLoaded2, CancellationToken cancellationToken) => { if (result != null) onResultFound2(result); }); return searchServiceCallback.ReturnsAsync(isFullyLoaded ? NavigateToSearchLocation.Latest : NavigateToSearchLocation.Cache); } private static ValueTask<bool> IsFullyLoadedAsync(bool projectSystem, bool remoteHost) => new(projectSystem && remoteHost); [Fact] public async Task NotFullyLoadedOnlyMakesOneSearchProjectCallIfValueReturned() { using var workspace = TestWorkspace.CreateCSharp(""); var pattern = "irrelevant"; var result = new TestNavigateToSearchResult(workspace, new TextSpan(0, 0)); var searchService = new Mock<INavigateToSearchService>(MockBehavior.Strict); SetupSearchProject(searchService, pattern, isFullyLoaded: false, result); // Simulate a host that says the solution isn't fully loaded. var hostMock = new Mock<INavigateToSearcherHost>(MockBehavior.Strict); hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny<CancellationToken>())).Returns(() => IsFullyLoadedAsync(projectSystem: false, remoteHost: false)); hostMock.Setup(h => h.GetNavigateToSearchService(It.IsAny<Project>())).Returns(searchService.Object); var callbackMock = new Mock<INavigateToSearchCallback>(MockBehavior.Strict); callbackMock.Setup(c => c.ReportProgress(It.IsAny<int>(), It.IsAny<int>())); callbackMock.Setup(c => c.AddItemAsync(It.IsAny<Project>(), result, It.IsAny<CancellationToken>())).Returns(Task.CompletedTask); // Because we returned a result when not fully loaded, we should notify the user that data was not complete. callbackMock.Setup(c => c.Done(false)); var searcher = NavigateToSearcher.Create( workspace.CurrentSolution, AsynchronousOperationListenerProvider.NullListener, callbackMock.Object, pattern, searchCurrentDocument: false, kinds: ImmutableHashSet<string>.Empty, CancellationToken.None, hostMock.Object); await searcher.SearchAsync(CancellationToken.None); } [Theory] [CombinatorialData] public async Task NotFullyLoadedMakesTwoSearchProjectCallIfValueNotReturned(bool projectSystemFullyLoaded) { using var workspace = TestWorkspace.CreateCSharp(""); var pattern = "irrelevant"; var result = new TestNavigateToSearchResult(workspace, new TextSpan(0, 0)); var searchService = new Mock<INavigateToSearchService>(MockBehavior.Strict); // First call will pass in that we're not fully loaded. If we return null, we should get // another call with the request to search the fully loaded data. SetupSearchProject(searchService, pattern, isFullyLoaded: false, result: null); SetupSearchProject(searchService, pattern, isFullyLoaded: true, result); // Simulate a host that says the solution isn't fully loaded. var hostMock = new Mock<INavigateToSearcherHost>(MockBehavior.Strict); hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny<CancellationToken>())).Returns(() => IsFullyLoadedAsync(projectSystemFullyLoaded, remoteHost: false)); hostMock.Setup(h => h.GetNavigateToSearchService(It.IsAny<Project>())).Returns(searchService.Object); var callbackMock = new Mock<INavigateToSearchCallback>(MockBehavior.Strict); callbackMock.Setup(c => c.ReportProgress(It.IsAny<int>(), It.IsAny<int>())); callbackMock.Setup(c => c.AddItemAsync(It.IsAny<Project>(), result, It.IsAny<CancellationToken>())) .Returns(Task.CompletedTask); // Because the remote host wasn't fully loaded, we still notify that our results may be incomplete. callbackMock.Setup(c => c.Done(false)); var searcher = NavigateToSearcher.Create( workspace.CurrentSolution, AsynchronousOperationListenerProvider.NullListener, callbackMock.Object, pattern, searchCurrentDocument: false, kinds: ImmutableHashSet<string>.Empty, CancellationToken.None, hostMock.Object); await searcher.SearchAsync(CancellationToken.None); } [Theory] [CombinatorialData] public async Task NotFullyLoadedStillReportsAsNotCompleteIfRemoteHostIsStillHydrating(bool projectIsFullyLoaded) { using var workspace = TestWorkspace.CreateCSharp(""); var pattern = "irrelevant"; var searchService = new Mock<INavigateToSearchService>(MockBehavior.Strict); // First call will pass in that we're not fully loaded. If we return null, we should get another call with // the request to search the fully loaded data. If we don't report anything the second time, we will still // tell the user the search was complete. SetupSearchProject(searchService, pattern, isFullyLoaded: false, result: null); SetupSearchProject(searchService, pattern, isFullyLoaded: true, result: null); // Simulate a host that says the solution isn't fully loaded. var hostMock = new Mock<INavigateToSearcherHost>(MockBehavior.Strict); hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny<CancellationToken>())).Returns(() => IsFullyLoadedAsync(projectIsFullyLoaded, remoteHost: false)); hostMock.Setup(h => h.GetNavigateToSearchService(It.IsAny<Project>())).Returns(searchService.Object); var callbackMock = new Mock<INavigateToSearchCallback>(MockBehavior.Strict); callbackMock.Setup(c => c.ReportProgress(It.IsAny<int>(), It.IsAny<int>())); // Because the remote host wasn't fully loaded, we still notify that our results may be incomplete. callbackMock.Setup(c => c.Done(false)); var searcher = NavigateToSearcher.Create( workspace.CurrentSolution, AsynchronousOperationListenerProvider.NullListener, callbackMock.Object, pattern, searchCurrentDocument: false, kinds: ImmutableHashSet<string>.Empty, CancellationToken.None, hostMock.Object); await searcher.SearchAsync(CancellationToken.None); } [Fact] public async Task FullyLoadedMakesSingleSearchProjectCallIfValueNotReturned() { using var workspace = TestWorkspace.CreateCSharp(""); var pattern = "irrelevant"; var result = new TestNavigateToSearchResult(workspace, new TextSpan(0, 0)); var searchService = new Mock<INavigateToSearchService>(MockBehavior.Strict); // First call will pass in that we're fully loaded. If we return null, we should not get another call. SetupSearchProject(searchService, pattern, isFullyLoaded: true, result: null); // Simulate a host that says the solution is fully loaded. var hostMock = new Mock<INavigateToSearcherHost>(MockBehavior.Strict); hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny<CancellationToken>())).Returns(() => IsFullyLoadedAsync(projectSystem: true, remoteHost: true)); hostMock.Setup(h => h.GetNavigateToSearchService(It.IsAny<Project>())).Returns(searchService.Object); var callbackMock = new Mock<INavigateToSearchCallback>(MockBehavior.Strict); callbackMock.Setup(c => c.ReportProgress(It.IsAny<int>(), It.IsAny<int>())); callbackMock.Setup(c => c.AddItemAsync(It.IsAny<Project>(), result, It.IsAny<CancellationToken>())) .Returns(Task.CompletedTask); // Because we did a full search, we should let the user know it was totally accurate. callbackMock.Setup(c => c.Done(true)); var searcher = NavigateToSearcher.Create( workspace.CurrentSolution, AsynchronousOperationListenerProvider.NullListener, callbackMock.Object, pattern, searchCurrentDocument: false, kinds: ImmutableHashSet<string>.Empty, CancellationToken.None, hostMock.Object); await searcher.SearchAsync(CancellationToken.None); } private class TestNavigateToSearchResult : INavigateToSearchResult, INavigableItem { private readonly TestWorkspace _workspace; private readonly TextSpan _sourceSpan; public TestNavigateToSearchResult(TestWorkspace workspace, TextSpan sourceSpan) { _workspace = workspace; _sourceSpan = sourceSpan; } public Document Document => _workspace.CurrentSolution.Projects.Single().Documents.Single(); public TextSpan SourceSpan => _sourceSpan; public string AdditionalInformation => throw new NotImplementedException(); public string Kind => throw new NotImplementedException(); public NavigateToMatchKind MatchKind => throw new NotImplementedException(); public bool IsCaseSensitive => throw new NotImplementedException(); public string Name => throw new NotImplementedException(); public ImmutableArray<TextSpan> NameMatchSpans => throw new NotImplementedException(); public string SecondarySort => throw new NotImplementedException(); public string Summary => throw new NotImplementedException(); public INavigableItem NavigableItem => this; public Glyph Glyph => throw new NotImplementedException(); public ImmutableArray<TaggedText> DisplayTaggedParts => throw new NotImplementedException(); public bool DisplayFileLocation => throw new NotImplementedException(); public bool IsImplicitlyDeclared => throw new NotImplementedException(); public bool IsStale => throw new NotImplementedException(); public ImmutableArray<INavigableItem> ChildItems => throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Moq; using Moq.Language.Flow; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NavigateTo { [UseExportProvider] [Trait(Traits.Feature, Traits.Features.NavigateTo)] public class NavigateToSearcherTests { private static IReturnsResult<INavigateToSearchService> SetupSearchProject( Mock<INavigateToSearchService> searchService, string pattern, bool isFullyLoaded, INavigateToSearchResult? result) { var searchServiceSetup = searchService.Setup(ss => ss.SearchProjectAsync( It.IsAny<Project>(), It.IsAny<ImmutableArray<Document>>(), pattern, ImmutableHashSet<string>.Empty, It.IsAny<Func<INavigateToSearchResult, Task>>(), isFullyLoaded, It.IsAny<CancellationToken>())); var searchServiceCallback = searchServiceSetup.Callback( (Project project, ImmutableArray<Document> priorityDocuments, string pattern2, IImmutableSet<string> kinds, Func<INavigateToSearchResult, Task> onResultFound2, bool isFullyLoaded2, CancellationToken cancellationToken) => { if (result != null) onResultFound2(result); }); return searchServiceCallback.ReturnsAsync(isFullyLoaded ? NavigateToSearchLocation.Latest : NavigateToSearchLocation.Cache); } private static ValueTask<bool> IsFullyLoadedAsync(bool projectSystem, bool remoteHost) => new(projectSystem && remoteHost); [Fact] public async Task NotFullyLoadedOnlyMakesOneSearchProjectCallIfValueReturned() { using var workspace = TestWorkspace.CreateCSharp(""); var pattern = "irrelevant"; var result = new TestNavigateToSearchResult(workspace, new TextSpan(0, 0)); var searchService = new Mock<INavigateToSearchService>(MockBehavior.Strict); SetupSearchProject(searchService, pattern, isFullyLoaded: false, result); // Simulate a host that says the solution isn't fully loaded. var hostMock = new Mock<INavigateToSearcherHost>(MockBehavior.Strict); hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny<CancellationToken>())).Returns(() => IsFullyLoadedAsync(projectSystem: false, remoteHost: false)); hostMock.Setup(h => h.GetNavigateToSearchService(It.IsAny<Project>())).Returns(searchService.Object); var callbackMock = new Mock<INavigateToSearchCallback>(MockBehavior.Strict); callbackMock.Setup(c => c.ReportProgress(It.IsAny<int>(), It.IsAny<int>())); callbackMock.Setup(c => c.AddItemAsync(It.IsAny<Project>(), result, It.IsAny<CancellationToken>())).Returns(Task.CompletedTask); // Because we returned a result when not fully loaded, we should notify the user that data was not complete. callbackMock.Setup(c => c.Done(false)); var searcher = NavigateToSearcher.Create( workspace.CurrentSolution, AsynchronousOperationListenerProvider.NullListener, callbackMock.Object, pattern, searchCurrentDocument: false, kinds: ImmutableHashSet<string>.Empty, CancellationToken.None, hostMock.Object); await searcher.SearchAsync(CancellationToken.None); } [Theory] [CombinatorialData] public async Task NotFullyLoadedMakesTwoSearchProjectCallIfValueNotReturned(bool projectSystemFullyLoaded) { using var workspace = TestWorkspace.CreateCSharp(""); var pattern = "irrelevant"; var result = new TestNavigateToSearchResult(workspace, new TextSpan(0, 0)); var searchService = new Mock<INavigateToSearchService>(MockBehavior.Strict); // First call will pass in that we're not fully loaded. If we return null, we should get // another call with the request to search the fully loaded data. SetupSearchProject(searchService, pattern, isFullyLoaded: false, result: null); SetupSearchProject(searchService, pattern, isFullyLoaded: true, result); // Simulate a host that says the solution isn't fully loaded. var hostMock = new Mock<INavigateToSearcherHost>(MockBehavior.Strict); hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny<CancellationToken>())).Returns(() => IsFullyLoadedAsync(projectSystemFullyLoaded, remoteHost: false)); hostMock.Setup(h => h.GetNavigateToSearchService(It.IsAny<Project>())).Returns(searchService.Object); var callbackMock = new Mock<INavigateToSearchCallback>(MockBehavior.Strict); callbackMock.Setup(c => c.ReportProgress(It.IsAny<int>(), It.IsAny<int>())); callbackMock.Setup(c => c.AddItemAsync(It.IsAny<Project>(), result, It.IsAny<CancellationToken>())) .Returns(Task.CompletedTask); // Because the remote host wasn't fully loaded, we still notify that our results may be incomplete. callbackMock.Setup(c => c.Done(false)); var searcher = NavigateToSearcher.Create( workspace.CurrentSolution, AsynchronousOperationListenerProvider.NullListener, callbackMock.Object, pattern, searchCurrentDocument: false, kinds: ImmutableHashSet<string>.Empty, CancellationToken.None, hostMock.Object); await searcher.SearchAsync(CancellationToken.None); } [Theory] [CombinatorialData] public async Task NotFullyLoadedStillReportsAsNotCompleteIfRemoteHostIsStillHydrating(bool projectIsFullyLoaded) { using var workspace = TestWorkspace.CreateCSharp(""); var pattern = "irrelevant"; var searchService = new Mock<INavigateToSearchService>(MockBehavior.Strict); // First call will pass in that we're not fully loaded. If we return null, we should get another call with // the request to search the fully loaded data. If we don't report anything the second time, we will still // tell the user the search was complete. SetupSearchProject(searchService, pattern, isFullyLoaded: false, result: null); SetupSearchProject(searchService, pattern, isFullyLoaded: true, result: null); // Simulate a host that says the solution isn't fully loaded. var hostMock = new Mock<INavigateToSearcherHost>(MockBehavior.Strict); hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny<CancellationToken>())).Returns(() => IsFullyLoadedAsync(projectIsFullyLoaded, remoteHost: false)); hostMock.Setup(h => h.GetNavigateToSearchService(It.IsAny<Project>())).Returns(searchService.Object); var callbackMock = new Mock<INavigateToSearchCallback>(MockBehavior.Strict); callbackMock.Setup(c => c.ReportProgress(It.IsAny<int>(), It.IsAny<int>())); // Because the remote host wasn't fully loaded, we still notify that our results may be incomplete. callbackMock.Setup(c => c.Done(false)); var searcher = NavigateToSearcher.Create( workspace.CurrentSolution, AsynchronousOperationListenerProvider.NullListener, callbackMock.Object, pattern, searchCurrentDocument: false, kinds: ImmutableHashSet<string>.Empty, CancellationToken.None, hostMock.Object); await searcher.SearchAsync(CancellationToken.None); } [Fact] public async Task FullyLoadedMakesSingleSearchProjectCallIfValueNotReturned() { using var workspace = TestWorkspace.CreateCSharp(""); var pattern = "irrelevant"; var result = new TestNavigateToSearchResult(workspace, new TextSpan(0, 0)); var searchService = new Mock<INavigateToSearchService>(MockBehavior.Strict); // First call will pass in that we're fully loaded. If we return null, we should not get another call. SetupSearchProject(searchService, pattern, isFullyLoaded: true, result: null); // Simulate a host that says the solution is fully loaded. var hostMock = new Mock<INavigateToSearcherHost>(MockBehavior.Strict); hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny<CancellationToken>())).Returns(() => IsFullyLoadedAsync(projectSystem: true, remoteHost: true)); hostMock.Setup(h => h.GetNavigateToSearchService(It.IsAny<Project>())).Returns(searchService.Object); var callbackMock = new Mock<INavigateToSearchCallback>(MockBehavior.Strict); callbackMock.Setup(c => c.ReportProgress(It.IsAny<int>(), It.IsAny<int>())); callbackMock.Setup(c => c.AddItemAsync(It.IsAny<Project>(), result, It.IsAny<CancellationToken>())) .Returns(Task.CompletedTask); // Because we did a full search, we should let the user know it was totally accurate. callbackMock.Setup(c => c.Done(true)); var searcher = NavigateToSearcher.Create( workspace.CurrentSolution, AsynchronousOperationListenerProvider.NullListener, callbackMock.Object, pattern, searchCurrentDocument: false, kinds: ImmutableHashSet<string>.Empty, CancellationToken.None, hostMock.Object); await searcher.SearchAsync(CancellationToken.None); } private class TestNavigateToSearchResult : INavigateToSearchResult, INavigableItem { private readonly TestWorkspace _workspace; private readonly TextSpan _sourceSpan; public TestNavigateToSearchResult(TestWorkspace workspace, TextSpan sourceSpan) { _workspace = workspace; _sourceSpan = sourceSpan; } public Document Document => _workspace.CurrentSolution.Projects.Single().Documents.Single(); public TextSpan SourceSpan => _sourceSpan; public string AdditionalInformation => throw new NotImplementedException(); public string Kind => throw new NotImplementedException(); public NavigateToMatchKind MatchKind => throw new NotImplementedException(); public bool IsCaseSensitive => throw new NotImplementedException(); public string Name => throw new NotImplementedException(); public ImmutableArray<TextSpan> NameMatchSpans => throw new NotImplementedException(); public string SecondarySort => throw new NotImplementedException(); public string Summary => throw new NotImplementedException(); public INavigableItem NavigableItem => this; public Glyph Glyph => throw new NotImplementedException(); public ImmutableArray<TaggedText> DisplayTaggedParts => throw new NotImplementedException(); public bool DisplayFileLocation => throw new NotImplementedException(); public bool IsImplicitlyDeclared => throw new NotImplementedException(); public bool IsStale => throw new NotImplementedException(); public ImmutableArray<INavigableItem> ChildItems => throw new NotImplementedException(); } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest/ConflictMarkerResolution/ConflictMarkerResolutionTests.cs
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.ConflictMarkerResolution; using Microsoft.CodeAnalysis.CSharp.ConflictMarkerResolution; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConflictMarkerResolution { using VerifyCS = CSharpCodeFixVerifier<EmptyDiagnosticAnalyzer, CSharpResolveConflictMarkerCodeFixProvider>; public class ConflictMarkerResolutionTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBottom1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBoth1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyTop_TakeTop() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyTop_TakeBottom() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyBottom_TakeTop() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyBottom_TakeBottom() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_WhitespaceInSection() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBottom1_WhitespaceInSection() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBoth_WhitespaceInSection() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_TopCommentedOut() { var source = @" public class Class1 { public void M() { /* <<<<<<< dest * a thing */ {|CS8300:=======|} * another thing */ {|CS8300:>>>>>>>|} source // */ } }"; var fixedSource = @" public class Class1 { public void M() { /* * a thing */ // */ } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_MiddleAndBottomCommentedOut() { var source = @" public class Class1 { public void M() { {|CS8300:<<<<<<<|} dest /* * a thing ======= * * another thing >>>>>>> source */ } }"; var fixedSource = @" public class Class1 { public void M() { /* * a thing */ } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_TopInString() { var source = @" class X { void x() { var x = @"" <<<<<<< working copy a""; {|CS8300:=======|} b""; {|CS8300:>>>>>>>|} merge rev } }"; var fixedSource = @" class X { void x() { var x = @"" a""; } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBottom_TopInString() { var source = @" class X { void x() { var x = @"" <<<<<<< working copy a""; {|CS8300:=======|} b""; {|CS8300:>>>>>>>|} merge rev } }"; var fixedSource = @" class X { void x() { var x = @"" b""; } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestMissingWithMiddleMarkerAtTopOfFile() { var source = @"{|CS8300:=======|} class X { } {|CS8300:>>>>>>>|} merge rev"; await new VerifyCS.Test { TestCode = source, FixedCode = source, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestMissingWithMiddleMarkerAtBottomOfFile() { var source = @"{|CS8300:<<<<<<<|} working copy class X { } {|CS8300:=======|}"; await new VerifyCS.Test { TestCode = source, FixedCode = source, }.RunAsync(); } [WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestFixAll1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { } {|CS8300:=======|} class Program2 { } {|CS8300:>>>>>>>|} This is theirs! {|CS8300:<<<<<<<|} This is mine! class Program3 { } {|CS8300:=======|} class Program4 { } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { } class Program3 { } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 2, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestFixAll2() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { } {|CS8300:=======|} class Program2 { } {|CS8300:>>>>>>>|} This is theirs! {|CS8300:<<<<<<<|} This is mine! class Program3 { } {|CS8300:=======|} class Program4 { } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { } class Program4 { } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 2, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestFixAll3() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { } {|CS8300:=======|} class Program2 { } {|CS8300:>>>>>>>|} This is theirs! {|CS8300:<<<<<<<|} This is mine! class Program3 { } {|CS8300:=======|} class Program4 { } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { } class Program2 { } class Program3 { } class Program4 { } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 2, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); } } }
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.ConflictMarkerResolution; using Microsoft.CodeAnalysis.CSharp.ConflictMarkerResolution; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConflictMarkerResolution { using VerifyCS = CSharpCodeFixVerifier<EmptyDiagnosticAnalyzer, CSharpResolveConflictMarkerCodeFixProvider>; public class ConflictMarkerResolutionTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBottom1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBoth1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyTop_TakeTop() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyTop_TakeBottom() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyBottom_TakeTop() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyBottom_TakeBottom() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_WhitespaceInSection() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBottom1_WhitespaceInSection() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBoth_WhitespaceInSection() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_TopCommentedOut() { var source = @" public class Class1 { public void M() { /* <<<<<<< dest * a thing */ {|CS8300:=======|} * another thing */ {|CS8300:>>>>>>>|} source // */ } }"; var fixedSource = @" public class Class1 { public void M() { /* * a thing */ // */ } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_MiddleAndBottomCommentedOut() { var source = @" public class Class1 { public void M() { {|CS8300:<<<<<<<|} dest /* * a thing ======= * * another thing >>>>>>> source */ } }"; var fixedSource = @" public class Class1 { public void M() { /* * a thing */ } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_TopInString() { var source = @" class X { void x() { var x = @"" <<<<<<< working copy a""; {|CS8300:=======|} b""; {|CS8300:>>>>>>>|} merge rev } }"; var fixedSource = @" class X { void x() { var x = @"" a""; } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBottom_TopInString() { var source = @" class X { void x() { var x = @"" <<<<<<< working copy a""; {|CS8300:=======|} b""; {|CS8300:>>>>>>>|} merge rev } }"; var fixedSource = @" class X { void x() { var x = @"" b""; } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestMissingWithMiddleMarkerAtTopOfFile() { var source = @"{|CS8300:=======|} class X { } {|CS8300:>>>>>>>|} merge rev"; await new VerifyCS.Test { TestCode = source, FixedCode = source, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestMissingWithMiddleMarkerAtBottomOfFile() { var source = @"{|CS8300:<<<<<<<|} working copy class X { } {|CS8300:=======|}"; await new VerifyCS.Test { TestCode = source, FixedCode = source, }.RunAsync(); } [WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestFixAll1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { } {|CS8300:=======|} class Program2 { } {|CS8300:>>>>>>>|} This is theirs! {|CS8300:<<<<<<<|} This is mine! class Program3 { } {|CS8300:=======|} class Program4 { } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { } class Program3 { } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 2, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestFixAll2() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { } {|CS8300:=======|} class Program2 { } {|CS8300:>>>>>>>|} This is theirs! {|CS8300:<<<<<<<|} This is mine! class Program3 { } {|CS8300:=======|} class Program4 { } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { } class Program4 { } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 2, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestFixAll3() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { } {|CS8300:=======|} class Program2 { } {|CS8300:>>>>>>>|} This is theirs! {|CS8300:<<<<<<<|} This is mine! class Program3 { } {|CS8300:=======|} class Program4 { } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { } class Program2 { } class Program3 { } class Program4 { } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 2, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/PEWriter/MetadataWriter.DynamicAnalysis.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.Cci { internal class DynamicAnalysisDataWriter { private struct DocumentRow { public BlobHandle Name; public GuidHandle HashAlgorithm; public BlobHandle Hash; } private struct MethodRow { public BlobHandle Spans; } // #Blob heap private readonly Dictionary<ImmutableArray<byte>, BlobHandle> _blobs; private int _blobHeapSize; // #GUID heap private readonly Dictionary<Guid, GuidHandle> _guids; private readonly BlobBuilder _guidWriter; // tables: private readonly List<DocumentRow> _documentTable; private readonly List<MethodRow> _methodTable; private readonly Dictionary<DebugSourceDocument, int> _documentIndex; public DynamicAnalysisDataWriter(int documentCountEstimate, int methodCountEstimate) { // Most methods will have a span blob, each document has a hash blob and at least two blobs encoding the name // (adding one more blob per document to account for all directory names): _blobs = new Dictionary<ImmutableArray<byte>, BlobHandle>(1 + methodCountEstimate + 4 * documentCountEstimate, ByteSequenceComparer.Instance); // Each document has a unique guid: const int guidSize = 16; _guids = new Dictionary<Guid, GuidHandle>(documentCountEstimate); _guidWriter = new BlobBuilder(guidSize * documentCountEstimate); _documentTable = new List<DocumentRow>(documentCountEstimate); _documentIndex = new Dictionary<DebugSourceDocument, int>(documentCountEstimate); _methodTable = new List<MethodRow>(methodCountEstimate); _blobs.Add(ImmutableArray<byte>.Empty, default(BlobHandle)); _blobHeapSize = 1; } internal void SerializeMethodDynamicAnalysisData(IMethodBody bodyOpt) { var data = bodyOpt?.DynamicAnalysisData; if (data == null) { _methodTable.Add(default(MethodRow)); return; } BlobHandle spanBlob = SerializeSpans(data.Spans, _documentIndex); _methodTable.Add(new MethodRow { Spans = spanBlob }); } #region Heaps private BlobHandle GetOrAddBlob(BlobBuilder builder) { // TODO: avoid making a copy if the blob exists in the index return GetOrAddBlob(builder.ToImmutableArray()); } private BlobHandle GetOrAddBlob(ImmutableArray<byte> blob) { BlobHandle index; if (!_blobs.TryGetValue(blob, out index)) { index = MetadataTokens.BlobHandle(_blobHeapSize); _blobs.Add(blob, index); _blobHeapSize += GetCompressedIntegerLength(blob.Length) + blob.Length; } return index; } private static int GetCompressedIntegerLength(int length) { return (length <= 0x7f) ? 1 : ((length <= 0x3fff) ? 2 : 4); } private GuidHandle GetOrAddGuid(Guid guid) { if (guid == Guid.Empty) { return default(GuidHandle); } GuidHandle result; if (_guids.TryGetValue(guid, out result)) { return result; } result = MetadataTokens.GuidHandle((_guidWriter.Count >> 4) + 1); _guids.Add(guid, result); _guidWriter.WriteBytes(guid.ToByteArray()); return result; } #endregion #region Spans private BlobHandle SerializeSpans( ImmutableArray<SourceSpan> spans, Dictionary<DebugSourceDocument, int> documentIndex) { if (spans.Length == 0) { return default(BlobHandle); } // 4 bytes per span plus a header, the builder expands by the same amount. var writer = new BlobBuilder(4 + spans.Length * 4); int previousStartLine = -1; int previousStartColumn = -1; DebugSourceDocument previousDocument = spans[0].Document; // header: writer.WriteCompressedInteger(GetOrAddDocument(previousDocument, documentIndex)); for (int i = 0; i < spans.Length; i++) { var currentDocument = spans[i].Document; if (previousDocument != currentDocument) { writer.WriteInt16(0); writer.WriteCompressedInteger(GetOrAddDocument(currentDocument, documentIndex)); previousDocument = currentDocument; } // Delta Lines & Columns: SerializeDeltaLinesAndColumns(writer, spans[i]); // delta Start Lines & Columns: if (previousStartLine < 0) { Debug.Assert(previousStartColumn < 0); writer.WriteCompressedInteger(spans[i].StartLine); writer.WriteCompressedInteger(spans[i].StartColumn); } else { writer.WriteCompressedSignedInteger(spans[i].StartLine - previousStartLine); writer.WriteCompressedSignedInteger(spans[i].StartColumn - previousStartColumn); } previousStartLine = spans[i].StartLine; previousStartColumn = spans[i].StartColumn; } return GetOrAddBlob(writer); } private void SerializeDeltaLinesAndColumns(BlobBuilder writer, SourceSpan span) { int deltaLines = span.EndLine - span.StartLine; int deltaColumns = span.EndColumn - span.StartColumn; // spans can't have zero width Debug.Assert(deltaLines != 0 || deltaColumns != 0); writer.WriteCompressedInteger(deltaLines); if (deltaLines == 0) { writer.WriteCompressedInteger(deltaColumns); } else { writer.WriteCompressedSignedInteger(deltaColumns); } } #endregion #region Documents internal int GetOrAddDocument(DebugSourceDocument document) { return GetOrAddDocument(document, _documentIndex); } private int GetOrAddDocument(DebugSourceDocument document, Dictionary<DebugSourceDocument, int> index) { int documentRowId; if (!index.TryGetValue(document, out documentRowId)) { documentRowId = _documentTable.Count + 1; index.Add(document, documentRowId); var sourceInfo = document.GetSourceInfo(); _documentTable.Add(new DocumentRow { Name = SerializeDocumentName(document.Location), HashAlgorithm = (sourceInfo.Checksum.IsDefault ? default(GuidHandle) : GetOrAddGuid(sourceInfo.ChecksumAlgorithmId)), Hash = (sourceInfo.Checksum.IsDefault) ? default(BlobHandle) : GetOrAddBlob(sourceInfo.Checksum) }); } return documentRowId; } private static readonly char[] s_separator1 = { '/' }; private static readonly char[] s_separator2 = { '\\' }; private BlobHandle SerializeDocumentName(string name) { Debug.Assert(name != null); int c1 = Count(name, s_separator1[0]); int c2 = Count(name, s_separator2[0]); char[] separator = (c1 >= c2) ? s_separator1 : s_separator2; // Estimate 2 bytes per part, if the blob heap gets big we expand the builder once. var writer = new BlobBuilder(1 + Math.Max(c1, c2) * 2); writer.WriteByte((byte)separator[0]); // TODO: avoid allocations foreach (var part in name.Split(separator)) { BlobHandle partIndex = GetOrAddBlob(ImmutableArray.Create(MetadataWriter.s_utf8Encoding.GetBytes(part))); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(partIndex)); } return GetOrAddBlob(writer); } private static int Count(string str, char c) { int count = 0; for (int i = 0; i < str.Length; i++) { if (str[i] == c) { count++; } } return count; } #endregion #region Table Serialization private struct Sizes { public readonly int BlobHeapSize; public readonly int GuidHeapSize; public readonly int BlobIndexSize; public readonly int GuidIndexSize; public Sizes(int blobHeapSize, int guidHeapSize) { BlobHeapSize = blobHeapSize; GuidHeapSize = guidHeapSize; BlobIndexSize = (blobHeapSize <= ushort.MaxValue) ? 2 : 4; GuidIndexSize = (guidHeapSize <= ushort.MaxValue) ? 2 : 4; } } internal void SerializeMetadataTables(BlobBuilder writer) { var sizes = new Sizes(_blobHeapSize, _guidWriter.Count); SerializeHeader(writer, sizes); // tables: SerializeDocumentTable(writer, sizes); SerializeMethodTable(writer, sizes); // heaps: writer.LinkSuffix(_guidWriter); WriteBlobHeap(writer); } private void WriteBlobHeap(BlobBuilder builder) { var writer = new BlobWriter(builder.ReserveBytes(_blobHeapSize)); // Perf consideration: With large heap the following loop may cause a lot of cache misses // since the order of entries in _blobs dictionary depends on the hash of the array values, // which is not correlated to the heap index. If we observe such issue we should order // the entries by heap position before running this loop. foreach (var entry in _blobs) { int heapOffset = MetadataTokens.GetHeapOffset(entry.Value); var blob = entry.Key; writer.Offset = heapOffset; writer.WriteCompressedInteger(blob.Length); writer.WriteBytes(blob); } } private void SerializeHeader(BlobBuilder writer, Sizes sizes) { // signature: writer.WriteByte((byte)'D'); writer.WriteByte((byte)'A'); writer.WriteByte((byte)'M'); writer.WriteByte((byte)'D'); // version: 0.2 writer.WriteByte(0); writer.WriteByte(2); // table sizes: writer.WriteInt32(_documentTable.Count); writer.WriteInt32(_methodTable.Count); // blob heap sizes: writer.WriteInt32(sizes.GuidHeapSize); writer.WriteInt32(sizes.BlobHeapSize); } private void SerializeDocumentTable(BlobBuilder writer, Sizes sizes) { foreach (var row in _documentTable) { writer.WriteReference(MetadataTokens.GetHeapOffset(row.Name), isSmall: (sizes.BlobIndexSize == 2)); writer.WriteReference(MetadataTokens.GetHeapOffset(row.HashAlgorithm), isSmall: (sizes.GuidIndexSize == 2)); writer.WriteReference(MetadataTokens.GetHeapOffset(row.Hash), isSmall: (sizes.BlobIndexSize == 2)); } } private void SerializeMethodTable(BlobBuilder writer, Sizes sizes) { foreach (var row in _methodTable) { writer.WriteReference(MetadataTokens.GetHeapOffset(row.Spans), isSmall: (sizes.BlobIndexSize == 2)); } } #endregion } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.Cci { internal class DynamicAnalysisDataWriter { private struct DocumentRow { public BlobHandle Name; public GuidHandle HashAlgorithm; public BlobHandle Hash; } private struct MethodRow { public BlobHandle Spans; } // #Blob heap private readonly Dictionary<ImmutableArray<byte>, BlobHandle> _blobs; private int _blobHeapSize; // #GUID heap private readonly Dictionary<Guid, GuidHandle> _guids; private readonly BlobBuilder _guidWriter; // tables: private readonly List<DocumentRow> _documentTable; private readonly List<MethodRow> _methodTable; private readonly Dictionary<DebugSourceDocument, int> _documentIndex; public DynamicAnalysisDataWriter(int documentCountEstimate, int methodCountEstimate) { // Most methods will have a span blob, each document has a hash blob and at least two blobs encoding the name // (adding one more blob per document to account for all directory names): _blobs = new Dictionary<ImmutableArray<byte>, BlobHandle>(1 + methodCountEstimate + 4 * documentCountEstimate, ByteSequenceComparer.Instance); // Each document has a unique guid: const int guidSize = 16; _guids = new Dictionary<Guid, GuidHandle>(documentCountEstimate); _guidWriter = new BlobBuilder(guidSize * documentCountEstimate); _documentTable = new List<DocumentRow>(documentCountEstimate); _documentIndex = new Dictionary<DebugSourceDocument, int>(documentCountEstimate); _methodTable = new List<MethodRow>(methodCountEstimate); _blobs.Add(ImmutableArray<byte>.Empty, default(BlobHandle)); _blobHeapSize = 1; } internal void SerializeMethodDynamicAnalysisData(IMethodBody bodyOpt) { var data = bodyOpt?.DynamicAnalysisData; if (data == null) { _methodTable.Add(default(MethodRow)); return; } BlobHandle spanBlob = SerializeSpans(data.Spans, _documentIndex); _methodTable.Add(new MethodRow { Spans = spanBlob }); } #region Heaps private BlobHandle GetOrAddBlob(BlobBuilder builder) { // TODO: avoid making a copy if the blob exists in the index return GetOrAddBlob(builder.ToImmutableArray()); } private BlobHandle GetOrAddBlob(ImmutableArray<byte> blob) { BlobHandle index; if (!_blobs.TryGetValue(blob, out index)) { index = MetadataTokens.BlobHandle(_blobHeapSize); _blobs.Add(blob, index); _blobHeapSize += GetCompressedIntegerLength(blob.Length) + blob.Length; } return index; } private static int GetCompressedIntegerLength(int length) { return (length <= 0x7f) ? 1 : ((length <= 0x3fff) ? 2 : 4); } private GuidHandle GetOrAddGuid(Guid guid) { if (guid == Guid.Empty) { return default(GuidHandle); } GuidHandle result; if (_guids.TryGetValue(guid, out result)) { return result; } result = MetadataTokens.GuidHandle((_guidWriter.Count >> 4) + 1); _guids.Add(guid, result); _guidWriter.WriteBytes(guid.ToByteArray()); return result; } #endregion #region Spans private BlobHandle SerializeSpans( ImmutableArray<SourceSpan> spans, Dictionary<DebugSourceDocument, int> documentIndex) { if (spans.Length == 0) { return default(BlobHandle); } // 4 bytes per span plus a header, the builder expands by the same amount. var writer = new BlobBuilder(4 + spans.Length * 4); int previousStartLine = -1; int previousStartColumn = -1; DebugSourceDocument previousDocument = spans[0].Document; // header: writer.WriteCompressedInteger(GetOrAddDocument(previousDocument, documentIndex)); for (int i = 0; i < spans.Length; i++) { var currentDocument = spans[i].Document; if (previousDocument != currentDocument) { writer.WriteInt16(0); writer.WriteCompressedInteger(GetOrAddDocument(currentDocument, documentIndex)); previousDocument = currentDocument; } // Delta Lines & Columns: SerializeDeltaLinesAndColumns(writer, spans[i]); // delta Start Lines & Columns: if (previousStartLine < 0) { Debug.Assert(previousStartColumn < 0); writer.WriteCompressedInteger(spans[i].StartLine); writer.WriteCompressedInteger(spans[i].StartColumn); } else { writer.WriteCompressedSignedInteger(spans[i].StartLine - previousStartLine); writer.WriteCompressedSignedInteger(spans[i].StartColumn - previousStartColumn); } previousStartLine = spans[i].StartLine; previousStartColumn = spans[i].StartColumn; } return GetOrAddBlob(writer); } private void SerializeDeltaLinesAndColumns(BlobBuilder writer, SourceSpan span) { int deltaLines = span.EndLine - span.StartLine; int deltaColumns = span.EndColumn - span.StartColumn; // spans can't have zero width Debug.Assert(deltaLines != 0 || deltaColumns != 0); writer.WriteCompressedInteger(deltaLines); if (deltaLines == 0) { writer.WriteCompressedInteger(deltaColumns); } else { writer.WriteCompressedSignedInteger(deltaColumns); } } #endregion #region Documents internal int GetOrAddDocument(DebugSourceDocument document) { return GetOrAddDocument(document, _documentIndex); } private int GetOrAddDocument(DebugSourceDocument document, Dictionary<DebugSourceDocument, int> index) { int documentRowId; if (!index.TryGetValue(document, out documentRowId)) { documentRowId = _documentTable.Count + 1; index.Add(document, documentRowId); var sourceInfo = document.GetSourceInfo(); _documentTable.Add(new DocumentRow { Name = SerializeDocumentName(document.Location), HashAlgorithm = (sourceInfo.Checksum.IsDefault ? default(GuidHandle) : GetOrAddGuid(sourceInfo.ChecksumAlgorithmId)), Hash = (sourceInfo.Checksum.IsDefault) ? default(BlobHandle) : GetOrAddBlob(sourceInfo.Checksum) }); } return documentRowId; } private static readonly char[] s_separator1 = { '/' }; private static readonly char[] s_separator2 = { '\\' }; private BlobHandle SerializeDocumentName(string name) { Debug.Assert(name != null); int c1 = Count(name, s_separator1[0]); int c2 = Count(name, s_separator2[0]); char[] separator = (c1 >= c2) ? s_separator1 : s_separator2; // Estimate 2 bytes per part, if the blob heap gets big we expand the builder once. var writer = new BlobBuilder(1 + Math.Max(c1, c2) * 2); writer.WriteByte((byte)separator[0]); // TODO: avoid allocations foreach (var part in name.Split(separator)) { BlobHandle partIndex = GetOrAddBlob(ImmutableArray.Create(MetadataWriter.s_utf8Encoding.GetBytes(part))); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(partIndex)); } return GetOrAddBlob(writer); } private static int Count(string str, char c) { int count = 0; for (int i = 0; i < str.Length; i++) { if (str[i] == c) { count++; } } return count; } #endregion #region Table Serialization private struct Sizes { public readonly int BlobHeapSize; public readonly int GuidHeapSize; public readonly int BlobIndexSize; public readonly int GuidIndexSize; public Sizes(int blobHeapSize, int guidHeapSize) { BlobHeapSize = blobHeapSize; GuidHeapSize = guidHeapSize; BlobIndexSize = (blobHeapSize <= ushort.MaxValue) ? 2 : 4; GuidIndexSize = (guidHeapSize <= ushort.MaxValue) ? 2 : 4; } } internal void SerializeMetadataTables(BlobBuilder writer) { var sizes = new Sizes(_blobHeapSize, _guidWriter.Count); SerializeHeader(writer, sizes); // tables: SerializeDocumentTable(writer, sizes); SerializeMethodTable(writer, sizes); // heaps: writer.LinkSuffix(_guidWriter); WriteBlobHeap(writer); } private void WriteBlobHeap(BlobBuilder builder) { var writer = new BlobWriter(builder.ReserveBytes(_blobHeapSize)); // Perf consideration: With large heap the following loop may cause a lot of cache misses // since the order of entries in _blobs dictionary depends on the hash of the array values, // which is not correlated to the heap index. If we observe such issue we should order // the entries by heap position before running this loop. foreach (var entry in _blobs) { int heapOffset = MetadataTokens.GetHeapOffset(entry.Value); var blob = entry.Key; writer.Offset = heapOffset; writer.WriteCompressedInteger(blob.Length); writer.WriteBytes(blob); } } private void SerializeHeader(BlobBuilder writer, Sizes sizes) { // signature: writer.WriteByte((byte)'D'); writer.WriteByte((byte)'A'); writer.WriteByte((byte)'M'); writer.WriteByte((byte)'D'); // version: 0.2 writer.WriteByte(0); writer.WriteByte(2); // table sizes: writer.WriteInt32(_documentTable.Count); writer.WriteInt32(_methodTable.Count); // blob heap sizes: writer.WriteInt32(sizes.GuidHeapSize); writer.WriteInt32(sizes.BlobHeapSize); } private void SerializeDocumentTable(BlobBuilder writer, Sizes sizes) { foreach (var row in _documentTable) { writer.WriteReference(MetadataTokens.GetHeapOffset(row.Name), isSmall: (sizes.BlobIndexSize == 2)); writer.WriteReference(MetadataTokens.GetHeapOffset(row.HashAlgorithm), isSmall: (sizes.GuidIndexSize == 2)); writer.WriteReference(MetadataTokens.GetHeapOffset(row.Hash), isSmall: (sizes.BlobIndexSize == 2)); } } private void SerializeMethodTable(BlobBuilder writer, Sizes sizes) { foreach (var row in _methodTable) { writer.WriteReference(MetadataTokens.GetHeapOffset(row.Spans), isSmall: (sizes.BlobIndexSize == 2)); } } #endregion } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Test/AssemblyReferenceTests.cs
// 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. #nullable disable using System.Linq; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests { /// <summary> /// VS for mac has some restrictions on the assemblies that they can load. /// These tests are created to make sure we don't accidentally add references to the dlls that they cannot load. /// </summary> public class AssemblyReferenceTests { [Fact, WorkItem(26642, "https://github.com/dotnet/roslyn/issues/26642")] public void TestNoReferenceToImageCatalog() { var editorsFeatureAssembly = typeof(Microsoft.CodeAnalysis.Editor.Shared.Extensions.GlyphExtensions).Assembly; var dependencies = editorsFeatureAssembly.GetReferencedAssemblies(); Assert.Empty(dependencies.Where(a => a.FullName.Contains("Microsoft.VisualStudio.ImageCatalog"))); } [Fact] public void TestNoReferenceToImagingInterop() { var editorsFeatureAssembly = typeof(Microsoft.CodeAnalysis.Editor.Shared.Extensions.GlyphExtensions).Assembly; var dependencies = editorsFeatureAssembly.GetReferencedAssemblies(); Assert.Empty(dependencies.Where(a => a.FullName.Contains("Microsoft.VisualStudio.Imaging.Interop"))); } } }
// 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. #nullable disable using System.Linq; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests { /// <summary> /// VS for mac has some restrictions on the assemblies that they can load. /// These tests are created to make sure we don't accidentally add references to the dlls that they cannot load. /// </summary> public class AssemblyReferenceTests { [Fact, WorkItem(26642, "https://github.com/dotnet/roslyn/issues/26642")] public void TestNoReferenceToImageCatalog() { var editorsFeatureAssembly = typeof(Microsoft.CodeAnalysis.Editor.Shared.Extensions.GlyphExtensions).Assembly; var dependencies = editorsFeatureAssembly.GetReferencedAssemblies(); Assert.Empty(dependencies.Where(a => a.FullName.Contains("Microsoft.VisualStudio.ImageCatalog"))); } [Fact] public void TestNoReferenceToImagingInterop() { var editorsFeatureAssembly = typeof(Microsoft.CodeAnalysis.Editor.Shared.Extensions.GlyphExtensions).Assembly; var dependencies = editorsFeatureAssembly.GetReferencedAssemblies(); Assert.Empty(dependencies.Where(a => a.FullName.Contains("Microsoft.VisualStudio.Imaging.Interop"))); } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EEDisplayClassFieldLocalSymbol.cs
// 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. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using System.Collections.Immutable; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { /// <summary> /// A display class field representing a local, exposed /// as a local on the original method. /// </summary> internal sealed class EEDisplayClassFieldLocalSymbol : EELocalSymbolBase { private readonly DisplayClassVariable _variable; public EEDisplayClassFieldLocalSymbol(DisplayClassVariable variable) { _variable = variable; // Verify all type parameters are substituted. Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.Type)); } internal override EELocalSymbolBase ToOtherMethod(MethodSymbol method, TypeMap typeMap) { return new EEDisplayClassFieldLocalSymbol(_variable.ToOtherMethod(method, typeMap)); } public override string Name { get { return _variable.Name; } } internal override LocalDeclarationKind DeclarationKind { get { return LocalDeclarationKind.RegularVariable; } } internal override SyntaxToken IdentifierToken { get { throw ExceptionUtilities.Unreachable; } } public override Symbol ContainingSymbol { get { return _variable.ContainingSymbol; } } public override TypeWithAnnotations TypeWithAnnotations { get { return TypeWithAnnotations.Create(_variable.Type); } } internal override bool IsPinned { get { return false; } } internal override bool IsCompilerGenerated { get { return false; } } public override RefKind RefKind { get { return RefKind.None; } } public override ImmutableArray<Location> Locations { get { return NoLocations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } } }
// 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. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using System.Collections.Immutable; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { /// <summary> /// A display class field representing a local, exposed /// as a local on the original method. /// </summary> internal sealed class EEDisplayClassFieldLocalSymbol : EELocalSymbolBase { private readonly DisplayClassVariable _variable; public EEDisplayClassFieldLocalSymbol(DisplayClassVariable variable) { _variable = variable; // Verify all type parameters are substituted. Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.Type)); } internal override EELocalSymbolBase ToOtherMethod(MethodSymbol method, TypeMap typeMap) { return new EEDisplayClassFieldLocalSymbol(_variable.ToOtherMethod(method, typeMap)); } public override string Name { get { return _variable.Name; } } internal override LocalDeclarationKind DeclarationKind { get { return LocalDeclarationKind.RegularVariable; } } internal override SyntaxToken IdentifierToken { get { throw ExceptionUtilities.Unreachable; } } public override Symbol ContainingSymbol { get { return _variable.ContainingSymbol; } } public override TypeWithAnnotations TypeWithAnnotations { get { return TypeWithAnnotations.Create(_variable.Type); } } internal override bool IsPinned { get { return false; } } internal override bool IsCompilerGenerated { get { return false; } } public override RefKind RefKind { get { return RefKind.None; } } public override ImmutableArray<Location> Locations { get { return NoLocations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Syntax/CrefParameterSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public sealed partial class CrefParameterSyntax { /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement property <see cref="RefKindKeyword"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public SyntaxToken RefOrOutKeyword => this.RefKindKeyword; /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement method <see cref="Update"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public CrefParameterSyntax WithRefOrOutKeyword(SyntaxToken refOrOutKeyword) { return this.Update(refOrOutKeyword, this.Type); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public sealed partial class CrefParameterSyntax { /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement property <see cref="RefKindKeyword"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public SyntaxToken RefOrOutKeyword => this.RefKindKeyword; /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement method <see cref="Update"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public CrefParameterSyntax WithRefOrOutKeyword(SyntaxToken refOrOutKeyword) { return this.Update(refOrOutKeyword, this.Type); } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core/Implementation/Structure/StructureTag.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Structure { internal sealed class StructureTag : IStructureTag { private readonly AbstractStructureTaggerProvider _tagProvider; public StructureTag(AbstractStructureTaggerProvider tagProvider, BlockSpan blockSpan, ITextSnapshot snapshot) { Snapshot = snapshot; OutliningSpan = blockSpan.TextSpan.ToSpan(); Type = ConvertType(blockSpan.Type); IsCollapsible = blockSpan.IsCollapsible; IsDefaultCollapsed = blockSpan.IsDefaultCollapsed; IsImplementation = blockSpan.AutoCollapse; if (blockSpan.HintSpan.Start < blockSpan.TextSpan.Start) { // The HeaderSpan is what is used for drawing the guidelines and also what is shown if // you mouse over a guideline. We will use the text from the hint start to the collapsing // start; in the case this spans mutiple lines the editor will clip it for us and suffix an // ellipsis at the end. HeaderSpan = Span.FromBounds(blockSpan.HintSpan.Start, blockSpan.TextSpan.Start); } else { var hintLine = snapshot.GetLineFromPosition(blockSpan.HintSpan.Start); HeaderSpan = AbstractStructureTaggerProvider.TrimLeadingWhitespace(hintLine.Extent); } CollapsedText = blockSpan.BannerText; CollapsedHintFormSpan = blockSpan.HintSpan.ToSpan(); _tagProvider = tagProvider; } /// <summary> /// The contents of the buffer to show if we mouse over the collapsed indicator. /// </summary> public readonly Span CollapsedHintFormSpan; public readonly string CollapsedText; public ITextSnapshot Snapshot { get; } public Span? OutliningSpan { get; } public Span? HeaderSpan { get; } public Span? GuideLineSpan => null; public int? GuideLineHorizontalAnchorPoint => null; public string Type { get; } public bool IsCollapsible { get; } public bool IsDefaultCollapsed { get; } public bool IsImplementation { get; } public object? GetCollapsedForm() { return CollapsedText; } public object? GetCollapsedHintForm() { return _tagProvider.GetCollapsedHintForm(this); } private static string ConvertType(string type) { return type switch { BlockTypes.Conditional => PredefinedStructureTagTypes.Conditional, BlockTypes.Comment => PredefinedStructureTagTypes.Comment, BlockTypes.Expression => PredefinedStructureTagTypes.Expression, BlockTypes.Imports => PredefinedStructureTagTypes.Imports, BlockTypes.Loop => PredefinedStructureTagTypes.Loop, BlockTypes.Member => PredefinedStructureTagTypes.Member, BlockTypes.Namespace => PredefinedStructureTagTypes.Namespace, BlockTypes.Nonstructural => PredefinedStructureTagTypes.Nonstructural, BlockTypes.PreprocessorRegion => PredefinedStructureTagTypes.PreprocessorRegion, BlockTypes.Statement => PredefinedStructureTagTypes.Statement, BlockTypes.Type => PredefinedStructureTagTypes.Type, _ => PredefinedStructureTagTypes.Structural }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Structure { internal sealed class StructureTag : IStructureTag { private readonly AbstractStructureTaggerProvider _tagProvider; public StructureTag(AbstractStructureTaggerProvider tagProvider, BlockSpan blockSpan, ITextSnapshot snapshot) { Snapshot = snapshot; OutliningSpan = blockSpan.TextSpan.ToSpan(); Type = ConvertType(blockSpan.Type); IsCollapsible = blockSpan.IsCollapsible; IsDefaultCollapsed = blockSpan.IsDefaultCollapsed; IsImplementation = blockSpan.AutoCollapse; if (blockSpan.HintSpan.Start < blockSpan.TextSpan.Start) { // The HeaderSpan is what is used for drawing the guidelines and also what is shown if // you mouse over a guideline. We will use the text from the hint start to the collapsing // start; in the case this spans mutiple lines the editor will clip it for us and suffix an // ellipsis at the end. HeaderSpan = Span.FromBounds(blockSpan.HintSpan.Start, blockSpan.TextSpan.Start); } else { var hintLine = snapshot.GetLineFromPosition(blockSpan.HintSpan.Start); HeaderSpan = AbstractStructureTaggerProvider.TrimLeadingWhitespace(hintLine.Extent); } CollapsedText = blockSpan.BannerText; CollapsedHintFormSpan = blockSpan.HintSpan.ToSpan(); _tagProvider = tagProvider; } /// <summary> /// The contents of the buffer to show if we mouse over the collapsed indicator. /// </summary> public readonly Span CollapsedHintFormSpan; public readonly string CollapsedText; public ITextSnapshot Snapshot { get; } public Span? OutliningSpan { get; } public Span? HeaderSpan { get; } public Span? GuideLineSpan => null; public int? GuideLineHorizontalAnchorPoint => null; public string Type { get; } public bool IsCollapsible { get; } public bool IsDefaultCollapsed { get; } public bool IsImplementation { get; } public object? GetCollapsedForm() { return CollapsedText; } public object? GetCollapsedHintForm() { return _tagProvider.GetCollapsedHintForm(this); } private static string ConvertType(string type) { return type switch { BlockTypes.Conditional => PredefinedStructureTagTypes.Conditional, BlockTypes.Comment => PredefinedStructureTagTypes.Comment, BlockTypes.Expression => PredefinedStructureTagTypes.Expression, BlockTypes.Imports => PredefinedStructureTagTypes.Imports, BlockTypes.Loop => PredefinedStructureTagTypes.Loop, BlockTypes.Member => PredefinedStructureTagTypes.Member, BlockTypes.Namespace => PredefinedStructureTagTypes.Namespace, BlockTypes.Nonstructural => PredefinedStructureTagTypes.Nonstructural, BlockTypes.PreprocessorRegion => PredefinedStructureTagTypes.PreprocessorRegion, BlockTypes.Statement => PredefinedStructureTagTypes.Statement, BlockTypes.Type => PredefinedStructureTagTypes.Type, _ => PredefinedStructureTagTypes.Structural }; } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Lowering/Extensions.cs
// 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. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal static partial class OperatorKindExtensions { public static RefKind RefKinds(this ImmutableArray<RefKind> ArgumentRefKinds, int index) { if (!ArgumentRefKinds.IsDefault && index < ArgumentRefKinds.Length) { return ArgumentRefKinds[index]; } else { return RefKind.None; } } } internal static partial class BoundExpressionExtensions { public static bool NullableAlwaysHasValue(this BoundExpression expr) { Debug.Assert(expr != null); if ((object)expr.Type == null) { return false; } if (expr.Type.IsDynamic()) { return false; } if (!expr.Type.IsNullableType()) { return true; } // new int?(123) always has a value: if (expr.Kind == BoundKind.ObjectCreationExpression) { var creation = (BoundObjectCreationExpression)expr; return creation.Constructor.ParameterCount != 0; } else if (expr.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)expr; switch (conversion.ConversionKind) { case ConversionKind.ImplicitNullable: case ConversionKind.ExplicitNullable: // A conversion from X? to Y? will be non-null if the operand is non-null, // so simply recurse. return conversion.Operand.NullableAlwaysHasValue(); case ConversionKind.ImplicitEnumeration: // The C# specification categorizes conversion from literal zero to nullable enum as // an Implicit Enumeration Conversion. return conversion.Operand.NullableAlwaysHasValue(); } } return false; } public static bool NullableNeverHasValue(this BoundExpression expr) { Debug.Assert(expr != null); if ((object)expr.Type == null && expr.ConstantValue == ConstantValue.Null) { return true; } if ((object)expr.Type == null || !expr.Type.IsNullableType()) { return false; } // "default(int?)" and "default" never have a value. if (expr is BoundDefaultLiteral || expr is BoundDefaultExpression) { return true; } // "new int?()" never has a value, but "new int?(x)" always does. if (expr.Kind == BoundKind.ObjectCreationExpression) { var creation = (BoundObjectCreationExpression)expr; return creation.Constructor.ParameterCount == 0; } if (expr.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)expr; switch (conversion.ConversionKind) { case ConversionKind.NullLiteral: // Any null literal conversion is a conversion from the literal null to // a nullable value type; obviously it never has a value. return true; case ConversionKind.DefaultLiteral: // Any default literal to a nullable value type never has a value. return true; case ConversionKind.ImplicitNullable: case ConversionKind.ExplicitNullable: // A conversion from X? to Y? will be null if the operand is null, // so simply recurse. return conversion.Operand.NullableNeverHasValue(); } } // UNDONE: We could be more sophisticated here. For example, most lifted operators that have // UNDONE: a known-to-be-null operand are also known to be null. return false; } public static bool IsNullableNonBoolean(this BoundExpression expr) { Debug.Assert(expr != null); if (expr.Type.IsNullableType() && expr.Type.GetNullableUnderlyingType().SpecialType != SpecialType.System_Boolean) return true; return false; } } }
// 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. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal static partial class OperatorKindExtensions { public static RefKind RefKinds(this ImmutableArray<RefKind> ArgumentRefKinds, int index) { if (!ArgumentRefKinds.IsDefault && index < ArgumentRefKinds.Length) { return ArgumentRefKinds[index]; } else { return RefKind.None; } } } internal static partial class BoundExpressionExtensions { public static bool NullableAlwaysHasValue(this BoundExpression expr) { Debug.Assert(expr != null); if ((object)expr.Type == null) { return false; } if (expr.Type.IsDynamic()) { return false; } if (!expr.Type.IsNullableType()) { return true; } // new int?(123) always has a value: if (expr.Kind == BoundKind.ObjectCreationExpression) { var creation = (BoundObjectCreationExpression)expr; return creation.Constructor.ParameterCount != 0; } else if (expr.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)expr; switch (conversion.ConversionKind) { case ConversionKind.ImplicitNullable: case ConversionKind.ExplicitNullable: // A conversion from X? to Y? will be non-null if the operand is non-null, // so simply recurse. return conversion.Operand.NullableAlwaysHasValue(); case ConversionKind.ImplicitEnumeration: // The C# specification categorizes conversion from literal zero to nullable enum as // an Implicit Enumeration Conversion. return conversion.Operand.NullableAlwaysHasValue(); } } return false; } public static bool NullableNeverHasValue(this BoundExpression expr) { Debug.Assert(expr != null); if ((object)expr.Type == null && expr.ConstantValue == ConstantValue.Null) { return true; } if ((object)expr.Type == null || !expr.Type.IsNullableType()) { return false; } // "default(int?)" and "default" never have a value. if (expr is BoundDefaultLiteral || expr is BoundDefaultExpression) { return true; } // "new int?()" never has a value, but "new int?(x)" always does. if (expr.Kind == BoundKind.ObjectCreationExpression) { var creation = (BoundObjectCreationExpression)expr; return creation.Constructor.ParameterCount == 0; } if (expr.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)expr; switch (conversion.ConversionKind) { case ConversionKind.NullLiteral: // Any null literal conversion is a conversion from the literal null to // a nullable value type; obviously it never has a value. return true; case ConversionKind.DefaultLiteral: // Any default literal to a nullable value type never has a value. return true; case ConversionKind.ImplicitNullable: case ConversionKind.ExplicitNullable: // A conversion from X? to Y? will be null if the operand is null, // so simply recurse. return conversion.Operand.NullableNeverHasValue(); } } // UNDONE: We could be more sophisticated here. For example, most lifted operators that have // UNDONE: a known-to-be-null operand are also known to be null. return false; } public static bool IsNullableNonBoolean(this BoundExpression expr) { Debug.Assert(expr != null); if (expr.Type.IsNullableType() && expr.Type.GetNullableUnderlyingType().SpecialType != SpecialType.System_Boolean) return true; return false; } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/RQName/RQNodeBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Features.RQName.Nodes; namespace Microsoft.CodeAnalysis.Features.RQName { internal static class RQNodeBuilder { /// <summary> /// Builds the RQName for a given symbol. /// </summary> /// <returns>The node if it could be created, otherwise null</returns> public static RQNode? Build(ISymbol symbol) => symbol switch { INamespaceSymbol namespaceSymbol => BuildNamespace(namespaceSymbol), INamedTypeSymbol namedTypeSymbol => BuildUnconstructedNamedType(namedTypeSymbol), IMethodSymbol methodSymbol => BuildMethod(methodSymbol), IFieldSymbol fieldSymbol => BuildField(fieldSymbol), IEventSymbol eventSymbol => BuildEvent(eventSymbol), IPropertySymbol propertySymbol => BuildProperty(propertySymbol), _ => null, }; private static RQNamespace BuildNamespace(INamespaceSymbol @namespace) => new(RQNodeBuilder.GetNameParts(@namespace)); private static IList<string> GetNameParts(INamespaceSymbol @namespace) { var parts = new List<string>(); if (@namespace == null) { return parts; } while ([email protected]) { parts.Add(@namespace.Name); @namespace = @namespace.ContainingNamespace; } parts.Reverse(); return parts; } private static RQUnconstructedType? BuildUnconstructedNamedType(INamedTypeSymbol type) { // Anything that is a valid RQUnconstructed types is ALWAYS safe for public APIs if (type == null) { return null; } // Anonymous types are unsupported if (type.IsAnonymousType) { return null; } // the following types are supported for BuildType() used in signatures, but are not supported // for UnconstructedTypes if (type != type.ConstructedFrom || type.SpecialType == SpecialType.System_Void) { return null; } // make an RQUnconstructedType var namespaceNames = RQNodeBuilder.GetNameParts(@type.ContainingNamespace); var typeInfos = new List<RQUnconstructedTypeInfo>(); for (var currentType = type; currentType != null; currentType = currentType.ContainingType) { typeInfos.Insert(0, new RQUnconstructedTypeInfo(currentType.Name, currentType.TypeParameters.Length)); } return new RQUnconstructedType(namespaceNames, typeInfos); } private static RQMember? BuildField(IFieldSymbol symbol) { var containingType = BuildUnconstructedNamedType(symbol.ContainingType); if (containingType == null) { return null; } return new RQMemberVariable(containingType, symbol.Name); } private static RQProperty? BuildProperty(IPropertySymbol symbol) { RQMethodPropertyOrEventName name = symbol.IsIndexer ? RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryIndexerName() : RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryPropertyName(symbol.Name); if (symbol.ExplicitInterfaceImplementations.Any()) { if (symbol.ExplicitInterfaceImplementations.Length > 1) { return null; } var interfaceType = BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType); if (interfaceType != null) { name = new RQExplicitInterfaceMemberName( interfaceType, (RQOrdinaryMethodPropertyOrEventName)name); } } var containingType = BuildUnconstructedNamedType(symbol.ContainingType); if (containingType == null) { return null; } var parameterList = BuildParameterList(symbol.Parameters); if (parameterList == null) { return null; } return new RQProperty(containingType, name, typeParameterCount: 0, parameters: parameterList); } private static IList<RQParameter>? BuildParameterList(ImmutableArray<IParameterSymbol> parameters) { var parameterList = new List<RQParameter>(); foreach (var parameter in parameters) { var parameterType = BuildType(parameter.Type); if (parameterType == null) { return null; } if (parameter.RefKind == RefKind.Out) { parameterList.Add(new RQOutParameter(parameterType)); } else if (parameter.RefKind == RefKind.Ref) { parameterList.Add(new RQRefParameter(parameterType)); } else { parameterList.Add(new RQNormalParameter(parameterType)); } } return parameterList; } private static RQEvent? BuildEvent(IEventSymbol symbol) { var containingType = BuildUnconstructedNamedType(symbol.ContainingType); if (containingType == null) { return null; } RQMethodPropertyOrEventName name = RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryEventName(symbol.Name); if (symbol.ExplicitInterfaceImplementations.Any()) { if (symbol.ExplicitInterfaceImplementations.Length > 1) { return null; } var interfaceType = BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType); if (interfaceType != null) { name = new RQExplicitInterfaceMemberName(interfaceType, (RQOrdinaryMethodPropertyOrEventName)name); } } return new RQEvent(containingType, name); } private static RQMethod? BuildMethod(IMethodSymbol symbol) { if (symbol.MethodKind is MethodKind.UserDefinedOperator or MethodKind.BuiltinOperator or MethodKind.EventAdd or MethodKind.EventRemove or MethodKind.PropertySet or MethodKind.PropertyGet) { return null; } RQMethodPropertyOrEventName name; if (symbol.MethodKind == MethodKind.Constructor) { name = RQOrdinaryMethodPropertyOrEventName.CreateConstructorName(); } else if (symbol.MethodKind == MethodKind.Destructor) { name = RQOrdinaryMethodPropertyOrEventName.CreateDestructorName(); } else { name = RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryMethodName(symbol.Name); } if (symbol.ExplicitInterfaceImplementations.Any()) { if (symbol.ExplicitInterfaceImplementations.Length > 1) { return null; } var interfaceType = BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType); if (interfaceType != null) { name = new RQExplicitInterfaceMemberName(interfaceType, (RQOrdinaryMethodPropertyOrEventName)name); } } var containingType = BuildUnconstructedNamedType(symbol.ContainingType); if (containingType == null) { return null; } var typeParamCount = symbol.TypeParameters.Length; var parameterList = BuildParameterList(symbol.Parameters); if (parameterList == null) { return null; } return new RQMethod(containingType, name, typeParamCount, parameterList); } private static RQType? BuildType(ITypeSymbol symbol) { if (symbol.IsAnonymousType) { return null; } if (symbol.SpecialType == SpecialType.System_Void) { return RQVoidType.Singleton; } else if (symbol is IPointerTypeSymbol pointerType) { var pointedAtType = BuildType(pointerType.PointedAtType); if (pointedAtType == null) { return null; } return new RQPointerType(pointedAtType); } else if (symbol is IArrayTypeSymbol arrayType) { var elementType = BuildType(arrayType.ElementType); if (elementType == null) { return null; } return new RQArrayType(arrayType.Rank, elementType); } else if (symbol.TypeKind == TypeKind.TypeParameter) { return new RQTypeVariableType(symbol.Name); } else if (symbol.TypeKind == TypeKind.Unknown) { return new RQErrorType(symbol.Name); } else if (symbol.TypeKind == TypeKind.Dynamic) { // NOTE: Because RQNames were defined as an interchange format before C# had "dynamic", and we didn't want // all consumers to have to update their logic to crack the attributes about whether something is object or // not, we just erase dynamic to object here. return RQType.ObjectType; } else if (symbol is INamedTypeSymbol namedTypeSymbol) { var definingType = namedTypeSymbol.ConstructedFrom ?? namedTypeSymbol; var typeChain = new List<INamedTypeSymbol>(); var type = namedTypeSymbol; typeChain.Add(namedTypeSymbol); while (type.ContainingType != null) { type = type.ContainingType; typeChain.Add(type); } typeChain.Reverse(); var typeArgumentList = new List<RQType>(); foreach (var entry in typeChain) { foreach (var typeArgument in entry.TypeArguments) { var rqType = BuildType(typeArgument); if (rqType == null) { return null; } typeArgumentList.Add(rqType); } } var containingType = BuildUnconstructedNamedType(definingType); if (containingType == null) { return null; } return new RQConstructedType(containingType, typeArgumentList); } else { return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Features.RQName.Nodes; namespace Microsoft.CodeAnalysis.Features.RQName { internal static class RQNodeBuilder { /// <summary> /// Builds the RQName for a given symbol. /// </summary> /// <returns>The node if it could be created, otherwise null</returns> public static RQNode? Build(ISymbol symbol) => symbol switch { INamespaceSymbol namespaceSymbol => BuildNamespace(namespaceSymbol), INamedTypeSymbol namedTypeSymbol => BuildUnconstructedNamedType(namedTypeSymbol), IMethodSymbol methodSymbol => BuildMethod(methodSymbol), IFieldSymbol fieldSymbol => BuildField(fieldSymbol), IEventSymbol eventSymbol => BuildEvent(eventSymbol), IPropertySymbol propertySymbol => BuildProperty(propertySymbol), _ => null, }; private static RQNamespace BuildNamespace(INamespaceSymbol @namespace) => new(RQNodeBuilder.GetNameParts(@namespace)); private static IList<string> GetNameParts(INamespaceSymbol @namespace) { var parts = new List<string>(); if (@namespace == null) { return parts; } while ([email protected]) { parts.Add(@namespace.Name); @namespace = @namespace.ContainingNamespace; } parts.Reverse(); return parts; } private static RQUnconstructedType? BuildUnconstructedNamedType(INamedTypeSymbol type) { // Anything that is a valid RQUnconstructed types is ALWAYS safe for public APIs if (type == null) { return null; } // Anonymous types are unsupported if (type.IsAnonymousType) { return null; } // the following types are supported for BuildType() used in signatures, but are not supported // for UnconstructedTypes if (type != type.ConstructedFrom || type.SpecialType == SpecialType.System_Void) { return null; } // make an RQUnconstructedType var namespaceNames = RQNodeBuilder.GetNameParts(@type.ContainingNamespace); var typeInfos = new List<RQUnconstructedTypeInfo>(); for (var currentType = type; currentType != null; currentType = currentType.ContainingType) { typeInfos.Insert(0, new RQUnconstructedTypeInfo(currentType.Name, currentType.TypeParameters.Length)); } return new RQUnconstructedType(namespaceNames, typeInfos); } private static RQMember? BuildField(IFieldSymbol symbol) { var containingType = BuildUnconstructedNamedType(symbol.ContainingType); if (containingType == null) { return null; } return new RQMemberVariable(containingType, symbol.Name); } private static RQProperty? BuildProperty(IPropertySymbol symbol) { RQMethodPropertyOrEventName name = symbol.IsIndexer ? RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryIndexerName() : RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryPropertyName(symbol.Name); if (symbol.ExplicitInterfaceImplementations.Any()) { if (symbol.ExplicitInterfaceImplementations.Length > 1) { return null; } var interfaceType = BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType); if (interfaceType != null) { name = new RQExplicitInterfaceMemberName( interfaceType, (RQOrdinaryMethodPropertyOrEventName)name); } } var containingType = BuildUnconstructedNamedType(symbol.ContainingType); if (containingType == null) { return null; } var parameterList = BuildParameterList(symbol.Parameters); if (parameterList == null) { return null; } return new RQProperty(containingType, name, typeParameterCount: 0, parameters: parameterList); } private static IList<RQParameter>? BuildParameterList(ImmutableArray<IParameterSymbol> parameters) { var parameterList = new List<RQParameter>(); foreach (var parameter in parameters) { var parameterType = BuildType(parameter.Type); if (parameterType == null) { return null; } if (parameter.RefKind == RefKind.Out) { parameterList.Add(new RQOutParameter(parameterType)); } else if (parameter.RefKind == RefKind.Ref) { parameterList.Add(new RQRefParameter(parameterType)); } else { parameterList.Add(new RQNormalParameter(parameterType)); } } return parameterList; } private static RQEvent? BuildEvent(IEventSymbol symbol) { var containingType = BuildUnconstructedNamedType(symbol.ContainingType); if (containingType == null) { return null; } RQMethodPropertyOrEventName name = RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryEventName(symbol.Name); if (symbol.ExplicitInterfaceImplementations.Any()) { if (symbol.ExplicitInterfaceImplementations.Length > 1) { return null; } var interfaceType = BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType); if (interfaceType != null) { name = new RQExplicitInterfaceMemberName(interfaceType, (RQOrdinaryMethodPropertyOrEventName)name); } } return new RQEvent(containingType, name); } private static RQMethod? BuildMethod(IMethodSymbol symbol) { if (symbol.MethodKind is MethodKind.UserDefinedOperator or MethodKind.BuiltinOperator or MethodKind.EventAdd or MethodKind.EventRemove or MethodKind.PropertySet or MethodKind.PropertyGet) { return null; } RQMethodPropertyOrEventName name; if (symbol.MethodKind == MethodKind.Constructor) { name = RQOrdinaryMethodPropertyOrEventName.CreateConstructorName(); } else if (symbol.MethodKind == MethodKind.Destructor) { name = RQOrdinaryMethodPropertyOrEventName.CreateDestructorName(); } else { name = RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryMethodName(symbol.Name); } if (symbol.ExplicitInterfaceImplementations.Any()) { if (symbol.ExplicitInterfaceImplementations.Length > 1) { return null; } var interfaceType = BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType); if (interfaceType != null) { name = new RQExplicitInterfaceMemberName(interfaceType, (RQOrdinaryMethodPropertyOrEventName)name); } } var containingType = BuildUnconstructedNamedType(symbol.ContainingType); if (containingType == null) { return null; } var typeParamCount = symbol.TypeParameters.Length; var parameterList = BuildParameterList(symbol.Parameters); if (parameterList == null) { return null; } return new RQMethod(containingType, name, typeParamCount, parameterList); } private static RQType? BuildType(ITypeSymbol symbol) { if (symbol.IsAnonymousType) { return null; } if (symbol.SpecialType == SpecialType.System_Void) { return RQVoidType.Singleton; } else if (symbol is IPointerTypeSymbol pointerType) { var pointedAtType = BuildType(pointerType.PointedAtType); if (pointedAtType == null) { return null; } return new RQPointerType(pointedAtType); } else if (symbol is IArrayTypeSymbol arrayType) { var elementType = BuildType(arrayType.ElementType); if (elementType == null) { return null; } return new RQArrayType(arrayType.Rank, elementType); } else if (symbol.TypeKind == TypeKind.TypeParameter) { return new RQTypeVariableType(symbol.Name); } else if (symbol.TypeKind == TypeKind.Unknown) { return new RQErrorType(symbol.Name); } else if (symbol.TypeKind == TypeKind.Dynamic) { // NOTE: Because RQNames were defined as an interchange format before C# had "dynamic", and we didn't want // all consumers to have to update their logic to crack the attributes about whether something is object or // not, we just erase dynamic to object here. return RQType.ObjectType; } else if (symbol is INamedTypeSymbol namedTypeSymbol) { var definingType = namedTypeSymbol.ConstructedFrom ?? namedTypeSymbol; var typeChain = new List<INamedTypeSymbol>(); var type = namedTypeSymbol; typeChain.Add(namedTypeSymbol); while (type.ContainingType != null) { type = type.ContainingType; typeChain.Add(type); } typeChain.Reverse(); var typeArgumentList = new List<RQType>(); foreach (var entry in typeChain) { foreach (var typeArgument in entry.TypeArguments) { var rqType = BuildType(typeArgument); if (rqType == null) { return null; } typeArgumentList.Add(rqType); } } var containingType = BuildUnconstructedNamedType(definingType); if (containingType == null) { return null; } return new RQConstructedType(containingType, typeArgumentList); } else { return null; } } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.cs
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameters() { var markup = @" static class Ext { /// <summary> /// This is a summary of <see cref=""M(object, int, string, bool, int, string, int[])""/> /// </summary> /// <param name=""o""></param> /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> /// <param name=""x""></param> /// <param name=""y""></param> /// <param name=""p""></param> static void $$M(this object o, int a, string b, bool c, int x = 0, string y = ""Zero"", params int[] p) { object t = new object(); M(t, 1, ""two"", true, 3, ""four"", new[] { 5, 6 }); M(t, 1, ""two"", true, 3, ""four"", 5, 6); t.M(1, ""two"", true, 3, ""four"", new[] { 5, 6 }); t.M(1, ""two"", true, 3, ""four"", 5, 6); M(t, 1, ""two"", true, 3, ""four""); M(t, 1, ""two"", true, 3); M(t, 1, ""two"", true); M(t, 1, ""two"", c: true); M(t, 1, ""two"", true, 3, y: ""four""); M(t, 1, ""two"", true, 3, p: new[] { 5 }); M(t, 1, ""two"", true, p: new[] { 5 }); M(t, 1, ""two"", true, y: ""four""); M(t, 1, ""two"", true, x: 3); M(t, 1, ""two"", true, y: ""four"", x: 3); M(t, 1, y: ""four"", x: 3, b: ""two"", c: true); M(t, y: ""four"", x: 3, c: true, b: ""two"", a: 1); M(t, p: new[] { 5 }, y: ""four"", x: 3, c: true, b: ""two"", a: 1); M(p: new[] { 5 }, y: ""four"", x: 3, c: true, b: ""two"", a: 1, o: t); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "System.Int32"), new AddedParameterOrExistingIndex(new AddedParameter(null, "string", "newString", CallSiteKind.Value, ""), "System.String"), new AddedParameterOrExistingIndex(5)}; var updatedCode = @" static class Ext { /// <summary> /// This is a summary of <see cref=""M(object, string, int, string, string)""/> /// </summary> /// <param name=""o""></param> /// <param name=""b""></param> /// <param name=""newIntegerParameter""></param> /// <param name=""newString""></param> /// <param name=""y""></param> /// /// static void M(this object o, string b, int newIntegerParameter, string newString, string y = ""Zero"") { object t = new object(); M(t, ""two"", 12345, , ""four""); M(t, ""two"", 12345, , ""four""); t.M(""two"", 12345, , ""four""); t.M(""two"", 12345, , ""four""); M(t, ""two"", 12345, , ""four""); M(t, ""two"", 12345, ); M(t, ""two"", 12345, ); M(t, ""two"", 12345, ); M(t, ""two"", 12345, , y: ""four""); M(t, ""two"", 12345, ); M(t, ""two"", 12345, ); M(t, ""two"", 12345, , y: ""four""); M(t, ""two"", 12345, ); M(t, ""two"", 12345, , y: ""four""); M(t, y: ""four"", newIntegerParameter: 12345, newString:, b: ""two""); M(t, y: ""four"", newIntegerParameter: 12345, newString:, b: ""two""); M(t, y: ""four"", newIntegerParameter: 12345, newString:, b: ""two""); M(y: ""four"", b: ""two"", newIntegerParameter: 12345, newString:, o: t); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameterToParameterlessMethod() { var markup = @" static class Ext { static void $$M() { M(); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "System.Int32")}; var updatedCode = @" static class Ext { static void M(int newIntegerParameter) { M(12345); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderLocalFunctionParametersAndArguments_OnDeclaration() { var markup = @" using System; class MyClass { public void M() { Goo(1, 2); void $$Goo(int x, string y) { } } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" using System; class MyClass { public void M() { Goo(2, 34, 1); void Goo(string y, byte b, int x) { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderLocalFunctionParametersAndArguments_OnInvocation() { var markup = @" using System; class MyClass { public void M() { $$Goo(1, null); void Goo(int x, string y) { } } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" using System; class MyClass { public void M() { Goo(null, 34, 1); void Goo(string y, byte b, int x) { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderMethodParameters() { var markup = @" using System; class MyClass { public void $$Goo(int x, string y) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" using System; class MyClass { public void Goo(string y, byte b, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderMethodParametersAndArguments() { var markup = @" using System; class MyClass { public void $$Goo(int x, string y) { Goo(3, ""hello""); } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" using System; class MyClass { public void Goo(string y, byte b, int x) { Goo(""hello"", 34, 3); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderMethodParametersAndArgumentsOfNestedCalls() { var markup = @" using System; class MyClass { public int $$Goo(int x, string y) { return Goo(Goo(4, ""inner""), ""outer""); } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" using System; class MyClass { public int Goo(string y, byte b, int x) { return Goo(""outer"", 34, Goo(""inner"", 34, 4)); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderConstructorParametersAndArguments() { var markup = @" using System; class MyClass2 : MyClass { public MyClass2() : base(5, ""test2"") { } } class MyClass { public MyClass() : this(2, ""test"") { } public $$MyClass(int x, string y) { var t = new MyClass(x, y); } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), AddedParameterOrExistingIndex.CreateAdded("byte", "b", CallSiteKind.Value, "34"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" using System; class MyClass2 : MyClass { public MyClass2() : base(""test2"", 34, 5) { } } class MyClass { public MyClass() : this(""test"", 34, 2) { } public MyClass(string y, byte b, int x) { var t = new MyClass(y, 34, x); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderAttributeConstructorParametersAndArguments() { var markup = @" [My(""test"", 8)] class MyClass { } class MyAttribute : System.Attribute { public MyAttribute(string x, int y)$$ { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" [My(8, 34, ""test"")] class MyClass { } class MyAttribute : System.Attribute { public MyAttribute(int y, byte b, string x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderExtensionMethodParametersAndArguments_StaticCall() { var markup = @" public class C { static void Main(string[] args) { CExt.M(new C(), 1, 2, ""three"", ""four"", ""five""); } } public static class CExt { public static void M(this $$C goo, int x, int y, string a = ""test_a"", string b = ""test_b"", string c = ""test_c"") { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(5), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(3)}; var updatedCode = @" public class C { static void Main(string[] args) { CExt.M(new C(), 2, 1, 34, ""five"", ""four"", ""three""); } } public static class CExt { public static void M(this C goo, int y, int x, byte b, string c = ""test_c"", string b = ""test_b"", string a = ""test_a"") { } }"; // Although the `ParameterConfig` has 0 for the `SelectedIndex`, the UI dialog will make an adjustment // and select parameter `y` instead because the `this` parameter cannot be moved or removed. await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderExtensionMethodParametersAndArguments_ExtensionCall() { var markup = @" public class C { static void Main(string[] args) { new C().M(1, 2, ""three"", ""four"", ""five""); } } public static class CExt { public static void M(this C goo, int x$$, int y, string a = ""test_a"", string b = ""test_b"", string c = ""test_c"") { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(5), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(3)}; var updatedCode = @" public class C { static void Main(string[] args) { new C().M(2, 1, 34, ""five"", ""four"", ""three""); } } public static class CExt { public static void M(this C goo, int y, int x, byte b, string c = ""test_c"", string b = ""test_b"", string a = ""test_a"") { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 1); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameterWithOmittedArgument_ParamsAsArray() { var markup = @" public class C { void $$M(int x, int y, params int[] p) { M(x, y, p: p); } }"; var permutation = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(1), AddedParameterOrExistingIndex.CreateAdded("int", "z", CallSiteKind.Omitted, isRequired: false, defaultValue: "3"), new AddedParameterOrExistingIndex(2)}; var updatedCode = @" public class C { void M(int x, int y, int z = 3, params int[] p) { M(x, y, p: p); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamsMethodParametersAndArguments_ParamsAsArray() { var markup = @" public class C { void $$M(int x, int y, params int[] p) { M(x, y, new[] { 1, 2, 3 }); } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(2)}; var updatedCode = @" public class C { void M(int y, int x, byte b, params int[] p) { M(y, x, 34, new[] { 1, 2, 3 }); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamsMethodParametersAndArguments_ParamsExpanded() { var markup = @" public class C { void $$M(int x, int y, params int[] p) { M(x, y, 1, 2, 3); } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(2)}; var updatedCode = @" public class C { void M(int y, int x, byte b, params int[] p) { M(y, x, 34, 1, 2, 3); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderExtensionAndParamsMethodParametersAndArguments_VariedCallsites() { var markup = @" public class C { static void Main(string[] args) { CExt.M(new C(), 1, 2, ""three"", ""four"", ""five"", new[] { 6, 7, 8 }); CExt.M(new C(), 1, 2, ""three"", ""four"", ""five"", 6, 7, 8); new C().M(1, 2, ""three"", ""four"", ""five"", new[] { 6, 7, 8 }); new C().M(1, 2, ""three"", ""four"", ""five"", 6, 7, 8); } } public static class CExt { public static void $$M(this C goo, int x, int y, string a = ""test_a"", string b = ""test_b"", string c = ""test_c"", params int[] p) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(5), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(3), new AddedParameterOrExistingIndex(6)}; var updatedCode = @" public class C { static void Main(string[] args) { CExt.M(new C(), 2, 1, 34, ""five"", ""four"", ""three"", new[] { 6, 7, 8 }); CExt.M(new C(), 2, 1, 34, ""five"", ""four"", ""three"", 6, 7, 8); new C().M(2, 1, 34, ""five"", ""four"", ""three"", new[] { 6, 7, 8 }); new C().M(2, 1, 34, ""five"", ""four"", ""three"", 6, 7, 8); } } public static class CExt { public static void M(this C goo, int y, int x, byte b, string c = ""test_c"", string b = ""test_b"", string a = ""test_a"", params int[] p) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderIndexerParametersAndArguments() { var markup = @" class Program { void M() { var x = new Program()[1, 2]; new Program()[1, 2] = x; } public int this[int x, int y]$$ { get { return 5; } set { } } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" class Program { void M() { var x = new Program()[2, 34, 1]; new Program()[2, 34, 1] = x; } public int this[int y, byte b, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_SingleLineDocComments_OnIndividualLines() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""c""></param> /// <param name=""b""></param> /// <param name=""bb""></param> /// <param name=""a""></param> void Goo(int c, int b, byte bb, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_SingleLineDocComments_OnSameLine() { var markup = @" public class C { /// <param name=""a"">a is fun</param><param name=""b"">b is fun</param><param name=""c"">c is fun</param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""c"">c is fun</param><param name=""b"">b is fun</param><param name=""bb""></param> /// <param name=""a"">a is fun</param> void Goo(int c, int b, byte bb, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_SingleLineDocComments_MixedLineDistribution() { var markup = @" public class C { /// <param name=""a""></param><param name=""b""></param> /// <param name=""c""></param> /// <param name=""d""></param> /// <param name=""e"">Comments spread /// over several /// lines</param><param name=""f""></param> void $$Goo(int a, int b, int c, int d, int e, int f) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(5), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(3), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""f""></param><param name=""e"">Comments spread /// over several /// lines</param> /// <param name=""d""></param> /// <param name=""c""></param> /// <param name=""bb""></param><param name=""b""></param> /// <param name=""a""></param> void Goo(int f, int e, int d, int c, byte bb, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_SingleLineDocComments_MixedWithRegularComments() { var markup = @" public class C { /// <param name=""a""></param><param name=""b""></param> // Why is there a regular comment here? /// <param name=""c""></param><param name=""d""></param><param name=""e""></param> void $$Goo(int a, int b, int c, int d, int e) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(3), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""e""></param><param name=""d""></param> // Why is there a regular comment here? /// <param name=""c""></param><param name=""b""></param><param name=""b""></param> /// <param name=""a""></param> void Goo(int e, int d, int c, byte b, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_MultiLineDocComments_OnSeparateLines1() { var markup = @" class Program { /** * <param name=""x"">x!</param> * <param name=""y"">y!</param> * <param name=""z"">z!</param> */ static void $$M(int x, int y, int z) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" class Program { /** * <param name=""z"">z!</param> * <param name=""b""></param> * <param name=""y"">y!</param> */ /// <param name=""x"">x!</param> static void M(int z, byte b, int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_MultiLineDocComments_OnSingleLine() { var markup = @" class Program { /** <param name=""x"">x!</param><param name=""y"">y!</param><param name=""z"">z!</param> */ static void $$M(int x, int y, int z) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" class Program { /** <param name=""z"">z!</param><param name=""b""></param><param name=""y"">y!</param> */ /// <param name=""x"">x!</param> static void M(int z, byte b, int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_IncorrectOrder_MaintainsOrder() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> /// <param name=""b""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> /// <param name=""b""></param> void Goo(int c, byte bb, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_WrongNames_MaintainsOrder() { var markup = @" public class C { /// <param name=""a2""></param> /// <param name=""b""></param> /// <param name=""c""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""a2""></param> /// <param name=""b""></param> /// <param name=""c""></param> void Goo(int c, byte b, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_InsufficientTags_MaintainsOrder() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> void Goo(int c, byte b, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_ExcessiveTags_MaintainsOrder() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> /// <param name=""d""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> /// <param name=""d""></param> void Goo(int c, byte bb, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_OnConstructors() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> public $$C(int a, int b, int c) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""c""></param> /// <param name=""bb""></param> /// <param name=""b""></param> /// <param name=""a""></param> public C(int c, byte bb, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_OnIndexers() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> public int $$this[int a, int b, int c] { get { return 5; } set { } } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""c""></param> /// <param name=""bb""></param> /// <param name=""b""></param> /// <param name=""a""></param> public int this[int c, byte bb, int b, int a] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParametersInCrefs() { var markup = @" class C { /// <summary> /// See <see cref=""M(int, string)""/> and <see cref=""M""/> /// </summary> $$void M(int x, string y) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" class C { /// <summary> /// See <see cref=""M(string, byte, int)""/> and <see cref=""M""/> /// </summary> void M(string y, byte b, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParametersInMethodThatImplementsInterfaceMethodOnlyThroughADerivedType1() { var markup = @" interface I { $$void M(int x, string y); } class C { public void M(int x, string y) { } } class D : C, I { }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" interface I { void M(string y, byte b, int x); } class C { public void M(string y, byte b, int x) { } } class D : C, I { }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParametersInMethodThatImplementsInterfaceMethodOnlyThroughADerivedType2() { var markup = @" interface I { void M(int x, string y); } class C { $$public void M(int x, string y) { } } class D : C, I { }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" interface I { void M(string y, byte b, int x); } class C { public void M(string y, byte b, int x) { } } class D : C, I { }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(43664, "https://github.com/dotnet/roslyn/issues/43664")] public async Task AddParameterOnUnparenthesizedLambda() { var markup = @" using System.Linq; namespace ConsoleApp426 { class Program { static void M(string[] args) { if (args.All(b$$ => Test())) { } } static bool Test() { return true; } } }"; var permutation = new[] { new AddedParameterOrExistingIndex(0), AddedParameterOrExistingIndex.CreateAdded("byte", "bb", CallSiteKind.Value, callSiteValue: "34") }; var updatedCode = @" using System.Linq; namespace ConsoleApp426 { class Program { static void M(string[] args) { if (args.All((b, byte bb) => Test())) { } } static bool Test() { return true; } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(44126, "https://github.com/dotnet/roslyn/issues/44126")] public async Task AddAndReorderImplicitObjectCreationParameter() { var markup = @" using System; class C { $$C(int x, string y) { } public void M() { C _ = new(1, ""y""); } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, callSiteValue: "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" using System; class C { C(string y, byte b, int x) { } public void M() { C _ = new(""y"", 34, 1); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(44558, "https://github.com/dotnet/roslyn/issues/44558")] public async Task AddParameters_Record() { var markup = @" /// <param name=""First""></param> /// <param name=""Second""></param> /// <param name=""Third""></param> record $$R(int First, int Second, int Third) { static R M() => new R(1, 2, 3); } "; var updatedSignature = new AddedParameterOrExistingIndex[] { new(0), new(2), new(1), new(new AddedParameter(null, "int", "Forth", CallSiteKind.Value, "12345"), "System.Int32") }; var updatedCode = @" /// <param name=""First""></param> /// <param name=""Third""></param> /// <param name=""Second""></param> /// <param name=""Forth""></param> record R(int First, int Third, int Second, int Forth) { static R M() => new R(1, 3, 2, 12345); } "; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } } }
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameters() { var markup = @" static class Ext { /// <summary> /// This is a summary of <see cref=""M(object, int, string, bool, int, string, int[])""/> /// </summary> /// <param name=""o""></param> /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> /// <param name=""x""></param> /// <param name=""y""></param> /// <param name=""p""></param> static void $$M(this object o, int a, string b, bool c, int x = 0, string y = ""Zero"", params int[] p) { object t = new object(); M(t, 1, ""two"", true, 3, ""four"", new[] { 5, 6 }); M(t, 1, ""two"", true, 3, ""four"", 5, 6); t.M(1, ""two"", true, 3, ""four"", new[] { 5, 6 }); t.M(1, ""two"", true, 3, ""four"", 5, 6); M(t, 1, ""two"", true, 3, ""four""); M(t, 1, ""two"", true, 3); M(t, 1, ""two"", true); M(t, 1, ""two"", c: true); M(t, 1, ""two"", true, 3, y: ""four""); M(t, 1, ""two"", true, 3, p: new[] { 5 }); M(t, 1, ""two"", true, p: new[] { 5 }); M(t, 1, ""two"", true, y: ""four""); M(t, 1, ""two"", true, x: 3); M(t, 1, ""two"", true, y: ""four"", x: 3); M(t, 1, y: ""four"", x: 3, b: ""two"", c: true); M(t, y: ""four"", x: 3, c: true, b: ""two"", a: 1); M(t, p: new[] { 5 }, y: ""four"", x: 3, c: true, b: ""two"", a: 1); M(p: new[] { 5 }, y: ""four"", x: 3, c: true, b: ""two"", a: 1, o: t); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "System.Int32"), new AddedParameterOrExistingIndex(new AddedParameter(null, "string", "newString", CallSiteKind.Value, ""), "System.String"), new AddedParameterOrExistingIndex(5)}; var updatedCode = @" static class Ext { /// <summary> /// This is a summary of <see cref=""M(object, string, int, string, string)""/> /// </summary> /// <param name=""o""></param> /// <param name=""b""></param> /// <param name=""newIntegerParameter""></param> /// <param name=""newString""></param> /// <param name=""y""></param> /// /// static void M(this object o, string b, int newIntegerParameter, string newString, string y = ""Zero"") { object t = new object(); M(t, ""two"", 12345, , ""four""); M(t, ""two"", 12345, , ""four""); t.M(""two"", 12345, , ""four""); t.M(""two"", 12345, , ""four""); M(t, ""two"", 12345, , ""four""); M(t, ""two"", 12345, ); M(t, ""two"", 12345, ); M(t, ""two"", 12345, ); M(t, ""two"", 12345, , y: ""four""); M(t, ""two"", 12345, ); M(t, ""two"", 12345, ); M(t, ""two"", 12345, , y: ""four""); M(t, ""two"", 12345, ); M(t, ""two"", 12345, , y: ""four""); M(t, y: ""four"", newIntegerParameter: 12345, newString:, b: ""two""); M(t, y: ""four"", newIntegerParameter: 12345, newString:, b: ""two""); M(t, y: ""four"", newIntegerParameter: 12345, newString:, b: ""two""); M(y: ""four"", b: ""two"", newIntegerParameter: 12345, newString:, o: t); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameterToParameterlessMethod() { var markup = @" static class Ext { static void $$M() { M(); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "newIntegerParameter", CallSiteKind.Value, "12345"), "System.Int32")}; var updatedCode = @" static class Ext { static void M(int newIntegerParameter) { M(12345); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderLocalFunctionParametersAndArguments_OnDeclaration() { var markup = @" using System; class MyClass { public void M() { Goo(1, 2); void $$Goo(int x, string y) { } } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" using System; class MyClass { public void M() { Goo(2, 34, 1); void Goo(string y, byte b, int x) { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderLocalFunctionParametersAndArguments_OnInvocation() { var markup = @" using System; class MyClass { public void M() { $$Goo(1, null); void Goo(int x, string y) { } } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" using System; class MyClass { public void M() { Goo(null, 34, 1); void Goo(string y, byte b, int x) { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderMethodParameters() { var markup = @" using System; class MyClass { public void $$Goo(int x, string y) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" using System; class MyClass { public void Goo(string y, byte b, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderMethodParametersAndArguments() { var markup = @" using System; class MyClass { public void $$Goo(int x, string y) { Goo(3, ""hello""); } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" using System; class MyClass { public void Goo(string y, byte b, int x) { Goo(""hello"", 34, 3); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderMethodParametersAndArgumentsOfNestedCalls() { var markup = @" using System; class MyClass { public int $$Goo(int x, string y) { return Goo(Goo(4, ""inner""), ""outer""); } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" using System; class MyClass { public int Goo(string y, byte b, int x) { return Goo(""outer"", 34, Goo(""inner"", 34, 4)); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderConstructorParametersAndArguments() { var markup = @" using System; class MyClass2 : MyClass { public MyClass2() : base(5, ""test2"") { } } class MyClass { public MyClass() : this(2, ""test"") { } public $$MyClass(int x, string y) { var t = new MyClass(x, y); } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), AddedParameterOrExistingIndex.CreateAdded("byte", "b", CallSiteKind.Value, "34"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" using System; class MyClass2 : MyClass { public MyClass2() : base(""test2"", 34, 5) { } } class MyClass { public MyClass() : this(""test"", 34, 2) { } public MyClass(string y, byte b, int x) { var t = new MyClass(y, 34, x); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderAttributeConstructorParametersAndArguments() { var markup = @" [My(""test"", 8)] class MyClass { } class MyAttribute : System.Attribute { public MyAttribute(string x, int y)$$ { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" [My(8, 34, ""test"")] class MyClass { } class MyAttribute : System.Attribute { public MyAttribute(int y, byte b, string x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderExtensionMethodParametersAndArguments_StaticCall() { var markup = @" public class C { static void Main(string[] args) { CExt.M(new C(), 1, 2, ""three"", ""four"", ""five""); } } public static class CExt { public static void M(this $$C goo, int x, int y, string a = ""test_a"", string b = ""test_b"", string c = ""test_c"") { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(5), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(3)}; var updatedCode = @" public class C { static void Main(string[] args) { CExt.M(new C(), 2, 1, 34, ""five"", ""four"", ""three""); } } public static class CExt { public static void M(this C goo, int y, int x, byte b, string c = ""test_c"", string b = ""test_b"", string a = ""test_a"") { } }"; // Although the `ParameterConfig` has 0 for the `SelectedIndex`, the UI dialog will make an adjustment // and select parameter `y` instead because the `this` parameter cannot be moved or removed. await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderExtensionMethodParametersAndArguments_ExtensionCall() { var markup = @" public class C { static void Main(string[] args) { new C().M(1, 2, ""three"", ""four"", ""five""); } } public static class CExt { public static void M(this C goo, int x$$, int y, string a = ""test_a"", string b = ""test_b"", string c = ""test_c"") { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(5), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(3)}; var updatedCode = @" public class C { static void Main(string[] args) { new C().M(2, 1, 34, ""five"", ""four"", ""three""); } } public static class CExt { public static void M(this C goo, int y, int x, byte b, string c = ""test_c"", string b = ""test_b"", string a = ""test_a"") { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 1); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameterWithOmittedArgument_ParamsAsArray() { var markup = @" public class C { void $$M(int x, int y, params int[] p) { M(x, y, p: p); } }"; var permutation = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(1), AddedParameterOrExistingIndex.CreateAdded("int", "z", CallSiteKind.Omitted, isRequired: false, defaultValue: "3"), new AddedParameterOrExistingIndex(2)}; var updatedCode = @" public class C { void M(int x, int y, int z = 3, params int[] p) { M(x, y, p: p); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamsMethodParametersAndArguments_ParamsAsArray() { var markup = @" public class C { void $$M(int x, int y, params int[] p) { M(x, y, new[] { 1, 2, 3 }); } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(2)}; var updatedCode = @" public class C { void M(int y, int x, byte b, params int[] p) { M(y, x, 34, new[] { 1, 2, 3 }); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamsMethodParametersAndArguments_ParamsExpanded() { var markup = @" public class C { void $$M(int x, int y, params int[] p) { M(x, y, 1, 2, 3); } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(2)}; var updatedCode = @" public class C { void M(int y, int x, byte b, params int[] p) { M(y, x, 34, 1, 2, 3); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderExtensionAndParamsMethodParametersAndArguments_VariedCallsites() { var markup = @" public class C { static void Main(string[] args) { CExt.M(new C(), 1, 2, ""three"", ""four"", ""five"", new[] { 6, 7, 8 }); CExt.M(new C(), 1, 2, ""three"", ""four"", ""five"", 6, 7, 8); new C().M(1, 2, ""three"", ""four"", ""five"", new[] { 6, 7, 8 }); new C().M(1, 2, ""three"", ""four"", ""five"", 6, 7, 8); } } public static class CExt { public static void $$M(this C goo, int x, int y, string a = ""test_a"", string b = ""test_b"", string c = ""test_c"", params int[] p) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(5), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(3), new AddedParameterOrExistingIndex(6)}; var updatedCode = @" public class C { static void Main(string[] args) { CExt.M(new C(), 2, 1, 34, ""five"", ""four"", ""three"", new[] { 6, 7, 8 }); CExt.M(new C(), 2, 1, 34, ""five"", ""four"", ""three"", 6, 7, 8); new C().M(2, 1, 34, ""five"", ""four"", ""three"", new[] { 6, 7, 8 }); new C().M(2, 1, 34, ""five"", ""four"", ""three"", 6, 7, 8); } } public static class CExt { public static void M(this C goo, int y, int x, byte b, string c = ""test_c"", string b = ""test_b"", string a = ""test_a"", params int[] p) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderIndexerParametersAndArguments() { var markup = @" class Program { void M() { var x = new Program()[1, 2]; new Program()[1, 2] = x; } public int this[int x, int y]$$ { get { return 5; } set { } } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" class Program { void M() { var x = new Program()[2, 34, 1]; new Program()[2, 34, 1] = x; } public int this[int y, byte b, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_SingleLineDocComments_OnIndividualLines() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""c""></param> /// <param name=""b""></param> /// <param name=""bb""></param> /// <param name=""a""></param> void Goo(int c, int b, byte bb, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_SingleLineDocComments_OnSameLine() { var markup = @" public class C { /// <param name=""a"">a is fun</param><param name=""b"">b is fun</param><param name=""c"">c is fun</param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""c"">c is fun</param><param name=""b"">b is fun</param><param name=""bb""></param> /// <param name=""a"">a is fun</param> void Goo(int c, int b, byte bb, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_SingleLineDocComments_MixedLineDistribution() { var markup = @" public class C { /// <param name=""a""></param><param name=""b""></param> /// <param name=""c""></param> /// <param name=""d""></param> /// <param name=""e"">Comments spread /// over several /// lines</param><param name=""f""></param> void $$Goo(int a, int b, int c, int d, int e, int f) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(5), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(3), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""f""></param><param name=""e"">Comments spread /// over several /// lines</param> /// <param name=""d""></param> /// <param name=""c""></param> /// <param name=""bb""></param><param name=""b""></param> /// <param name=""a""></param> void Goo(int f, int e, int d, int c, byte bb, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_SingleLineDocComments_MixedWithRegularComments() { var markup = @" public class C { /// <param name=""a""></param><param name=""b""></param> // Why is there a regular comment here? /// <param name=""c""></param><param name=""d""></param><param name=""e""></param> void $$Goo(int a, int b, int c, int d, int e) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(3), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""e""></param><param name=""d""></param> // Why is there a regular comment here? /// <param name=""c""></param><param name=""b""></param><param name=""b""></param> /// <param name=""a""></param> void Goo(int e, int d, int c, byte b, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_MultiLineDocComments_OnSeparateLines1() { var markup = @" class Program { /** * <param name=""x"">x!</param> * <param name=""y"">y!</param> * <param name=""z"">z!</param> */ static void $$M(int x, int y, int z) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" class Program { /** * <param name=""z"">z!</param> * <param name=""b""></param> * <param name=""y"">y!</param> */ /// <param name=""x"">x!</param> static void M(int z, byte b, int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_MultiLineDocComments_OnSingleLine() { var markup = @" class Program { /** <param name=""x"">x!</param><param name=""y"">y!</param><param name=""z"">z!</param> */ static void $$M(int x, int y, int z) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" class Program { /** <param name=""z"">z!</param><param name=""b""></param><param name=""y"">y!</param> */ /// <param name=""x"">x!</param> static void M(int z, byte b, int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_IncorrectOrder_MaintainsOrder() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> /// <param name=""b""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> /// <param name=""b""></param> void Goo(int c, byte bb, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_WrongNames_MaintainsOrder() { var markup = @" public class C { /// <param name=""a2""></param> /// <param name=""b""></param> /// <param name=""c""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""a2""></param> /// <param name=""b""></param> /// <param name=""c""></param> void Goo(int c, byte b, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_InsufficientTags_MaintainsOrder() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> void Goo(int c, byte b, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_ExcessiveTags_MaintainsOrder() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> /// <param name=""d""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> /// <param name=""d""></param> void Goo(int c, byte bb, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_OnConstructors() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> public $$C(int a, int b, int c) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""c""></param> /// <param name=""bb""></param> /// <param name=""b""></param> /// <param name=""a""></param> public C(int c, byte bb, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParamTagsInDocComments_OnIndexers() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> public int $$this[int a, int b, int c] { get { return 5; } set { } } }"; var permutation = new[] { new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" public class C { /// <param name=""c""></param> /// <param name=""bb""></param> /// <param name=""b""></param> /// <param name=""a""></param> public int this[int c, byte bb, int b, int a] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParametersInCrefs() { var markup = @" class C { /// <summary> /// See <see cref=""M(int, string)""/> and <see cref=""M""/> /// </summary> $$void M(int x, string y) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" class C { /// <summary> /// See <see cref=""M(string, byte, int)""/> and <see cref=""M""/> /// </summary> void M(string y, byte b, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParametersInMethodThatImplementsInterfaceMethodOnlyThroughADerivedType1() { var markup = @" interface I { $$void M(int x, string y); } class C { public void M(int x, string y) { } } class D : C, I { }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" interface I { void M(string y, byte b, int x); } class C { public void M(string y, byte b, int x) { } } class D : C, I { }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddAndReorderParametersInMethodThatImplementsInterfaceMethodOnlyThroughADerivedType2() { var markup = @" interface I { void M(int x, string y); } class C { $$public void M(int x, string y) { } } class D : C, I { }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" interface I { void M(string y, byte b, int x); } class C { public void M(string y, byte b, int x) { } } class D : C, I { }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(43664, "https://github.com/dotnet/roslyn/issues/43664")] public async Task AddParameterOnUnparenthesizedLambda() { var markup = @" using System.Linq; namespace ConsoleApp426 { class Program { static void M(string[] args) { if (args.All(b$$ => Test())) { } } static bool Test() { return true; } } }"; var permutation = new[] { new AddedParameterOrExistingIndex(0), AddedParameterOrExistingIndex.CreateAdded("byte", "bb", CallSiteKind.Value, callSiteValue: "34") }; var updatedCode = @" using System.Linq; namespace ConsoleApp426 { class Program { static void M(string[] args) { if (args.All((b, byte bb) => Test())) { } } static bool Test() { return true; } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(44126, "https://github.com/dotnet/roslyn/issues/44126")] public async Task AddAndReorderImplicitObjectCreationParameter() { var markup = @" using System; class C { $$C(int x, string y) { } public void M() { C _ = new(1, ""y""); } }"; var permutation = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "b", CallSiteKind.Value, callSiteValue: "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var updatedCode = @" using System; class C { C(string y, byte b, int x) { } public void M() { C _ = new(""y"", 34, 1); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(44558, "https://github.com/dotnet/roslyn/issues/44558")] public async Task AddParameters_Record() { var markup = @" /// <param name=""First""></param> /// <param name=""Second""></param> /// <param name=""Third""></param> record $$R(int First, int Second, int Third) { static R M() => new R(1, 2, 3); } "; var updatedSignature = new AddedParameterOrExistingIndex[] { new(0), new(2), new(1), new(new AddedParameter(null, "int", "Forth", CallSiteKind.Value, "12345"), "System.Int32") }; var updatedCode = @" /// <param name=""First""></param> /// <param name=""Third""></param> /// <param name=""Second""></param> /// <param name=""Forth""></param> record R(int First, int Third, int Second, int Forth) { static R M() => new R(1, 3, 2, 12345); } "; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ChecksumKeywordRecommender.cs
// 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. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ChecksumKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ChecksumKeywordRecommender() : base(SyntaxKind.ChecksumKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { // # pragma | // # pragma w| var previousToken1 = context.TargetToken; var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true); return previousToken1.Kind() == SyntaxKind.PragmaKeyword && previousToken2.Kind() == SyntaxKind.HashToken; } } }
// 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. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ChecksumKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ChecksumKeywordRecommender() : base(SyntaxKind.ChecksumKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { // # pragma | // # pragma w| var previousToken1 = context.TargetToken; var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true); return previousToken1.Kind() == SyntaxKind.PragmaKeyword && previousToken2.Kind() == SyntaxKind.HashToken; } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxNodeTests.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; using System.Text; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxNodeTests { [Fact] [WorkItem(565382, "https://developercommunity.visualstudio.com/content/problem/565382/compiling-causes-a-stack-overflow-error.html")] public void TestLargeFluentCallWithDirective() { var builder = new StringBuilder(); builder.AppendLine( @" class C { C M(string x) { return this; } void M2() { new C() #region Region "); for (int i = 0; i < 20000; i++) { builder.AppendLine(@" .M(""test"")"); } builder.AppendLine( @" .M(""test""); #endregion } }"); var tree = SyntaxFactory.ParseSyntaxTree(builder.ToString()); var directives = tree.GetRoot().GetDirectives(); Assert.Equal(2, directives.Count); } [Fact] public void TestQualifiedNameSyntaxWith() { // this is just a test to prove that at least one generate With method exists and functions correctly. :-) var qname = (QualifiedNameSyntax)SyntaxFactory.ParseName("A.B"); var qname2 = qname.WithRight(SyntaxFactory.IdentifierName("C")); var text = qname2.ToString(); Assert.Equal("A.C", text); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void TestAddBaseListTypes() { var cls = SyntaxFactory.ParseCompilationUnit("class C { }").Members[0] as ClassDeclarationSyntax; var cls2 = cls.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("B"))); } [Fact] public void TestChildNodes() { var text = "m(a,b,c)"; var expression = SyntaxFactory.ParseExpression(text); var nodes = expression.ChildNodes().ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.IdentifierName, nodes[0].Kind()); Assert.Equal(SyntaxKind.ArgumentList, nodes[1].Kind()); } [Fact] public void TestAncestors() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var nodes = e.Ancestors().ToList(); Assert.Equal(7, nodes.Count); Assert.Equal(SyntaxKind.DivideExpression, nodes[0].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.MultiplyExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[3].Kind()); Assert.Equal(SyntaxKind.SubtractExpression, nodes[4].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[5].Kind()); Assert.Equal(SyntaxKind.AddExpression, nodes[6].Kind()); } [Fact] public void TestAncestorsAndSelf() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var nodes = e.AncestorsAndSelf().ToList(); Assert.Equal(8, nodes.Count); Assert.Equal(SyntaxKind.IdentifierName, nodes[0].Kind()); Assert.Equal(SyntaxKind.DivideExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.MultiplyExpression, nodes[3].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[4].Kind()); Assert.Equal(SyntaxKind.SubtractExpression, nodes[5].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[6].Kind()); Assert.Equal(SyntaxKind.AddExpression, nodes[7].Kind()); } [Fact] public void TestFirstAncestorOrSelf() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var firstParens = e.FirstAncestorOrSelf<ExpressionSyntax>(n => n.Kind() == SyntaxKind.ParenthesizedExpression); Assert.NotNull(firstParens); Assert.Equal("(d / e)", firstParens.ToString()); } [Fact] public void TestDescendantNodes() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodes = statement.DescendantNodes().ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); nodes = statement.DescendantNodes(n => n is StatementSyntax).ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); // all over again with spans nodes = statement.DescendantNodes(statement.FullSpan).ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(statement.FullSpan, descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); nodes = statement.DescendantNodes(statement.FullSpan, n => n is StatementSyntax).ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(statement.FullSpan, n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); } [Fact] public void TestDescendantNodesAndSelf() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodes = statement.DescendantNodesAndSelf().ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(descendIntoTrivia: true).ToList(); Assert.Equal(4, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[3].Kind()); nodes = statement.DescendantNodesAndSelf(n => n is StatementSyntax).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); // all over again with spans nodes = statement.DescendantNodesAndSelf(statement.FullSpan).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(statement.FullSpan, descendIntoTrivia: true).ToList(); Assert.Equal(4, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[3].Kind()); nodes = statement.DescendantNodesAndSelf(statement.FullSpan, n => n is StatementSyntax).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(statement.FullSpan, n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); } [Fact] public void TestDescendantNodesAndTokens() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodesAndTokens = statement.DescendantNodesAndTokens().ToList(); Assert.Equal(4, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[3].Kind()); nodesAndTokens = statement.DescendantNodesAndTokens(descendIntoTrivia: true).ToList(); Assert.Equal(10, nodesAndTokens.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.HashToken, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.IfKeyword, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[4].Kind()); Assert.Equal(SyntaxKind.EndOfDirectiveToken, nodesAndTokens[5].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[6].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[7].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[8].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[9].Kind()); // with span nodesAndTokens = statement.DescendantNodesAndTokens(statement.FullSpan).ToList(); Assert.Equal(4, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[3].Kind()); } [Fact] public void TestDescendantNodesAndTokensAndSelf() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodesAndTokens = statement.DescendantNodesAndTokensAndSelf().ToList(); Assert.Equal(5, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[4].Kind()); nodesAndTokens = statement.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToList(); Assert.Equal(11, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.HashToken, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.IfKeyword, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[4].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[5].Kind()); Assert.Equal(SyntaxKind.EndOfDirectiveToken, nodesAndTokens[6].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[7].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[8].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[9].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[10].Kind()); // with span nodesAndTokens = statement.DescendantNodesAndTokensAndSelf(statement.FullSpan).ToList(); Assert.Equal(5, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[4].Kind()); } [Fact] public void TestDescendantNodesAndTokensAndSelfForEmptyCompilationUnit() { var text = ""; var cu = SyntaxFactory.ParseCompilationUnit(text); var nodesAndTokens = cu.DescendantNodesAndTokensAndSelf().ToList(); Assert.Equal(2, nodesAndTokens.Count); Assert.Equal(SyntaxKind.CompilationUnit, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, nodesAndTokens[1].Kind()); } [Fact] public void TestDescendantNodesAndTokensAndSelfForDocumentationComment() { var text = "/// Goo\r\n x"; var expr = SyntaxFactory.ParseExpression(text); var nodesAndTokens = expr.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToList(); Assert.Equal(7, nodesAndTokens.Count); Assert.Equal(SyntaxKind.IdentifierName, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.SingleLineDocumentationCommentTrivia, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.XmlText, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.XmlTextLiteralToken, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.XmlTextLiteralNewLineToken, nodesAndTokens[4].Kind()); Assert.Equal(SyntaxKind.EndOfDocumentationCommentToken, nodesAndTokens[5].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, nodesAndTokens[6].Kind()); } [Fact] public void TestGetAllDirectivesUsingDescendantNodes() { var text = "#if false\r\n eat a sandwich\r\n#endif\r\n x"; var expr = SyntaxFactory.ParseExpression(text); var directives = expr.GetDirectives(); var descendantDirectives = expr.DescendantNodesAndSelf(n => n.ContainsDirectives, descendIntoTrivia: true).OfType<DirectiveTriviaSyntax>().ToList(); Assert.Equal(directives.Count, descendantDirectives.Count); for (int i = 0; i < directives.Count; i++) { Assert.Equal(directives[i], descendantDirectives[i]); } } [Fact] public void TestGetAllAnnotatedNodesUsingDescendantNodes() { var text = "a + (b - (c * (d / e)))"; var expr = SyntaxFactory.ParseExpression(text); var myAnnotation = new SyntaxAnnotation(); var identifierNodes = expr.DescendantNodes().OfType<IdentifierNameSyntax>().ToList(); var exprWithAnnotations = expr.ReplaceNodes(identifierNodes, (e, e2) => e2.WithAdditionalAnnotations(myAnnotation)); var nodesWithMyAnnotations = exprWithAnnotations.DescendantNodesAndSelf(n => n.ContainsAnnotations).Where(n => n.HasAnnotation(myAnnotation)).ToList(); Assert.Equal(identifierNodes.Count, nodesWithMyAnnotations.Count); for (int i = 0; i < identifierNodes.Count; i++) { // compare text because node identity changed when adding the annotation Assert.Equal(identifierNodes[i].ToString(), nodesWithMyAnnotations[i].ToString()); } } [Fact] public void TestDescendantTokens() { var s1 = "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.UsingKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, tokens[3].Kind()); } [Fact] public void TestDescendantTokensWithExtraWhitespace() { var s1 = " using Goo ; "; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.UsingKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, tokens[3].Kind()); } [Fact] public void TestDescendantTokensEntireRange() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(8, tokens.Count); Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[3].Kind()); Assert.Equal(SyntaxKind.UsingKeyword, tokens[4].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[5].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[6].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, tokens[7].Kind()); } [Fact] public void TestDescendantTokensOverFullSpan() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(0, 16)).ToList(); Assert.Equal(3, tokens.Count); Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind()); } [Fact] public void TestDescendantTokensOverInsideSpan() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(1, 14)).ToList(); Assert.Equal(3, tokens.Count); Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind()); } [Fact] public void TestDescendantTokensOverFullSpanOffset() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(7, 17)).ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.AliasKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.UsingKeyword, tokens[3].Kind()); } [Fact] public void TestDescendantTokensOverInsideSpanOffset() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(8, 15)).ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.AliasKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.UsingKeyword, tokens[3].Kind()); } [Fact] public void TestDescendantTrivia() { var text = "// goo\r\na + b"; var expr = SyntaxFactory.ParseExpression(text); var list = expr.DescendantTrivia().ToList(); Assert.Equal(4, list.Count); Assert.Equal(SyntaxKind.SingleLineCommentTrivia, list[0].Kind()); Assert.Equal(SyntaxKind.EndOfLineTrivia, list[1].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[2].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[3].Kind()); } [Fact] public void TestDescendantTriviaIntoStructuredTrivia() { var text = @" /// <goo > /// </goo> a + b"; var expr = SyntaxFactory.ParseExpression(text); var list = expr.DescendantTrivia(descendIntoTrivia: true).ToList(); Assert.Equal(7, list.Count); Assert.Equal(SyntaxKind.EndOfLineTrivia, list[0].Kind()); Assert.Equal(SyntaxKind.SingleLineDocumentationCommentTrivia, list[1].Kind()); Assert.Equal(SyntaxKind.DocumentationCommentExteriorTrivia, list[2].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[3].Kind()); Assert.Equal(SyntaxKind.DocumentationCommentExteriorTrivia, list[4].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[5].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[6].Kind()); } [Fact] public void Bug877223() { var s1 = "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); // var node = t1.GetCompilationUnitRoot().Usings[0].GetTokens(new TextSpan(6, 3)).First(); var node = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(6, 3)).First(); Assert.Equal("Goo", node.ToString()); } [Fact] public void TestFindToken() { var text = "class\n #if XX\n#endif\n goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var token = tree.GetCompilationUnitRoot().FindToken("class\n #i".Length); Assert.Equal(SyntaxKind.IdentifierToken, token.Kind()); Assert.Equal("goo", token.ToString()); token = tree.GetCompilationUnitRoot().FindToken("class\n #i".Length, findInsideTrivia: true); Assert.Equal(SyntaxKind.IfKeyword, token.Kind()); } [Fact] public void TestFindTokenInLargeList() { var identifier = SyntaxFactory.Identifier("x"); var missingIdentifier = SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken); var name = SyntaxFactory.IdentifierName(identifier); var missingName = SyntaxFactory.IdentifierName(missingIdentifier); var comma = SyntaxFactory.Token(SyntaxKind.CommaToken); var missingComma = SyntaxFactory.MissingToken(SyntaxKind.CommaToken); var argument = SyntaxFactory.Argument(name); var missingArgument = SyntaxFactory.Argument(missingName); // make a large list that has lots of zero-length nodes (that shouldn't be found) var nodesAndTokens = SyntaxFactory.NodeOrTokenList( missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, argument); var argumentList = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList<ArgumentSyntax>(SyntaxFactory.NodeOrTokenList(nodesAndTokens))); var invocation = SyntaxFactory.InvocationExpression(name, argumentList); CheckFindToken(invocation); } private void CheckFindToken(SyntaxNode node) { for (int i = 0; i < node.FullSpan.End; i++) { var token = node.FindToken(i); Assert.True(token.FullSpan.Contains(i)); } } [WorkItem(755236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755236")] [Fact] public void TestFindNode() { var text = "class\n #if XX\n#endif\n goo { }\n class bar { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var root = tree.GetRoot(); Assert.Equal(root, root.FindNode(root.Span, findInsideTrivia: false)); Assert.Equal(root, root.FindNode(root.Span, findInsideTrivia: true)); var classDecl = (TypeDeclarationSyntax)root.ChildNodes().First(); // IdentifierNameSyntax in trivia. var identifier = root.DescendantNodes(descendIntoTrivia: true).Single(n => n is IdentifierNameSyntax); var position = identifier.Span.Start + 1; Assert.Equal(classDecl, root.FindNode(identifier.Span, findInsideTrivia: false)); Assert.Equal(identifier, root.FindNode(identifier.Span, findInsideTrivia: true)); // Token span. Assert.Equal(classDecl, root.FindNode(classDecl.Identifier.Span, findInsideTrivia: false)); // EOF Token span. var EOFSpan = new TextSpan(root.FullSpan.End, 0); Assert.Equal(root, root.FindNode(EOFSpan, findInsideTrivia: false)); Assert.Equal(root, root.FindNode(EOFSpan, findInsideTrivia: true)); // EOF Invalid span for childnode var classDecl2 = (TypeDeclarationSyntax)root.ChildNodes().Last(); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(EOFSpan)); // Check end position included in node span var nodeEndPositionSpan = new TextSpan(classDecl.FullSpan.End, 0); Assert.Equal(classDecl2, root.FindNode(nodeEndPositionSpan, findInsideTrivia: false)); Assert.Equal(classDecl2, root.FindNode(nodeEndPositionSpan, findInsideTrivia: true)); Assert.Equal(classDecl2, classDecl2.FindNode(nodeEndPositionSpan, findInsideTrivia: false)); Assert.Equal(classDecl2, classDecl2.FindNode(nodeEndPositionSpan, findInsideTrivia: true)); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl.FindNode(nodeEndPositionSpan)); // Invalid spans. var invalidSpan = new TextSpan(100, 100); Assert.Throws<ArgumentOutOfRangeException>(() => root.FindNode(invalidSpan)); invalidSpan = new TextSpan(root.FullSpan.End - 1, 2); Assert.Throws<ArgumentOutOfRangeException>(() => root.FindNode(invalidSpan)); invalidSpan = new TextSpan(classDecl2.FullSpan.Start - 1, root.FullSpan.End); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(invalidSpan)); invalidSpan = new TextSpan(classDecl.FullSpan.End, root.FullSpan.End); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(invalidSpan)); // Parent node's span. Assert.Throws<ArgumentOutOfRangeException>(() => classDecl.FindNode(root.FullSpan)); } [WorkItem(539941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539941")] [Fact] public void TestFindTriviaNoTriviaExistsAtPosition() { var code = @"class Goo { void Bar() { } }"; var tree = SyntaxFactory.ParseSyntaxTree(code); var position = tree.GetText().Lines[2].End - 1; // position points to the closing parenthesis on the line that has "void Bar()" // There should be no trivia at this position var trivia = tree.GetCompilationUnitRoot().FindTrivia(position); Assert.Equal(SyntaxKind.None, trivia.Kind()); Assert.Equal(0, trivia.SpanStart); Assert.Equal(0, trivia.Span.End); Assert.Equal(default(SyntaxTrivia), trivia); } [Fact] public void TestTreeEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree.GetCompilationUnitRoot().IsEquivalentTo(tree.GetCompilationUnitRoot())); } [Fact] public void TestTreeNotEquivalentToNull() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.False(tree.GetCompilationUnitRoot().IsEquivalentTo(null)); } [Fact] public void TestTreesFromSameSourceEquivalent() { var text = "class goo { }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = SyntaxFactory.ParseSyntaxTree(text); Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot()); Assert.True(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestDifferentTreesNotEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { }"); var tree2 = SyntaxFactory.ParseSyntaxTree("class bar { }"); Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot()); Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestVastlyDifferentTreesNotEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { }"); var tree2 = SyntaxFactory.ParseSyntaxTree(string.Empty); Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot()); Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestSimilarSubtreesEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { void M() { } }"); var tree2 = SyntaxFactory.ParseSyntaxTree("class bar { void M() { } }"); var m1 = ((TypeDeclarationSyntax)tree1.GetCompilationUnitRoot().Members[0]).Members[0]; var m2 = ((TypeDeclarationSyntax)tree2.GetCompilationUnitRoot().Members[0]).Members[0]; Assert.Equal(SyntaxKind.MethodDeclaration, m1.Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, m2.Kind()); Assert.NotEqual(m1, m2); Assert.True(m1.IsEquivalentTo(m2)); } [Fact] public void TestTreesWithDifferentTriviaAreNotEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo {void M() { }}"); var tree2 = SyntaxFactory.ParseSyntaxTree("class goo { void M() { } }"); Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestNodeIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree.GetCompilationUnitRoot().IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot())); } [Fact] public void TestTokenIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree.GetCompilationUnitRoot().EndOfFileToken.IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot().EndOfFileToken)); } [Fact] public void TestDifferentTokensFromSameTreeNotIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.False(tree.GetCompilationUnitRoot().GetFirstToken().IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot().GetFirstToken().GetNextToken())); } [Fact] public void TestCachedTokensFromDifferentTreesIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree1.GetCompilationUnitRoot().GetFirstToken().IsIncrementallyIdenticalTo(tree2.GetCompilationUnitRoot().GetFirstToken())); } [Fact] public void TestNodesFromSameContentNotIncrementallyParsedNotIncrementallyEquivalent() { var text = "class goo { }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = SyntaxFactory.ParseSyntaxTree(text); Assert.False(tree1.GetCompilationUnitRoot().IsIncrementallyIdenticalTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestNodesFromIncrementalParseIncrementallyEquivalent1() { var text = "class goo { void M() { } }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = tree1.WithChangedText(tree1.GetText().WithChanges(new TextChange(default, " "))); Assert.True( tree1.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().IsIncrementallyIdenticalTo( tree2.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); } [Fact] public void TestNodesFromIncrementalParseNotIncrementallyEquivalent1() { var text = "class goo { void M() { } }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = tree1.WithChangedText(tree1.GetText().WithChanges(new TextChange(new TextSpan(22, 0), " return; "))); Assert.False( tree1.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().IsIncrementallyIdenticalTo( tree2.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); } [Fact, WorkItem(536664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536664")] public void TestTriviaNodeCached() { var tree = SyntaxFactory.ParseSyntaxTree(" class goo {}"); // get to the trivia node var trivia = tree.GetCompilationUnitRoot().Members[0].GetLeadingTrivia()[0]; // we get the trivia again var triviaAgain = tree.GetCompilationUnitRoot().Members[0].GetLeadingTrivia()[0]; // should NOT return two distinct objects for trivia and triviaAgain - struct now. Assert.True(SyntaxTrivia.Equals(trivia, triviaAgain)); } [Fact] public void TestGetFirstToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var first = tree.GetCompilationUnitRoot().GetFirstToken(); Assert.Equal(SyntaxKind.PublicKeyword, first.Kind()); } [Fact] public void TestGetFirstTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var first = tree.GetCompilationUnitRoot().GetFirstToken(includeZeroWidth: true); Assert.Equal(SyntaxKind.PublicKeyword, first.Kind()); } [Fact] public void TestGetLastToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var last = tree.GetCompilationUnitRoot().GetLastToken(); Assert.Equal(SyntaxKind.CloseBraceToken, last.Kind()); } [Fact] public void TestGetLastTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { "); var last = tree.GetCompilationUnitRoot().GetLastToken(includeZeroWidth: true); Assert.Equal(SyntaxKind.EndOfFileToken, last.Kind()); last = tree.GetCompilationUnitRoot().Members[0].GetLastToken(includeZeroWidth: true); Assert.Equal(SyntaxKind.CloseBraceToken, last.Kind()); Assert.True(last.IsMissing); Assert.Equal(26, last.FullSpan.Start); } [Fact] public void TestReverseChildSyntaxList() { var tree1 = SyntaxFactory.ParseSyntaxTree("class A {} public class B {} public static class C {}"); var root1 = tree1.GetCompilationUnitRoot(); TestReverse(root1.ChildNodesAndTokens()); TestReverse(root1.Members[0].ChildNodesAndTokens()); TestReverse(root1.Members[1].ChildNodesAndTokens()); TestReverse(root1.Members[2].ChildNodesAndTokens()); } private void TestReverse(ChildSyntaxList children) { var list1 = children.AsEnumerable().Reverse().ToList(); var list2 = children.Reverse().ToList(); Assert.Equal(list1.Count, list2.Count); for (int i = 0; i < list1.Count; i++) { Assert.Equal(list1[i], list2[i]); Assert.Equal(list1[i].FullSpan.Start, list2[i].FullSpan.Start); } } [Fact] public void TestGetNextToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeSkipped: true); } // descendant tokens include EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenIncludingSkippedTokens() { var text = @"garbage using goo.bar; "; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); var tokens = tree.GetCompilationUnitRoot().DescendantTokens(descendIntoTrivia: true).Where(SyntaxToken.NonZeroWidth).ToList(); Assert.Equal(6, tokens.Count); Assert.Equal("garbage", tokens[0].Text); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeSkipped: true); } Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenExcludingSkippedTokens() { var tree = SyntaxFactory.ParseSyntaxTree( @"garbage using goo.bar; "); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(6, tokens.Count); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: false); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeSkipped: false); } // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); SyntaxToken token = syntaxTree.GetRoot().GetFirstToken(); while (token.RawKind != 0) { list.Add(token); token = token.GetNextToken(); } // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().GetLastToken(); // skip EOF while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(); } list.Reverse(); // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenIncludingSkippedTokens() { var text = @"garbage using goo.bar; "; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); var tokens = tree.GetCompilationUnitRoot().DescendantTokens(descendIntoTrivia: true).Where(SyntaxToken.NonZeroWidth).ToList(); Assert.Equal(6, tokens.Count); Assert.Equal("garbage", tokens[0].Text); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetLastToken(includeSkipped: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(includeSkipped: true); } list.Reverse(); Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenExcludingSkippedTokens() { var text = @"garbage using goo.bar; "; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(6, tokens.Count); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetLastToken(includeSkipped: false); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(includeSkipped: false); } list.Reverse(); // descendant tokens includes EOF Assert.Equal(tokens.Count, list.Count + 1); for (int i = 0; i < list.Count; i++) { Assert.Equal(tokens[i], list[i]); } } [Fact] public void TestGetPreviousTokenCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); var token = syntaxTree.GetRoot().GetLastToken(includeZeroWidth: false); // skip EOF while (token.RawKind != 0) { list.Add(token); token = token.GetPreviousToken(); } list.Reverse(); // descendant tokens include EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeZeroWidth: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeZeroWidth: true); } Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenIncludingZeroWidthCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); SyntaxToken token = syntaxTree.GetRoot().GetFirstToken(includeZeroWidth: true); while (token.RawKind != 0) { list.Add(token); token = token.GetNextToken(includeZeroWidth: true); } Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().EndOfFileToken.GetPreviousToken(includeZeroWidth: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(includeZeroWidth: true); } list.Reverse(); // descendant tokens include EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenIncludingZeroWidthCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); SyntaxToken token = ((SyntaxToken)((SyntaxTree)syntaxTree).GetCompilationUnitRoot().EndOfFileToken).GetPreviousToken(includeZeroWidth: true); while (token.RawKind != 0) { list.Add(token); token = token.GetPreviousToken(includeZeroWidth: true); } list.Reverse(); // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(tokens[i], list[i]); } } [Fact] public void TestGetNextSibling() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var children = tree.GetCompilationUnitRoot().Members[0].ChildNodesAndTokens().ToList(); var list = new List<SyntaxNodeOrToken>(); for (var child = children[0]; child.Kind() != SyntaxKind.None; child = child.GetNextSibling()) { list.Add(child); } Assert.Equal(children.Count, list.Count); for (int i = 0; i < children.Count; i++) { Assert.Equal(list[i], children[i]); } } [Fact] public void TestGetPreviousSibling() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var children = tree.GetCompilationUnitRoot().Members[0].ChildNodesAndTokens().ToList(); var reversed = children.AsEnumerable().Reverse().ToList(); var list = new List<SyntaxNodeOrToken>(); for (var child = children[children.Count - 1]; child.Kind() != SyntaxKind.None; child = child.GetPreviousSibling()) { list.Add(child); } Assert.Equal(children.Count, list.Count); for (int i = 0; i < reversed.Count; i++) { Assert.Equal(list[i], reversed[i]); } } [Fact] public void TestSyntaxNodeOrTokenEquality() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var child = tree.GetCompilationUnitRoot().ChildNodesAndTokens()[0]; var member = (TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]; Assert.Equal((SyntaxNodeOrToken)member, child); var name = member.Identifier; var nameChild = member.ChildNodesAndTokens()[3]; Assert.Equal((SyntaxNodeOrToken)name, nameChild); var closeBraceToken = member.CloseBraceToken; var closeBraceChild = member.GetLastToken(); Assert.Equal((SyntaxNodeOrToken)closeBraceToken, closeBraceChild); } [Fact] public void TestStructuredTriviaHasNoParent() { var tree = SyntaxFactory.ParseSyntaxTree("#define GOO"); var trivia = tree.GetCompilationUnitRoot().EndOfFileToken.GetLeadingTrivia()[0]; Assert.Equal(SyntaxKind.DefineDirectiveTrivia, trivia.Kind()); Assert.True(trivia.HasStructure); Assert.NotNull(trivia.GetStructure()); Assert.Null(trivia.GetStructure().Parent); } [Fact] public void TestStructuredTriviaHasParentTrivia() { var tree = SyntaxFactory.ParseSyntaxTree("#define GOO"); var trivia = tree.GetCompilationUnitRoot().EndOfFileToken.GetLeadingTrivia()[0]; Assert.Equal(SyntaxKind.DefineDirectiveTrivia, trivia.Kind()); Assert.True(trivia.HasStructure); Assert.NotNull(trivia.GetStructure()); var parentTrivia = trivia.GetStructure().ParentTrivia; Assert.NotEqual(SyntaxKind.None, parentTrivia.Kind()); Assert.Equal(trivia, parentTrivia); } [Fact] public void TestStructuredTriviaParentTrivia() { var def = SyntaxFactory.DefineDirectiveTrivia(SyntaxFactory.Identifier("GOO"), false); // unrooted structured trivia should report parent trivia as default Assert.Equal(default(SyntaxTrivia), def.ParentTrivia); var trivia = SyntaxFactory.Trivia(def); var structure = trivia.GetStructure(); Assert.NotEqual(def, structure); // these should not be identity equals Assert.True(def.IsEquivalentTo(structure)); // they should be equivalent though Assert.Equal(trivia, structure.ParentTrivia); // parent trivia should be equal to original trivia // attach trivia to token and walk down to structured trivia and back up again var token = SyntaxFactory.Identifier(default(SyntaxTriviaList), "x", SyntaxTriviaList.Create(trivia)); var tokenTrivia = token.TrailingTrivia[0]; var tokenStructuredTrivia = tokenTrivia.GetStructure(); var tokenStructuredParentTrivia = tokenStructuredTrivia.ParentTrivia; Assert.Equal(tokenTrivia, tokenStructuredParentTrivia); Assert.Equal(token, tokenStructuredParentTrivia.Token); } [Fact] public void TestGetFirstDirective() { var tree = SyntaxFactory.ParseSyntaxTree("#define GOO"); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); } [Fact] public void TestGetLastDirective() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #undef GOO "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.UndefDirectiveTrivia, d.Kind()); } [Fact] public void TestGetNextDirective() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #define BAR class C { #if GOO void M() { } #endif } "); var d1 = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d1); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d1.Kind()); var d2 = d1.GetNextDirective(); Assert.NotNull(d2); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d2.Kind()); var d3 = d2.GetNextDirective(); Assert.NotNull(d3); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d3.Kind()); var d4 = d3.GetNextDirective(); Assert.NotNull(d4); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d4.Kind()); var d5 = d4.GetNextDirective(); Assert.Null(d5); } [Fact] public void TestGetPreviousDirective() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #define BAR class C { #if GOO void M() { } #endif } "); var d1 = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d1); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d1.Kind()); var d2 = d1.GetPreviousDirective(); Assert.NotNull(d2); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d2.Kind()); var d3 = d2.GetPreviousDirective(); Assert.NotNull(d3); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d3.Kind()); var d4 = d3.GetPreviousDirective(); Assert.NotNull(d4); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d4.Kind()); var d5 = d4.GetPreviousDirective(); Assert.Null(d5); } [Fact] public void TestGetDirectivesRelatedToIf() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToIfElements() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); // get directives related to elif var related2 = related[1].GetRelatedDirectives(); Assert.True(related.SequenceEqual(related2)); // get directives related to else var related3 = related[3].GetRelatedDirectives(); Assert.True(related.SequenceEqual(related3)); } [Fact] public void TestGetDirectivesRelatedToEndIf() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToIfWithNestedIfEndIF() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #if ZED class A1 { } #endif #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToIfWithNestedRegionEndRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #region some region class A1 { } #endregion #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToEndIfWithNestedIfEndIf() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #if ZED class A1 { } #endif #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToEndIfWithNestedRegionEndRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO #region some region class A { } #endregion #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @"#region Some Region class A { } #endregion #if GOO #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(2, related.Count); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, related[1].Kind()); } [Fact] public void TestGetDirectivesRelatedToEndRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @" #if GOO #endif #region Some Region class A { } #endregion "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(2, related.Count); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, related[1].Kind()); } [WorkItem(536995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536995")] [Fact] public void TestTextAndSpanWithTrivia1() { var tree = SyntaxFactory.ParseSyntaxTree( @"/*START*/namespace Microsoft.CSharp.Test { }/*END*/"); var rootNode = tree.GetCompilationUnitRoot(); Assert.Equal(rootNode.FullSpan.Length, rootNode.ToFullString().Length); Assert.Equal(rootNode.Span.Length, rootNode.ToString().Length); Assert.True(rootNode.ToString().Contains("/*END*/")); Assert.False(rootNode.ToString().Contains("/*START*/")); } [WorkItem(536996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536996")] [Fact] public void TestTextAndSpanWithTrivia2() { var tree = SyntaxFactory.ParseSyntaxTree( @"/*START*/ namespace Microsoft.CSharp.Test { } /*END*/"); var rootNode = tree.GetCompilationUnitRoot(); Assert.Equal(rootNode.FullSpan.Length, rootNode.ToFullString().Length); Assert.Equal(rootNode.Span.Length, rootNode.ToString().Length); Assert.True(rootNode.ToString().Contains("/*END*/")); Assert.False(rootNode.ToString().Contains("/*START*/")); } [Fact] public void TestCreateCommonSyntaxNode() { var rootNode = SyntaxFactory.ParseSyntaxTree("using X; namespace Y { }").GetCompilationUnitRoot(); var namespaceNode = rootNode.ChildNodesAndTokens()[1].AsNode(); var nodeOrToken = (SyntaxNodeOrToken)namespaceNode; Assert.True(nodeOrToken.IsNode); Assert.Equal(namespaceNode, nodeOrToken.AsNode()); Assert.Equal(rootNode, nodeOrToken.Parent); Assert.Equal(namespaceNode.FullSpan, nodeOrToken.FullSpan); Assert.Equal(namespaceNode.Span, nodeOrToken.Span); } [Fact, WorkItem(537070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537070")] public void TestTraversalUsingCommonSyntaxNodeOrToken() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(@"class c1 { }"); var nodeOrToken = (SyntaxNodeOrToken)syntaxTree.GetRoot(); Assert.Equal(0, syntaxTree.GetDiagnostics().Count()); Action<SyntaxNodeOrToken> walk = null; walk = (SyntaxNodeOrToken nOrT) => { Assert.Equal(0, syntaxTree.GetDiagnostics(nOrT).Count()); foreach (var child in nOrT.ChildNodesAndTokens()) { walk(child); } }; walk(nodeOrToken); } [WorkItem(537747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537747")] [Fact] public void SyntaxTriviaDefaultIsDirective() { SyntaxTrivia trivia = new SyntaxTrivia(); Assert.False(trivia.IsDirective); } [Fact] public void SyntaxNames() { var cc = SyntaxFactory.Token(SyntaxKind.ColonColonToken); var lt = SyntaxFactory.Token(SyntaxKind.LessThanToken); var gt = SyntaxFactory.Token(SyntaxKind.GreaterThanToken); var dot = SyntaxFactory.Token(SyntaxKind.DotToken); var gp = SyntaxFactory.SingletonSeparatedList<TypeSyntax>(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword))); var externAlias = SyntaxFactory.IdentifierName("alias"); var goo = SyntaxFactory.IdentifierName("Goo"); var bar = SyntaxFactory.IdentifierName("Bar"); // Goo.Bar var qualified = SyntaxFactory.QualifiedName(goo, dot, bar); Assert.Equal("Goo.Bar", qualified.ToString()); Assert.Equal("Bar", qualified.GetUnqualifiedName().Identifier.ValueText); // Bar<int> var generic = SyntaxFactory.GenericName(bar.Identifier, SyntaxFactory.TypeArgumentList(lt, gp, gt)); Assert.Equal("Bar<int>", generic.ToString()); Assert.Equal("Bar", generic.GetUnqualifiedName().Identifier.ValueText); // Goo.Bar<int> var qualifiedGeneric = SyntaxFactory.QualifiedName(goo, dot, generic); Assert.Equal("Goo.Bar<int>", qualifiedGeneric.ToString()); Assert.Equal("Bar", qualifiedGeneric.GetUnqualifiedName().Identifier.ValueText); // alias::Goo var alias = SyntaxFactory.AliasQualifiedName(externAlias, cc, goo); Assert.Equal("alias::Goo", alias.ToString()); Assert.Equal("Goo", alias.GetUnqualifiedName().Identifier.ValueText); // alias::Bar<int> var aliasGeneric = SyntaxFactory.AliasQualifiedName(externAlias, cc, generic); Assert.Equal("alias::Bar<int>", aliasGeneric.ToString()); Assert.Equal("Bar", aliasGeneric.GetUnqualifiedName().Identifier.ValueText); // alias::Goo.Bar var aliasQualified = SyntaxFactory.QualifiedName(alias, dot, bar); Assert.Equal("alias::Goo.Bar", aliasQualified.ToString()); Assert.Equal("Bar", aliasQualified.GetUnqualifiedName().Identifier.ValueText); // alias::Goo.Bar<int> var aliasQualifiedGeneric = SyntaxFactory.QualifiedName(alias, dot, generic); Assert.Equal("alias::Goo.Bar<int>", aliasQualifiedGeneric.ToString()); Assert.Equal("Bar", aliasQualifiedGeneric.GetUnqualifiedName().Identifier.ValueText); } [Fact] public void ZeroWidthTokensInListAreUnique() { var someToken = SyntaxFactory.MissingToken(SyntaxKind.IntKeyword); var list = SyntaxFactory.TokenList(someToken, someToken); Assert.Equal(someToken, someToken); Assert.NotEqual(list[0], list[1]); } [Fact] public void ZeroWidthTokensInParentAreUnique() { var missingComma = SyntaxFactory.MissingToken(SyntaxKind.CommaToken); var omittedArraySize = SyntaxFactory.OmittedArraySizeExpression(SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken)); var spec = SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.Token(SyntaxKind.OpenBracketToken), SyntaxFactory.SeparatedList<ExpressionSyntax>(new SyntaxNodeOrToken[] { omittedArraySize, missingComma, omittedArraySize, missingComma, omittedArraySize, missingComma, omittedArraySize }), SyntaxFactory.Token(SyntaxKind.CloseBracketToken) ); var sizes = spec.Sizes; Assert.Equal(4, sizes.Count); Assert.Equal(3, sizes.SeparatorCount); Assert.NotEqual(sizes[0], sizes[1]); Assert.NotEqual(sizes[0], sizes[2]); Assert.NotEqual(sizes[0], sizes[3]); Assert.NotEqual(sizes[1], sizes[2]); Assert.NotEqual(sizes[1], sizes[3]); Assert.NotEqual(sizes[2], sizes[3]); Assert.NotEqual(sizes.GetSeparator(0), sizes.GetSeparator(1)); Assert.NotEqual(sizes.GetSeparator(0), sizes.GetSeparator(2)); Assert.NotEqual(sizes.GetSeparator(1), sizes.GetSeparator(2)); } [Fact] public void ZeroWidthStructuredTrivia() { // create zero width structured trivia (not sure how these come about but its not impossible) var zeroWidth = SyntaxFactory.ElseDirectiveTrivia(SyntaxFactory.MissingToken(SyntaxKind.HashToken), SyntaxFactory.MissingToken(SyntaxKind.ElseKeyword), SyntaxFactory.MissingToken(SyntaxKind.EndOfDirectiveToken), false, false); Assert.Equal(0, zeroWidth.Width); // create token with more than one instance of same zero width structured trivia! var someToken = SyntaxFactory.Identifier(default(SyntaxTriviaList), "goo", SyntaxFactory.TriviaList(SyntaxFactory.Trivia(zeroWidth), SyntaxFactory.Trivia(zeroWidth))); // create node with this token var someNode = SyntaxFactory.IdentifierName(someToken); Assert.Equal(2, someNode.Identifier.TrailingTrivia.Count); Assert.True(someNode.Identifier.TrailingTrivia[0].HasStructure); Assert.True(someNode.Identifier.TrailingTrivia[1].HasStructure); // prove that trivia have different identity Assert.False(someNode.Identifier.TrailingTrivia[0].Equals(someNode.Identifier.TrailingTrivia[1])); var tt0 = someNode.Identifier.TrailingTrivia[0]; var tt1 = someNode.Identifier.TrailingTrivia[1]; var str0 = tt0.GetStructure(); var str1 = tt1.GetStructure(); // prove that structures have different identity Assert.NotEqual(str0, str1); // prove that structured trivia can get back to original trivia with correct identity var tr0 = str0.ParentTrivia; Assert.Equal(tt0, tr0); var tr1 = str1.ParentTrivia; Assert.Equal(tt1, tr1); } [Fact] public void ZeroWidthStructuredTriviaOnZeroWidthToken() { // create zero width structured trivia (not sure how these come about but its not impossible) var zeroWidth = SyntaxFactory.ElseDirectiveTrivia(SyntaxFactory.MissingToken(SyntaxKind.HashToken), SyntaxFactory.MissingToken(SyntaxKind.ElseKeyword), SyntaxFactory.MissingToken(SyntaxKind.EndOfDirectiveToken), false, false); Assert.Equal(0, zeroWidth.Width); // create token with more than one instance of same zero width structured trivia! var someToken = SyntaxFactory.Identifier(default(SyntaxTriviaList), "", SyntaxFactory.TriviaList(SyntaxFactory.Trivia(zeroWidth), SyntaxFactory.Trivia(zeroWidth))); // create node with this token var someNode = SyntaxFactory.IdentifierName(someToken); Assert.Equal(2, someNode.Identifier.TrailingTrivia.Count); Assert.True(someNode.Identifier.TrailingTrivia[0].HasStructure); Assert.True(someNode.Identifier.TrailingTrivia[1].HasStructure); // prove that trivia have different identity Assert.False(someNode.Identifier.TrailingTrivia[0].Equals(someNode.Identifier.TrailingTrivia[1])); var tt0 = someNode.Identifier.TrailingTrivia[0]; var tt1 = someNode.Identifier.TrailingTrivia[1]; var str0 = tt0.GetStructure(); var str1 = tt1.GetStructure(); // prove that structures have different identity Assert.NotEqual(str0, str1); // prove that structured trivia can get back to original trivia with correct identity var tr0 = str0.ParentTrivia; Assert.Equal(tt0, tr0); var tr1 = str1.ParentTrivia; Assert.Equal(tt1, tr1); } [WorkItem(537059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537059")] [Fact] public void TestIncompleteDeclWithDotToken() { var tree = SyntaxFactory.ParseSyntaxTree( @" class Test { int IX.GOO "); // Verify the kind of the CSharpSyntaxNode "int IX.GOO" is MethodDeclaration and NOT FieldDeclaration Assert.Equal(SyntaxKind.MethodDeclaration, tree.GetCompilationUnitRoot().ChildNodesAndTokens()[0].ChildNodesAndTokens()[3].Kind()); } [WorkItem(538360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538360")] [Fact] public void TestGetTokensLanguageAny() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("class C {}"); var actualTokens = syntaxTree.GetCompilationUnitRoot().DescendantTokens(); var expectedTokenKinds = new SyntaxKind[] { SyntaxKind.ClassKeyword, SyntaxKind.IdentifierToken, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, SyntaxKind.EndOfFileToken, }; Assert.Equal(expectedTokenKinds.Count(), actualTokens.Count()); //redundant but helps debug Assert.True(expectedTokenKinds.SequenceEqual(actualTokens.Select(t => t.Kind()))); } [WorkItem(538360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538360")] [Fact] public void TestGetTokensCommonAny() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("class C {}"); var actualTokens = syntaxTree.GetRoot().DescendantTokens(syntaxTree.GetRoot().FullSpan); var expectedTokenKinds = new SyntaxKind[] { SyntaxKind.ClassKeyword, SyntaxKind.IdentifierToken, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, SyntaxKind.EndOfFileToken, }; Assert.Equal(expectedTokenKinds.Count(), actualTokens.Count()); //redundant but helps debug Assert.True(expectedTokenKinds.SequenceEqual(actualTokens.Select(t => (SyntaxKind)t.RawKind))); } [Fact] public void TestGetLocation() { var tree = SyntaxFactory.ParseSyntaxTree("class C { void F() { } }"); dynamic root = tree.GetCompilationUnitRoot(); MethodDeclarationSyntax method = root.Members[0].Members[0]; var nodeLocation = method.GetLocation(); Assert.True(nodeLocation.IsInSource); Assert.Equal(tree, nodeLocation.SourceTree); Assert.Equal(method.Span, nodeLocation.SourceSpan); var tokenLocation = method.Identifier.GetLocation(); Assert.True(tokenLocation.IsInSource); Assert.Equal(tree, tokenLocation.SourceTree); Assert.Equal(method.Identifier.Span, tokenLocation.SourceSpan); var triviaLocation = method.ReturnType.GetLastToken().TrailingTrivia[0].GetLocation(); Assert.True(triviaLocation.IsInSource); Assert.Equal(tree, triviaLocation.SourceTree); Assert.Equal(method.ReturnType.GetLastToken().TrailingTrivia[0].Span, triviaLocation.SourceSpan); var textSpan = new TextSpan(5, 10); var spanLocation = tree.GetLocation(textSpan); Assert.True(spanLocation.IsInSource); Assert.Equal(tree, spanLocation.SourceTree); Assert.Equal(textSpan, spanLocation.SourceSpan); } [Fact] public void TestReplaceNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var bex = (BinaryExpressionSyntax)expr; var expr2 = bex.ReplaceNode(bex.Right, SyntaxFactory.ParseExpression("c")); Assert.Equal("a + c", expr2.ToFullString()); } [Fact] public void TestReplaceNodes() { var expr = SyntaxFactory.ParseExpression("a + b + c + d"); // replace each expression with a parenthesized expression var replaced = expr.ReplaceNodes( expr.DescendantNodes().OfType<ExpressionSyntax>(), (node, rewritten) => SyntaxFactory.ParenthesizedExpression(rewritten)); var replacedText = replaced.ToFullString(); Assert.Equal("(((a )+ (b ))+ (c ))+ (d)", replacedText); } [Fact] public void TestReplaceNodeInListWithMultiple() { var invocation = (InvocationExpressionSyntax)SyntaxFactory.ParseExpression("m(a, b)"); var argC = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c")); var argD = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("d")); // replace first with multiple var newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD }); Assert.Equal("m(c,d, b)", newNode.ToFullString()); // replace last with multiple newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a, c,d)", newNode.ToFullString()); // replace first with empty list newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { }); Assert.Equal("m(b)", newNode.ToFullString()); // replace last with empty list newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { }); Assert.Equal("m(a)", newNode.ToFullString()); } [Fact] public void TestReplaceNonListNodeWithMultiple() { var ifstatement = (IfStatementSyntax)SyntaxFactory.ParseStatement("if (a < b) m(c)"); var then = ifstatement.Statement; var stat1 = SyntaxFactory.ParseStatement("m1(x)"); var stat2 = SyntaxFactory.ParseStatement("m2(y)"); // you cannot replace a node that is a single node member with multiple nodes Assert.Throws<InvalidOperationException>(() => ifstatement.ReplaceNode(then, new[] { stat1, stat2 })); // you cannot replace a node that is a single node member with an empty list Assert.Throws<InvalidOperationException>(() => ifstatement.ReplaceNode(then, new StatementSyntax[] { })); } [Fact] public void TestInsertNodesInList() { var invocation = (InvocationExpressionSyntax)SyntaxFactory.ParseExpression("m(a, b)"); var argC = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c")); var argD = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("d")); // insert before first var newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD }); Assert.Equal("m(c,d,a, b)", newNode.ToFullString()); // insert after first newNode = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a,c,d, b)", newNode.ToFullString()); // insert before last newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a,c,d, b)", newNode.ToFullString()); // insert after last newNode = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a, b,c,d)", newNode.ToFullString()); } [Fact] public void TestInsertNodesRelativeToNonListNode() { var ifstatement = (IfStatementSyntax)SyntaxFactory.ParseStatement("if (a < b) m(c)"); var then = ifstatement.Statement; var stat1 = SyntaxFactory.ParseStatement("m1(x)"); var stat2 = SyntaxFactory.ParseStatement("m2(y)"); // you cannot insert nodes before/after a node that is not part of a list Assert.Throws<InvalidOperationException>(() => ifstatement.InsertNodesBefore(then, new[] { stat1, stat2 })); // you cannot insert nodes before/after a node that is not part of a list Assert.Throws<InvalidOperationException>(() => ifstatement.InsertNodesAfter(then, new StatementSyntax[] { })); } [Fact] public void TestReplaceStatementInListWithMultiple() { var block = (BlockSyntax)SyntaxFactory.ParseStatement("{ var x = 10; var y = 20; }"); var stmt1 = SyntaxFactory.ParseStatement("var z = 30; "); var stmt2 = SyntaxFactory.ParseStatement("var q = 40; "); // replace first with multiple var newBlock = block.ReplaceNode(block.Statements[0], new[] { stmt1, stmt2 }); Assert.Equal("{ var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString()); // replace second with multiple newBlock = block.ReplaceNode(block.Statements[1], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var z = 30; var q = 40; }", newBlock.ToFullString()); // replace first with empty list newBlock = block.ReplaceNode(block.Statements[0], new SyntaxNode[] { }); Assert.Equal("{ var y = 20; }", newBlock.ToFullString()); // replace second with empty list newBlock = block.ReplaceNode(block.Statements[1], new SyntaxNode[] { }); Assert.Equal("{ var x = 10; }", newBlock.ToFullString()); } [Fact] public void TestInsertStatementsInList() { var block = (BlockSyntax)SyntaxFactory.ParseStatement("{ var x = 10; var y = 20; }"); var stmt1 = SyntaxFactory.ParseStatement("var z = 30; "); var stmt2 = SyntaxFactory.ParseStatement("var q = 40; "); // insert before first var newBlock = block.InsertNodesBefore(block.Statements[0], new[] { stmt1, stmt2 }); Assert.Equal("{ var z = 30; var q = 40; var x = 10; var y = 20; }", newBlock.ToFullString()); // insert after first newBlock = block.InsertNodesAfter(block.Statements[0], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString()); // insert before last newBlock = block.InsertNodesBefore(block.Statements[1], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString()); // insert after last newBlock = block.InsertNodesAfter(block.Statements[1], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var y = 20; var z = 30; var q = 40; }", newBlock.ToFullString()); } [Fact] public void TestReplaceSingleToken() { var expr = SyntaxFactory.ParseExpression("a + b"); var bToken = expr.DescendantTokens().First(t => t.Text == "b"); var expr2 = expr.ReplaceToken(bToken, SyntaxFactory.ParseToken("c")); Assert.Equal("a + c", expr2.ToString()); } [Fact] public void TestReplaceMultipleTokens() { var expr = SyntaxFactory.ParseExpression("a + b + c"); var d = SyntaxFactory.ParseToken("d "); var tokens = expr.DescendantTokens().Where(t => t.IsKind(SyntaxKind.IdentifierToken)).ToList(); var replaced = expr.ReplaceTokens(tokens, (tok, tok2) => d); Assert.Equal("d + d + d ", replaced.ToFullString()); } [Fact] public void TestReplaceSingleTokenWithMultipleTokens() { var cu = SyntaxFactory.ParseCompilationUnit("private class C { }"); var privateToken = ((ClassDeclarationSyntax)cu.Members[0]).Modifiers[0]; var publicToken = SyntaxFactory.ParseToken("public "); var partialToken = SyntaxFactory.ParseToken("partial "); var cu1 = cu.ReplaceToken(privateToken, publicToken); Assert.Equal("public class C { }", cu1.ToFullString()); var cu2 = cu.ReplaceToken(privateToken, new[] { publicToken, partialToken }); Assert.Equal("public partial class C { }", cu2.ToFullString()); var cu3 = cu.ReplaceToken(privateToken, new SyntaxToken[] { }); Assert.Equal("class C { }", cu3.ToFullString()); } [Fact] public void TestReplaceNonListTokenWithMultipleTokensFails() { var cu = SyntaxFactory.ParseCompilationUnit("private class C { }"); var identifierC = cu.DescendantTokens().First(t => t.Text == "C"); var identifierA = SyntaxFactory.ParseToken("A"); var identifierB = SyntaxFactory.ParseToken("B"); // you cannot replace a token that is a single token member with multiple tokens Assert.Throws<InvalidOperationException>(() => cu.ReplaceToken(identifierC, new[] { identifierA, identifierB })); // you cannot replace a token that is a single token member with an empty list of tokens Assert.Throws<InvalidOperationException>(() => cu.ReplaceToken(identifierC, new SyntaxToken[] { })); } [Fact] public void TestInsertTokens() { var cu = SyntaxFactory.ParseCompilationUnit("public class C { }"); var publicToken = ((ClassDeclarationSyntax)cu.Members[0]).Modifiers[0]; var partialToken = SyntaxFactory.ParseToken("partial "); var staticToken = SyntaxFactory.ParseToken("static "); var cu1 = cu.InsertTokensBefore(publicToken, new[] { staticToken }); Assert.Equal("static public class C { }", cu1.ToFullString()); var cu2 = cu.InsertTokensAfter(publicToken, new[] { staticToken }); Assert.Equal("public static class C { }", cu2.ToFullString()); } [Fact] public void TestInsertTokensRelativeToNonListToken() { var cu = SyntaxFactory.ParseCompilationUnit("public class C { }"); var identifierC = cu.DescendantTokens().First(t => t.Text == "C"); var identifierA = SyntaxFactory.ParseToken("A"); var identifierB = SyntaxFactory.ParseToken("B"); // you cannot insert a token before/after a token that is not part of a list of tokens Assert.Throws<InvalidOperationException>(() => cu.InsertTokensBefore(identifierC, new[] { identifierA, identifierB })); // you cannot insert a token before/after a token that is not part of a list of tokens Assert.Throws<InvalidOperationException>(() => cu.InsertTokensAfter(identifierC, new[] { identifierA, identifierB })); } [Fact] public void ReplaceMissingToken() { var text = "return x"; var expr = SyntaxFactory.ParseStatement(text); var token = expr.DescendantTokens().First(t => t.IsMissing); var expr2 = expr.ReplaceToken(token, SyntaxFactory.Token(token.Kind())); var text2 = expr2.ToFullString(); Assert.Equal("return x;", text2); } [Fact] public void ReplaceEndOfCommentToken() { var text = "/// Goo\r\n return x;"; var expr = SyntaxFactory.ParseStatement(text); var tokens = expr.DescendantTokens(descendIntoTrivia: true).ToList(); var token = tokens.First(t => t.Kind() == SyntaxKind.EndOfDocumentationCommentToken); var expr2 = expr.ReplaceToken(token, SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.Whitespace("garbage")), token.Kind(), default(SyntaxTriviaList))); var text2 = expr2.ToFullString(); Assert.Equal("/// Goo\r\ngarbage return x;", text2); } [Fact] public void ReplaceEndOfFileToken() { var text = ""; var cu = SyntaxFactory.ParseCompilationUnit(text); var token = cu.DescendantTokens().Single(t => t.Kind() == SyntaxKind.EndOfFileToken); var cu2 = cu.ReplaceToken(token, SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.Whitespace(" ")), token.Kind(), default(SyntaxTriviaList))); var text2 = cu2.ToFullString(); Assert.Equal(" ", text2); } [Fact] public void TestReplaceTriviaDeep() { var expr = SyntaxFactory.ParseExpression("#if true\r\na + \r\n#endif\r\n + b"); // get whitespace trivia inside structured directive trivia var deepTrivia = expr.GetDirectives().SelectMany(d => d.DescendantTrivia().Where(tr => tr.Kind() == SyntaxKind.WhitespaceTrivia)).ToList(); // replace deep trivia with double-whitespace trivia var twoSpace = SyntaxFactory.Whitespace(" "); var expr2 = expr.ReplaceTrivia(deepTrivia, (tr, tr2) => twoSpace); Assert.Equal("#if true\r\na + \r\n#endif\r\n + b", expr2.ToFullString()); } [Fact] public void TestReplaceSingleTriviaInNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var trivia = expr.DescendantTokens().First(t => t.Text == "a").TrailingTrivia[0]; var twoSpaces = SyntaxFactory.Whitespace(" "); var expr2 = expr.ReplaceTrivia(trivia, twoSpaces); Assert.Equal("a + b", expr2.ToFullString()); } [Fact] public void TestReplaceMultipleTriviaInNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var twoSpaces = SyntaxFactory.Whitespace(" "); var trivia = expr.DescendantTrivia().Where(tr => tr.IsKind(SyntaxKind.WhitespaceTrivia)).ToList(); var replaced = expr.ReplaceTrivia(trivia, (tr, tr2) => twoSpaces); Assert.Equal("a + b", replaced.ToFullString()); } [Fact] public void TestReplaceSingleTriviaWithMultipleTriviaInNode() { var ex = SyntaxFactory.ParseExpression("/* c */ identifier"); var leadingTrivia = ex.GetLeadingTrivia(); Assert.Equal(2, leadingTrivia.Count); var comment1 = leadingTrivia[0]; Assert.Equal(SyntaxKind.MultiLineCommentTrivia, comment1.Kind()); var newComment1 = SyntaxFactory.ParseLeadingTrivia("/* a */")[0]; var newComment2 = SyntaxFactory.ParseLeadingTrivia("/* b */")[0]; var ex1 = ex.ReplaceTrivia(comment1, newComment1); Assert.Equal("/* a */ identifier", ex1.ToFullString()); var ex2 = ex.ReplaceTrivia(comment1, new[] { newComment1, newComment2 }); Assert.Equal("/* a *//* b */ identifier", ex2.ToFullString()); var ex3 = ex.ReplaceTrivia(comment1, new SyntaxTrivia[] { }); Assert.Equal(" identifier", ex3.ToFullString()); } [Fact] public void TestInsertTriviaInNode() { var ex = SyntaxFactory.ParseExpression("/* c */ identifier"); var leadingTrivia = ex.GetLeadingTrivia(); Assert.Equal(2, leadingTrivia.Count); var comment1 = leadingTrivia[0]; Assert.Equal(SyntaxKind.MultiLineCommentTrivia, comment1.Kind()); var newComment1 = SyntaxFactory.ParseLeadingTrivia("/* a */")[0]; var newComment2 = SyntaxFactory.ParseLeadingTrivia("/* b */")[0]; var ex1 = ex.InsertTriviaBefore(comment1, new[] { newComment1, newComment2 }); Assert.Equal("/* a *//* b *//* c */ identifier", ex1.ToFullString()); var ex2 = ex.InsertTriviaAfter(comment1, new[] { newComment1, newComment2 }); Assert.Equal("/* c *//* a *//* b */ identifier", ex2.ToFullString()); } [Fact] public void TestReplaceSingleTriviaInToken() { var id = SyntaxFactory.ParseToken("a "); var trivia = id.TrailingTrivia[0]; var twoSpace = SyntaxFactory.Whitespace(" "); var id2 = id.ReplaceTrivia(trivia, twoSpace); Assert.Equal("a ", id2.ToFullString()); } [Fact] public void TestReplaceMultipleTriviaInToken() { var id = SyntaxFactory.ParseToken("a // goo\r\n"); // replace each trivia with a single space var id2 = id.ReplaceTrivia(id.GetAllTrivia(), (tr, tr2) => SyntaxFactory.Space); // should be 3 spaces (one for original space, comment and end-of-line) Assert.Equal("a ", id2.ToFullString()); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(a , /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_2() { var expr = SyntaxFactory.ParseExpression(@"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_3() { var expr = SyntaxFactory.ParseExpression(@"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_4() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(/*arg1:*/ a, /*arg2:*/ b, /*arg3:*/ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(/*arg1:*/ a, /*arg2:*/ /*arg3:*/ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_5() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(// comment about a a, // some comment about b b, // some comment about c c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(// comment about a a, // some comment about b // some comment about c c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia() { var expr = SyntaxFactory.ParseExpression("m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal("m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_2() { var expr = SyntaxFactory.ParseExpression( @"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_3() { var expr = SyntaxFactory.ParseExpression( @"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_4() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(/*arg1:*/ a, /*arg2:*/ b, /*arg3:*/ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(/*arg1:*/ a, /*arg3:*/ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_5() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(// comment about a a, // some comment about b b, // some comment about c c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(// comment about a a, // some comment about c c)", text); } [Fact] public void TestRemoveOnlyNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(/* before */ a /* after */)"); var n = expr.DescendantTokens().Where(t => t.Text == "a").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(n); var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(/* before */ /* after */)", text); } [Fact] public void TestRemoveFirstNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(/* before */ a /* after */, b, c)"); var n = expr.DescendantTokens().Where(t => t.Text == "a").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(n); var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(/* before */ /* after */ b, c)", text); } [Fact] public void TestRemoveLastNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(a, b, /* before */ c /* after */)"); var n = expr.DescendantTokens().Where(t => t.Text == "c").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(n); var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(a, b /* before */ /* after */)", text); } [Fact] public void TestRemoveNode_KeepNoTrivia() { var expr = SyntaxFactory.ParseStatement("{ a; b; /* trivia */ c }"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<StatementSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal("{ a; c }", text); } [Fact] public void TestRemoveNode_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseStatement("{ a; b; /* trivia */ c }"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<StatementSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("{ a; /* trivia */ c }", text); } [Fact] public void TestRemoveLastNode_KeepExteriorTrivia() { // this tests removing the last node in a non-terminal such that there is no token to the right of the removed // node to attach the kept trivia too. The trivia must be attached to the previous token. var cu = SyntaxFactory.ParseCompilationUnit("class C { void M() { } /* trivia */ }"); var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); // remove the body block from the method syntax (since it can be set to null) var m2 = m.RemoveNode(m.Body, SyntaxRemoveOptions.KeepExteriorTrivia); var text = m2.ToFullString(); Assert.Equal("void M() /* trivia */ ", text); } [Fact] public void TestRemove_KeepExteriorTrivia_KeepUnbalancedDirectives() { var cu = SyntaxFactory.ParseCompilationUnit(@" class C { // before void M() { #region Fred } // after #endregion }"); var expectedText = @" class C { // before #region Fred // after #endregion }"; var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepExteriorTrivia | SyntaxRemoveOptions.KeepUnbalancedDirectives); var text = cu2.ToFullString(); Assert.Equal(expectedText, text); } [Fact] public void TestRemove_KeepUnbalancedDirectives() { var inputText = @" class C { // before #region Fred // more before void M() { } // after #endregion }"; var expectedText = @" class C { #region Fred #endregion }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepUnbalancedDirectives); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] public void TestRemove_KeepDirectives() { var inputText = @" class C { // before #region Fred // more before void M() { #if true #endif } // after #endregion }"; var expectedText = @" class C { #region Fred #if true #endif #endregion }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepDirectives); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemove_KeepEndOfLine() { var inputText = @" class C { // before void M() { } // after }"; var expectedText = @" class C { }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveWithoutEOL_KeepEndOfLine() { var cu = SyntaxFactory.ParseCompilationUnit(@"class A { } class B { } // test"); var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal("class A { } ", text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveBadDirectiveWithoutEOL_KeepEndOfLine_KeepDirectives() { var cu = SyntaxFactory.ParseCompilationUnit(@"class A { } class B { } #endregion"); var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine | SyntaxRemoveOptions.KeepDirectives); var text = cu2.ToFullString(); Assert.Equal("class A { } \r\n#endregion", text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveDocument_KeepEndOfLine() { var cu = SyntaxFactory.ParseCompilationUnit(@" #region A class A { } #endregion"); var cu2 = cu.RemoveNode(cu, SyntaxRemoveOptions.KeepEndOfLine); Assert.Null(cu2); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameterEOLCommaTokenTrailingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken TrailingTrivia var inputText = @" class C { void M( // before a int a, // after a // before b int b /* after b*/) { } }"; var expectedText = @" class C { void M( // after a // before b int b /* after b*/) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameterEOLParameterSyntaxTrailingTrivia_KeepEndOfLine() { // EOL should be found on ParameterSyntax TrailingTrivia var inputText = @" class C { void M( // before a int a , /* after comma */ int b /* after b*/) { } }"; var expectedText = @" class C { void M( int b /* after b*/) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameterEOLCommaTokenLeadingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken LeadingTrivia and also on ParameterSyntax TrailingTrivia // but only one will be added var inputText = @" class C { void M( // before a int a // before b , /* after comma */ int b /* after b*/) { } }"; var expectedText = @" class C { void M( int b /* after b*/) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameter_KeepTrailingTrivia() { var cu = SyntaxFactory.ParseCompilationUnit(@" class C { void M( // before a int a // before b , /* after comma */ int b /* after b*/) { } }"); var expectedText = @" class C { void M( // before b /* after comma */ int b /* after b*/) { } }"; var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepTrailingTrivia); var text = cu2.ToFullString(); Assert.Equal(expectedText, text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameterEOLCommaTokenLeadingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken LeadingTrivia var inputText = @" class C { void M( // before a int a // after a , /* after comma*/ int b /* after b*/) { } }"; var expectedText = @" class C { void M( // before a int a ) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameterEOLCommaTokenTrailingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken TrailingTrivia var inputText = @" class C { void M( // before a int a, /* after comma*/ int b /* after b*/) { } }"; var expectedText = @" class C { void M( // before a int a ) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameterEOLParameterSyntaxLeadingTrivia_KeepEndOfLine() { // EOL should be found on ParameterSyntax LeadingTrivia and also on CommaToken TrailingTrivia // but only one will be added var inputText = @" class C { void M( // before a int a, /* after comma */ // before b int b /* after b*/) { } }"; var expectedText = @" class C { void M( // before a int a ) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameter_KeepLeadingTrivia() { var cu = SyntaxFactory.ParseCompilationUnit(@" class C { void M( // before a int a, /* after comma */ // before b int b /* after b*/) { } }"); var expectedText = @" class C { void M( // before a int a /* after comma */ // before b ) { } }"; var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepLeadingTrivia); var text = cu2.ToFullString(); Assert.Equal(expectedText, text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveClassWithEndRegionDirectiveWithoutEOL_KeepEndOfLine_KeepDirectives() { var inputText = @" #region A class A { } #endregion"; var expectedText = @" #region A #endregion"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine | SyntaxRemoveOptions.KeepDirectives); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] public void SeparatorsOfSeparatedSyntaxLists() { var s1 = "int goo(int a, int b, int c) {}"; var tree = SyntaxFactory.ParseSyntaxTree(s1); var root = tree.GetCompilationUnitRoot(); var method = (LocalFunctionStatementSyntax)((GlobalStatementSyntax)root.Members[0]).Statement; var list = (SeparatedSyntaxList<ParameterSyntax>)method.ParameterList.Parameters; Assert.Equal(SyntaxKind.CommaToken, ((SyntaxToken)list.GetSeparator(0)).Kind()); Assert.Equal(SyntaxKind.CommaToken, ((SyntaxToken)list.GetSeparator(1)).Kind()); foreach (var index in new int[] { -1, 2 }) { bool exceptionThrown = false; try { var unused = list.GetSeparator(2); } catch (ArgumentOutOfRangeException) { exceptionThrown = true; } Assert.True(exceptionThrown); } var internalParameterList = (InternalSyntax.ParameterListSyntax)method.ParameterList.Green; var internalParameters = internalParameterList.Parameters; Assert.Equal(2, internalParameters.SeparatorCount); Assert.Equal(SyntaxKind.CommaToken, (new SyntaxToken(internalParameters.GetSeparator(0))).Kind()); Assert.Equal(SyntaxKind.CommaToken, (new SyntaxToken(internalParameters.GetSeparator(1))).Kind()); Assert.Equal(3, internalParameters.Count); Assert.Equal("a", internalParameters[0].Identifier.ValueText); Assert.Equal("b", internalParameters[1].Identifier.ValueText); Assert.Equal("c", internalParameters[2].Identifier.ValueText); } [Fact] public void ThrowIfUnderlyingNodeIsNullForList() { var list = new SyntaxNodeOrTokenList(); Assert.Equal(0, list.Count); foreach (var index in new int[] { -1, 0, 23 }) { bool exceptionThrown = false; try { var unused = list[0]; } catch (ArgumentOutOfRangeException) { exceptionThrown = true; } Assert.True(exceptionThrown); } } [WorkItem(541188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541188")] [Fact] public void GetDiagnosticsOnMissingToken() { var syntaxTree = SyntaxFactory.ParseSyntaxTree(@"namespace n1 { c1<t"); var token = syntaxTree.FindNodeOrTokenByKind(SyntaxKind.GreaterThanToken); var diag = syntaxTree.GetDiagnostics(token).ToList(); Assert.True(token.IsMissing); Assert.Equal(1, diag.Count); } [WorkItem(541325, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541325")] [Fact] public void GetDiagnosticsOnMissingToken2() { var syntaxTree = SyntaxFactory.ParseSyntaxTree(@" class Base<T> { public virtual int Property { get { return 0; } // Note: Repro for bug 7990 requires a missing close brace token i.e. missing } below set { } public virtual void Method() { } }"); foreach (var t in syntaxTree.GetCompilationUnitRoot().DescendantTokens()) { // Bug 7990: Below for loop is an infinite loop. foreach (var e in syntaxTree.GetDiagnostics(t)) { } } // TODO: Please add meaningful checks once the above deadlock issue is fixed. } [WorkItem(541648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541648")] [Fact] public void GetDiagnosticsOnMissingToken4() { string code = @" public class MyClass { using Lib; using Lib2; public class Test1 { } }"; var syntaxTree = SyntaxFactory.ParseSyntaxTree(code); var token = syntaxTree.GetCompilationUnitRoot().FindToken(code.IndexOf("using Lib;", StringComparison.Ordinal)); var diag = syntaxTree.GetDiagnostics(token).ToList(); Assert.True(token.IsMissing); Assert.Equal(3, diag.Count); } [WorkItem(541630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541630")] [Fact] public void GetDiagnosticsOnBadReferenceDirective() { string code = @"class c1 { #r void m1() { } }"; var tree = SyntaxFactory.ParseSyntaxTree(code); var trivia = tree.GetCompilationUnitRoot().FindTrivia(code.IndexOf("#r", StringComparison.Ordinal)); // ReferenceDirective. foreach (var diag in tree.GetDiagnostics(trivia)) { Assert.NotNull(diag); // TODO: Please add any additional validations if necessary. } } [WorkItem(528626, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528626")] [Fact] public void SpanOfNodeWithMissingChildren() { string code = @"delegate = 1;"; var tree = SyntaxFactory.ParseSyntaxTree(code); var compilationUnit = tree.GetCompilationUnitRoot(); var delegateDecl = (DelegateDeclarationSyntax)compilationUnit.Members[0]; var paramList = delegateDecl.ParameterList; // For (non-EOF) tokens, IsMissing is true if and only if Width is 0. Assert.True(compilationUnit.DescendantTokens(node => true). Where(token => token.Kind() != SyntaxKind.EndOfFileToken). All(token => token.IsMissing == (token.Width == 0))); // For non-terminals, Is true if Width is 0, but the converse may not hold. Assert.True(paramList.IsMissing); Assert.NotEqual(0, paramList.Width); Assert.NotEqual(0, paramList.FullWidth); } [WorkItem(542457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542457")] [Fact] public void AddMethodModifier() { var tree = SyntaxFactory.ParseSyntaxTree(@" class Program { static void Main(string[] args) { } }"); var compilationUnit = tree.GetCompilationUnitRoot(); var @class = (ClassDeclarationSyntax)compilationUnit.Members.Single(); var method = (MethodDeclarationSyntax)@class.Members.Single(); var newModifiers = method.Modifiers.Add(SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.UnsafeKeyword, SyntaxFactory.TriviaList(SyntaxFactory.Space))); Assert.Equal(" static unsafe ", newModifiers.ToFullString()); Assert.Equal(2, newModifiers.Count); Assert.Equal(SyntaxKind.StaticKeyword, newModifiers[0].Kind()); Assert.Equal(SyntaxKind.UnsafeKeyword, newModifiers[1].Kind()); } [Fact] public void SeparatedSyntaxListValidation() { var intType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)); var commaToken = SyntaxFactory.Token(SyntaxKind.CommaToken); SyntaxFactory.SingletonSeparatedList<TypeSyntax>(intType); SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken }); SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, intType }); SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, intType, commaToken }); Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { commaToken })); Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, commaToken })); Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, intType })); } [WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")] [Fact] public void SyntaxDotParseCompilationUnitContainingOnlyWhitespace() { var node = SyntaxFactory.ParseCompilationUnit(" "); Assert.True(node.HasLeadingTrivia); Assert.Equal(1, node.GetLeadingTrivia().Count); Assert.Equal(1, node.DescendantTrivia().Count()); Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()); } [WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")] [Fact] public void SyntaxTreeDotParseCompilationUnitContainingOnlyWhitespace() { var node = SyntaxFactory.ParseSyntaxTree(" ").GetCompilationUnitRoot(); Assert.True(node.HasLeadingTrivia); Assert.Equal(1, node.GetLeadingTrivia().Count); Assert.Equal(1, node.DescendantTrivia().Count()); Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()); } [Fact] public void SyntaxNodeAndTokenToString() { var text = @"class A { }"; var root = SyntaxFactory.ParseCompilationUnit(text); var children = root.DescendantNodesAndTokens(); var nodeOrToken = children.First(); Assert.Equal("class A { }", nodeOrToken.ToString()); Assert.Equal(text, nodeOrToken.ToString()); var node = (SyntaxNode)children.First(n => n.IsNode); Assert.Equal("class A { }", node.ToString()); Assert.Equal(text, node.ToFullString()); var token = (SyntaxToken)children.First(n => n.IsToken); Assert.Equal("class", token.ToString()); Assert.Equal("class ", token.ToFullString()); var trivia = root.DescendantTrivia().First(); Assert.Equal(" ", trivia.ToString()); Assert.Equal(" ", trivia.ToFullString()); } [WorkItem(545116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545116")] [Fact] public void FindTriviaOutsideNode() { var text = @"// This is trivia class C { static void Main() { } } "; var root = SyntaxFactory.ParseCompilationUnit(text); Assert.InRange(0, root.FullSpan.Start, root.FullSpan.End); var rootTrivia = root.FindTrivia(0); Assert.Equal("// This is trivia", rootTrivia.ToString().Trim()); var method = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.NotInRange(0, method.FullSpan.Start, method.FullSpan.End); var methodTrivia = method.FindTrivia(0); Assert.Equal(default(SyntaxTrivia), methodTrivia); } [Fact] public void TestSyntaxTriviaListEquals() { var emptyWhitespace = SyntaxFactory.Whitespace(""); var emptyToken = SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken).WithTrailingTrivia(emptyWhitespace, emptyWhitespace); var emptyTokenList = SyntaxFactory.TokenList(emptyToken, emptyToken); // elements should be not equal Assert.NotEqual(emptyTokenList[0].TrailingTrivia[0], emptyTokenList[1].TrailingTrivia[0]); // lists should be not equal Assert.NotEqual(emptyTokenList[0].TrailingTrivia, emptyTokenList[1].TrailingTrivia); // Two lists with the same parent node, but different indexes should NOT be the same. var emptyTriviaList = SyntaxFactory.TriviaList(emptyWhitespace, emptyWhitespace); emptyToken = emptyToken.WithLeadingTrivia(emptyTriviaList).WithTrailingTrivia(emptyTriviaList); // elements should be not equal Assert.NotEqual(emptyToken.LeadingTrivia[0], emptyToken.TrailingTrivia[0]); // lists should be not equal Assert.NotEqual(emptyToken.LeadingTrivia, emptyToken.TrailingTrivia); } [Fact] public void Test_SyntaxTree_ParseTextInvalidArguments() { // Invalid arguments - Validate Exceptions Assert.Throws<System.ArgumentNullException>(delegate { SourceText st = null; var treeFromSource_invalid2 = SyntaxFactory.ParseSyntaxTree(st); }); } [Fact] public void TestSyntaxTree_Changes() { string SourceText = @"using System; using System.Linq; using System.Collections; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText); var root = (CompilationUnitSyntax)tree.GetRoot(); // Get the Imports Clauses var FirstUsingClause = root.Usings[0]; var SecondUsingClause = root.Usings[1]; var ThirdUsingClause = root.Usings[2]; var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChanges(SecondUsingClause.SyntaxTree); Assert.Equal(0, ChangesForDifferentTrees.Count); // Do a transform to Replace and Existing Tree NameSyntax name = SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Collections.Generic")); UsingDirectiveSyntax newUsingClause = ThirdUsingClause.WithName(name); // Replace Node with a different Imports Clause root = root.ReplaceNode(ThirdUsingClause, newUsingClause); var ChangesFromTransform = ThirdUsingClause.SyntaxTree.GetChanges(newUsingClause.SyntaxTree); Assert.Equal(2, ChangesFromTransform.Count); // Using the Common Syntax Changes Method SyntaxTree x = ThirdUsingClause.SyntaxTree; SyntaxTree y = newUsingClause.SyntaxTree; var changes2UsingCommonSyntax = x.GetChanges(y); Assert.Equal(2, changes2UsingCommonSyntax.Count); // Verify Changes from CS Specific SyntaxTree and Common SyntaxTree are the same Assert.Equal(ChangesFromTransform, changes2UsingCommonSyntax); } [Fact, WorkItem(658329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658329")] public void TestSyntaxTree_GetChangesInvalid() { string SourceText = @"using System; using System.Linq; using System.Collections; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText); var root = (CompilationUnitSyntax)tree.GetRoot(); // Get the Imports Clauses var FirstUsingClause = root.Usings[0]; var SecondUsingClause = root.Usings[1]; var ThirdUsingClause = root.Usings[2]; var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChanges(SecondUsingClause.SyntaxTree); Assert.Equal(0, ChangesForDifferentTrees.Count); // With null tree SyntaxTree BlankTree = null; Assert.Throws<ArgumentNullException>(() => FirstUsingClause.SyntaxTree.GetChanges(BlankTree)); } [Fact, WorkItem(658329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658329")] public void TestSyntaxTree_GetChangedSpansInvalid() { string SourceText = @"using System; using System.Linq; using System.Collections; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText); var root = (CompilationUnitSyntax)tree.GetRoot(); // Get the Imports Clauses var FirstUsingClause = root.Usings[0]; var SecondUsingClause = root.Usings[1]; var ThirdUsingClause = root.Usings[2]; var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChangedSpans(SecondUsingClause.SyntaxTree); Assert.Equal(0, ChangesForDifferentTrees.Count); // With null tree SyntaxTree BlankTree = null; Assert.Throws<ArgumentNullException>(() => FirstUsingClause.SyntaxTree.GetChangedSpans(BlankTree)); } [Fact] public void TestTriviaExists() { // token constructed using factory w/o specifying trivia (should have zero-width elastic trivia) var idToken = SyntaxFactory.Identifier("goo"); Assert.True(idToken.HasLeadingTrivia); Assert.Equal(1, idToken.LeadingTrivia.Count); Assert.Equal(0, idToken.LeadingTrivia.Span.Length); // zero-width elastic trivia Assert.True(idToken.HasTrailingTrivia); Assert.Equal(1, idToken.TrailingTrivia.Count); Assert.Equal(0, idToken.TrailingTrivia.Span.Length); // zero-width elastic trivia // token constructed by parser w/o trivia idToken = SyntaxFactory.ParseToken("x"); Assert.False(idToken.HasLeadingTrivia); Assert.Equal(0, idToken.LeadingTrivia.Count); Assert.False(idToken.HasTrailingTrivia); Assert.Equal(0, idToken.TrailingTrivia.Count); // token constructed by parser with trivia idToken = SyntaxFactory.ParseToken(" x "); Assert.True(idToken.HasLeadingTrivia); Assert.Equal(1, idToken.LeadingTrivia.Count); Assert.Equal(1, idToken.LeadingTrivia.Span.Length); Assert.True(idToken.HasTrailingTrivia); Assert.Equal(1, idToken.TrailingTrivia.Count); Assert.Equal(2, idToken.TrailingTrivia.Span.Length); // node constructed using factory w/o specifying trivia SyntaxNode namedNode = SyntaxFactory.IdentifierName("goo"); Assert.True(namedNode.HasLeadingTrivia); Assert.Equal(1, namedNode.GetLeadingTrivia().Count); Assert.Equal(0, namedNode.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(namedNode.HasTrailingTrivia); Assert.Equal(1, namedNode.GetTrailingTrivia().Count); Assert.Equal(0, namedNode.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // node constructed by parse w/o trivia namedNode = SyntaxFactory.ParseExpression("goo"); Assert.False(namedNode.HasLeadingTrivia); Assert.Equal(0, namedNode.GetLeadingTrivia().Count); Assert.False(namedNode.HasTrailingTrivia); Assert.Equal(0, namedNode.GetTrailingTrivia().Count); // node constructed by parse with trivia namedNode = SyntaxFactory.ParseExpression(" goo "); Assert.True(namedNode.HasLeadingTrivia); Assert.Equal(1, namedNode.GetLeadingTrivia().Count); Assert.Equal(1, namedNode.GetLeadingTrivia().Span.Length); Assert.True(namedNode.HasTrailingTrivia); Assert.Equal(1, namedNode.GetTrailingTrivia().Count); Assert.Equal(2, namedNode.GetTrailingTrivia().Span.Length); // nodeOrToken with token constructed from factory w/o specifying trivia SyntaxNodeOrToken nodeOrToken = SyntaxFactory.Identifier("goo"); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // nodeOrToken with node constructed from factory w/o specifying trivia nodeOrToken = SyntaxFactory.IdentifierName("goo"); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // nodeOrToken with token parsed from factory w/o trivia nodeOrToken = SyntaxFactory.ParseToken("goo"); Assert.False(nodeOrToken.HasLeadingTrivia); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Count); Assert.False(nodeOrToken.HasTrailingTrivia); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Count); // nodeOrToken with node parsed from factory w/o trivia nodeOrToken = SyntaxFactory.ParseExpression("goo"); Assert.False(nodeOrToken.HasLeadingTrivia); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Count); Assert.False(nodeOrToken.HasTrailingTrivia); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Count); // nodeOrToken with token parsed from factory with trivia nodeOrToken = SyntaxFactory.ParseToken(" goo "); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(2, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // nodeOrToken with node parsed from factory with trivia nodeOrToken = SyntaxFactory.ParseExpression(" goo "); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(2, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia } [WorkItem(6536, "https://github.com/dotnet/roslyn/issues/6536")] [Fact] public void TestFindTrivia_NoStackOverflowOnLargeExpression() { StringBuilder code = new StringBuilder(); code.Append( @"class Goo { void Bar() { string test = "); for (var i = 0; i < 3000; i++) { code.Append(@"""asdf"" + "); } code.Append(@"""last""; } }"); var tree = SyntaxFactory.ParseSyntaxTree(code.ToString()); var position = 4000; var trivia = tree.GetCompilationUnitRoot().FindTrivia(position); // no stack overflow } [Fact, WorkItem(8625, "https://github.com/dotnet/roslyn/issues/8625")] public void SyntaxNodeContains() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var a = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var firstParens = e.FirstAncestorOrSelf<ExpressionSyntax>(n => n.Kind() == SyntaxKind.ParenthesizedExpression); Assert.False(firstParens.Contains(a)); // fixing #8625 allows this to return quicker Assert.True(firstParens.Contains(e)); } private static void TestWithWindowsAndUnixEndOfLines(string inputText, string expectedText, Action<CompilationUnitSyntax, string> action) { inputText = inputText.NormalizeLineEndings(); expectedText = expectedText.NormalizeLineEndings(); var tests = new Dictionary<string, string> { {inputText, expectedText}, // Test CRLF (Windows) {inputText.Replace("\r", ""), expectedText.Replace("\r", "")}, // Test LF (Unix) }; foreach (var test in tests) { action(SyntaxFactory.ParseCompilationUnit(test.Key), test.Value); } } } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; using System.Text; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxNodeTests { [Fact] [WorkItem(565382, "https://developercommunity.visualstudio.com/content/problem/565382/compiling-causes-a-stack-overflow-error.html")] public void TestLargeFluentCallWithDirective() { var builder = new StringBuilder(); builder.AppendLine( @" class C { C M(string x) { return this; } void M2() { new C() #region Region "); for (int i = 0; i < 20000; i++) { builder.AppendLine(@" .M(""test"")"); } builder.AppendLine( @" .M(""test""); #endregion } }"); var tree = SyntaxFactory.ParseSyntaxTree(builder.ToString()); var directives = tree.GetRoot().GetDirectives(); Assert.Equal(2, directives.Count); } [Fact] public void TestQualifiedNameSyntaxWith() { // this is just a test to prove that at least one generate With method exists and functions correctly. :-) var qname = (QualifiedNameSyntax)SyntaxFactory.ParseName("A.B"); var qname2 = qname.WithRight(SyntaxFactory.IdentifierName("C")); var text = qname2.ToString(); Assert.Equal("A.C", text); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void TestAddBaseListTypes() { var cls = SyntaxFactory.ParseCompilationUnit("class C { }").Members[0] as ClassDeclarationSyntax; var cls2 = cls.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("B"))); } [Fact] public void TestChildNodes() { var text = "m(a,b,c)"; var expression = SyntaxFactory.ParseExpression(text); var nodes = expression.ChildNodes().ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.IdentifierName, nodes[0].Kind()); Assert.Equal(SyntaxKind.ArgumentList, nodes[1].Kind()); } [Fact] public void TestAncestors() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var nodes = e.Ancestors().ToList(); Assert.Equal(7, nodes.Count); Assert.Equal(SyntaxKind.DivideExpression, nodes[0].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.MultiplyExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[3].Kind()); Assert.Equal(SyntaxKind.SubtractExpression, nodes[4].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[5].Kind()); Assert.Equal(SyntaxKind.AddExpression, nodes[6].Kind()); } [Fact] public void TestAncestorsAndSelf() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var nodes = e.AncestorsAndSelf().ToList(); Assert.Equal(8, nodes.Count); Assert.Equal(SyntaxKind.IdentifierName, nodes[0].Kind()); Assert.Equal(SyntaxKind.DivideExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.MultiplyExpression, nodes[3].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[4].Kind()); Assert.Equal(SyntaxKind.SubtractExpression, nodes[5].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[6].Kind()); Assert.Equal(SyntaxKind.AddExpression, nodes[7].Kind()); } [Fact] public void TestFirstAncestorOrSelf() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var firstParens = e.FirstAncestorOrSelf<ExpressionSyntax>(n => n.Kind() == SyntaxKind.ParenthesizedExpression); Assert.NotNull(firstParens); Assert.Equal("(d / e)", firstParens.ToString()); } [Fact] public void TestDescendantNodes() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodes = statement.DescendantNodes().ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); nodes = statement.DescendantNodes(n => n is StatementSyntax).ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); // all over again with spans nodes = statement.DescendantNodes(statement.FullSpan).ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(statement.FullSpan, descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); nodes = statement.DescendantNodes(statement.FullSpan, n => n is StatementSyntax).ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(statement.FullSpan, n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); } [Fact] public void TestDescendantNodesAndSelf() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodes = statement.DescendantNodesAndSelf().ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(descendIntoTrivia: true).ToList(); Assert.Equal(4, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[3].Kind()); nodes = statement.DescendantNodesAndSelf(n => n is StatementSyntax).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); // all over again with spans nodes = statement.DescendantNodesAndSelf(statement.FullSpan).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(statement.FullSpan, descendIntoTrivia: true).ToList(); Assert.Equal(4, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[3].Kind()); nodes = statement.DescendantNodesAndSelf(statement.FullSpan, n => n is StatementSyntax).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(statement.FullSpan, n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); } [Fact] public void TestDescendantNodesAndTokens() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodesAndTokens = statement.DescendantNodesAndTokens().ToList(); Assert.Equal(4, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[3].Kind()); nodesAndTokens = statement.DescendantNodesAndTokens(descendIntoTrivia: true).ToList(); Assert.Equal(10, nodesAndTokens.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.HashToken, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.IfKeyword, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[4].Kind()); Assert.Equal(SyntaxKind.EndOfDirectiveToken, nodesAndTokens[5].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[6].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[7].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[8].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[9].Kind()); // with span nodesAndTokens = statement.DescendantNodesAndTokens(statement.FullSpan).ToList(); Assert.Equal(4, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[3].Kind()); } [Fact] public void TestDescendantNodesAndTokensAndSelf() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodesAndTokens = statement.DescendantNodesAndTokensAndSelf().ToList(); Assert.Equal(5, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[4].Kind()); nodesAndTokens = statement.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToList(); Assert.Equal(11, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.HashToken, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.IfKeyword, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[4].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[5].Kind()); Assert.Equal(SyntaxKind.EndOfDirectiveToken, nodesAndTokens[6].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[7].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[8].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[9].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[10].Kind()); // with span nodesAndTokens = statement.DescendantNodesAndTokensAndSelf(statement.FullSpan).ToList(); Assert.Equal(5, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[4].Kind()); } [Fact] public void TestDescendantNodesAndTokensAndSelfForEmptyCompilationUnit() { var text = ""; var cu = SyntaxFactory.ParseCompilationUnit(text); var nodesAndTokens = cu.DescendantNodesAndTokensAndSelf().ToList(); Assert.Equal(2, nodesAndTokens.Count); Assert.Equal(SyntaxKind.CompilationUnit, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, nodesAndTokens[1].Kind()); } [Fact] public void TestDescendantNodesAndTokensAndSelfForDocumentationComment() { var text = "/// Goo\r\n x"; var expr = SyntaxFactory.ParseExpression(text); var nodesAndTokens = expr.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToList(); Assert.Equal(7, nodesAndTokens.Count); Assert.Equal(SyntaxKind.IdentifierName, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.SingleLineDocumentationCommentTrivia, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.XmlText, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.XmlTextLiteralToken, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.XmlTextLiteralNewLineToken, nodesAndTokens[4].Kind()); Assert.Equal(SyntaxKind.EndOfDocumentationCommentToken, nodesAndTokens[5].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, nodesAndTokens[6].Kind()); } [Fact] public void TestGetAllDirectivesUsingDescendantNodes() { var text = "#if false\r\n eat a sandwich\r\n#endif\r\n x"; var expr = SyntaxFactory.ParseExpression(text); var directives = expr.GetDirectives(); var descendantDirectives = expr.DescendantNodesAndSelf(n => n.ContainsDirectives, descendIntoTrivia: true).OfType<DirectiveTriviaSyntax>().ToList(); Assert.Equal(directives.Count, descendantDirectives.Count); for (int i = 0; i < directives.Count; i++) { Assert.Equal(directives[i], descendantDirectives[i]); } } [Fact] public void TestGetAllAnnotatedNodesUsingDescendantNodes() { var text = "a + (b - (c * (d / e)))"; var expr = SyntaxFactory.ParseExpression(text); var myAnnotation = new SyntaxAnnotation(); var identifierNodes = expr.DescendantNodes().OfType<IdentifierNameSyntax>().ToList(); var exprWithAnnotations = expr.ReplaceNodes(identifierNodes, (e, e2) => e2.WithAdditionalAnnotations(myAnnotation)); var nodesWithMyAnnotations = exprWithAnnotations.DescendantNodesAndSelf(n => n.ContainsAnnotations).Where(n => n.HasAnnotation(myAnnotation)).ToList(); Assert.Equal(identifierNodes.Count, nodesWithMyAnnotations.Count); for (int i = 0; i < identifierNodes.Count; i++) { // compare text because node identity changed when adding the annotation Assert.Equal(identifierNodes[i].ToString(), nodesWithMyAnnotations[i].ToString()); } } [Fact] public void TestDescendantTokens() { var s1 = "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.UsingKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, tokens[3].Kind()); } [Fact] public void TestDescendantTokensWithExtraWhitespace() { var s1 = " using Goo ; "; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.UsingKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, tokens[3].Kind()); } [Fact] public void TestDescendantTokensEntireRange() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(8, tokens.Count); Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[3].Kind()); Assert.Equal(SyntaxKind.UsingKeyword, tokens[4].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[5].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[6].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, tokens[7].Kind()); } [Fact] public void TestDescendantTokensOverFullSpan() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(0, 16)).ToList(); Assert.Equal(3, tokens.Count); Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind()); } [Fact] public void TestDescendantTokensOverInsideSpan() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(1, 14)).ToList(); Assert.Equal(3, tokens.Count); Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind()); } [Fact] public void TestDescendantTokensOverFullSpanOffset() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(7, 17)).ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.AliasKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.UsingKeyword, tokens[3].Kind()); } [Fact] public void TestDescendantTokensOverInsideSpanOffset() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(8, 15)).ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.AliasKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.UsingKeyword, tokens[3].Kind()); } [Fact] public void TestDescendantTrivia() { var text = "// goo\r\na + b"; var expr = SyntaxFactory.ParseExpression(text); var list = expr.DescendantTrivia().ToList(); Assert.Equal(4, list.Count); Assert.Equal(SyntaxKind.SingleLineCommentTrivia, list[0].Kind()); Assert.Equal(SyntaxKind.EndOfLineTrivia, list[1].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[2].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[3].Kind()); } [Fact] public void TestDescendantTriviaIntoStructuredTrivia() { var text = @" /// <goo > /// </goo> a + b"; var expr = SyntaxFactory.ParseExpression(text); var list = expr.DescendantTrivia(descendIntoTrivia: true).ToList(); Assert.Equal(7, list.Count); Assert.Equal(SyntaxKind.EndOfLineTrivia, list[0].Kind()); Assert.Equal(SyntaxKind.SingleLineDocumentationCommentTrivia, list[1].Kind()); Assert.Equal(SyntaxKind.DocumentationCommentExteriorTrivia, list[2].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[3].Kind()); Assert.Equal(SyntaxKind.DocumentationCommentExteriorTrivia, list[4].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[5].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[6].Kind()); } [Fact] public void Bug877223() { var s1 = "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); // var node = t1.GetCompilationUnitRoot().Usings[0].GetTokens(new TextSpan(6, 3)).First(); var node = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(6, 3)).First(); Assert.Equal("Goo", node.ToString()); } [Fact] public void TestFindToken() { var text = "class\n #if XX\n#endif\n goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var token = tree.GetCompilationUnitRoot().FindToken("class\n #i".Length); Assert.Equal(SyntaxKind.IdentifierToken, token.Kind()); Assert.Equal("goo", token.ToString()); token = tree.GetCompilationUnitRoot().FindToken("class\n #i".Length, findInsideTrivia: true); Assert.Equal(SyntaxKind.IfKeyword, token.Kind()); } [Fact] public void TestFindTokenInLargeList() { var identifier = SyntaxFactory.Identifier("x"); var missingIdentifier = SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken); var name = SyntaxFactory.IdentifierName(identifier); var missingName = SyntaxFactory.IdentifierName(missingIdentifier); var comma = SyntaxFactory.Token(SyntaxKind.CommaToken); var missingComma = SyntaxFactory.MissingToken(SyntaxKind.CommaToken); var argument = SyntaxFactory.Argument(name); var missingArgument = SyntaxFactory.Argument(missingName); // make a large list that has lots of zero-length nodes (that shouldn't be found) var nodesAndTokens = SyntaxFactory.NodeOrTokenList( missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, argument); var argumentList = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList<ArgumentSyntax>(SyntaxFactory.NodeOrTokenList(nodesAndTokens))); var invocation = SyntaxFactory.InvocationExpression(name, argumentList); CheckFindToken(invocation); } private void CheckFindToken(SyntaxNode node) { for (int i = 0; i < node.FullSpan.End; i++) { var token = node.FindToken(i); Assert.True(token.FullSpan.Contains(i)); } } [WorkItem(755236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755236")] [Fact] public void TestFindNode() { var text = "class\n #if XX\n#endif\n goo { }\n class bar { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var root = tree.GetRoot(); Assert.Equal(root, root.FindNode(root.Span, findInsideTrivia: false)); Assert.Equal(root, root.FindNode(root.Span, findInsideTrivia: true)); var classDecl = (TypeDeclarationSyntax)root.ChildNodes().First(); // IdentifierNameSyntax in trivia. var identifier = root.DescendantNodes(descendIntoTrivia: true).Single(n => n is IdentifierNameSyntax); var position = identifier.Span.Start + 1; Assert.Equal(classDecl, root.FindNode(identifier.Span, findInsideTrivia: false)); Assert.Equal(identifier, root.FindNode(identifier.Span, findInsideTrivia: true)); // Token span. Assert.Equal(classDecl, root.FindNode(classDecl.Identifier.Span, findInsideTrivia: false)); // EOF Token span. var EOFSpan = new TextSpan(root.FullSpan.End, 0); Assert.Equal(root, root.FindNode(EOFSpan, findInsideTrivia: false)); Assert.Equal(root, root.FindNode(EOFSpan, findInsideTrivia: true)); // EOF Invalid span for childnode var classDecl2 = (TypeDeclarationSyntax)root.ChildNodes().Last(); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(EOFSpan)); // Check end position included in node span var nodeEndPositionSpan = new TextSpan(classDecl.FullSpan.End, 0); Assert.Equal(classDecl2, root.FindNode(nodeEndPositionSpan, findInsideTrivia: false)); Assert.Equal(classDecl2, root.FindNode(nodeEndPositionSpan, findInsideTrivia: true)); Assert.Equal(classDecl2, classDecl2.FindNode(nodeEndPositionSpan, findInsideTrivia: false)); Assert.Equal(classDecl2, classDecl2.FindNode(nodeEndPositionSpan, findInsideTrivia: true)); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl.FindNode(nodeEndPositionSpan)); // Invalid spans. var invalidSpan = new TextSpan(100, 100); Assert.Throws<ArgumentOutOfRangeException>(() => root.FindNode(invalidSpan)); invalidSpan = new TextSpan(root.FullSpan.End - 1, 2); Assert.Throws<ArgumentOutOfRangeException>(() => root.FindNode(invalidSpan)); invalidSpan = new TextSpan(classDecl2.FullSpan.Start - 1, root.FullSpan.End); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(invalidSpan)); invalidSpan = new TextSpan(classDecl.FullSpan.End, root.FullSpan.End); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(invalidSpan)); // Parent node's span. Assert.Throws<ArgumentOutOfRangeException>(() => classDecl.FindNode(root.FullSpan)); } [WorkItem(539941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539941")] [Fact] public void TestFindTriviaNoTriviaExistsAtPosition() { var code = @"class Goo { void Bar() { } }"; var tree = SyntaxFactory.ParseSyntaxTree(code); var position = tree.GetText().Lines[2].End - 1; // position points to the closing parenthesis on the line that has "void Bar()" // There should be no trivia at this position var trivia = tree.GetCompilationUnitRoot().FindTrivia(position); Assert.Equal(SyntaxKind.None, trivia.Kind()); Assert.Equal(0, trivia.SpanStart); Assert.Equal(0, trivia.Span.End); Assert.Equal(default(SyntaxTrivia), trivia); } [Fact] public void TestTreeEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree.GetCompilationUnitRoot().IsEquivalentTo(tree.GetCompilationUnitRoot())); } [Fact] public void TestTreeNotEquivalentToNull() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.False(tree.GetCompilationUnitRoot().IsEquivalentTo(null)); } [Fact] public void TestTreesFromSameSourceEquivalent() { var text = "class goo { }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = SyntaxFactory.ParseSyntaxTree(text); Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot()); Assert.True(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestDifferentTreesNotEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { }"); var tree2 = SyntaxFactory.ParseSyntaxTree("class bar { }"); Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot()); Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestVastlyDifferentTreesNotEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { }"); var tree2 = SyntaxFactory.ParseSyntaxTree(string.Empty); Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot()); Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestSimilarSubtreesEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { void M() { } }"); var tree2 = SyntaxFactory.ParseSyntaxTree("class bar { void M() { } }"); var m1 = ((TypeDeclarationSyntax)tree1.GetCompilationUnitRoot().Members[0]).Members[0]; var m2 = ((TypeDeclarationSyntax)tree2.GetCompilationUnitRoot().Members[0]).Members[0]; Assert.Equal(SyntaxKind.MethodDeclaration, m1.Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, m2.Kind()); Assert.NotEqual(m1, m2); Assert.True(m1.IsEquivalentTo(m2)); } [Fact] public void TestTreesWithDifferentTriviaAreNotEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo {void M() { }}"); var tree2 = SyntaxFactory.ParseSyntaxTree("class goo { void M() { } }"); Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestNodeIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree.GetCompilationUnitRoot().IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot())); } [Fact] public void TestTokenIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree.GetCompilationUnitRoot().EndOfFileToken.IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot().EndOfFileToken)); } [Fact] public void TestDifferentTokensFromSameTreeNotIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.False(tree.GetCompilationUnitRoot().GetFirstToken().IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot().GetFirstToken().GetNextToken())); } [Fact] public void TestCachedTokensFromDifferentTreesIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree1.GetCompilationUnitRoot().GetFirstToken().IsIncrementallyIdenticalTo(tree2.GetCompilationUnitRoot().GetFirstToken())); } [Fact] public void TestNodesFromSameContentNotIncrementallyParsedNotIncrementallyEquivalent() { var text = "class goo { }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = SyntaxFactory.ParseSyntaxTree(text); Assert.False(tree1.GetCompilationUnitRoot().IsIncrementallyIdenticalTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestNodesFromIncrementalParseIncrementallyEquivalent1() { var text = "class goo { void M() { } }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = tree1.WithChangedText(tree1.GetText().WithChanges(new TextChange(default, " "))); Assert.True( tree1.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().IsIncrementallyIdenticalTo( tree2.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); } [Fact] public void TestNodesFromIncrementalParseNotIncrementallyEquivalent1() { var text = "class goo { void M() { } }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = tree1.WithChangedText(tree1.GetText().WithChanges(new TextChange(new TextSpan(22, 0), " return; "))); Assert.False( tree1.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().IsIncrementallyIdenticalTo( tree2.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); } [Fact, WorkItem(536664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536664")] public void TestTriviaNodeCached() { var tree = SyntaxFactory.ParseSyntaxTree(" class goo {}"); // get to the trivia node var trivia = tree.GetCompilationUnitRoot().Members[0].GetLeadingTrivia()[0]; // we get the trivia again var triviaAgain = tree.GetCompilationUnitRoot().Members[0].GetLeadingTrivia()[0]; // should NOT return two distinct objects for trivia and triviaAgain - struct now. Assert.True(SyntaxTrivia.Equals(trivia, triviaAgain)); } [Fact] public void TestGetFirstToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var first = tree.GetCompilationUnitRoot().GetFirstToken(); Assert.Equal(SyntaxKind.PublicKeyword, first.Kind()); } [Fact] public void TestGetFirstTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var first = tree.GetCompilationUnitRoot().GetFirstToken(includeZeroWidth: true); Assert.Equal(SyntaxKind.PublicKeyword, first.Kind()); } [Fact] public void TestGetLastToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var last = tree.GetCompilationUnitRoot().GetLastToken(); Assert.Equal(SyntaxKind.CloseBraceToken, last.Kind()); } [Fact] public void TestGetLastTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { "); var last = tree.GetCompilationUnitRoot().GetLastToken(includeZeroWidth: true); Assert.Equal(SyntaxKind.EndOfFileToken, last.Kind()); last = tree.GetCompilationUnitRoot().Members[0].GetLastToken(includeZeroWidth: true); Assert.Equal(SyntaxKind.CloseBraceToken, last.Kind()); Assert.True(last.IsMissing); Assert.Equal(26, last.FullSpan.Start); } [Fact] public void TestReverseChildSyntaxList() { var tree1 = SyntaxFactory.ParseSyntaxTree("class A {} public class B {} public static class C {}"); var root1 = tree1.GetCompilationUnitRoot(); TestReverse(root1.ChildNodesAndTokens()); TestReverse(root1.Members[0].ChildNodesAndTokens()); TestReverse(root1.Members[1].ChildNodesAndTokens()); TestReverse(root1.Members[2].ChildNodesAndTokens()); } private void TestReverse(ChildSyntaxList children) { var list1 = children.AsEnumerable().Reverse().ToList(); var list2 = children.Reverse().ToList(); Assert.Equal(list1.Count, list2.Count); for (int i = 0; i < list1.Count; i++) { Assert.Equal(list1[i], list2[i]); Assert.Equal(list1[i].FullSpan.Start, list2[i].FullSpan.Start); } } [Fact] public void TestGetNextToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeSkipped: true); } // descendant tokens include EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenIncludingSkippedTokens() { var text = @"garbage using goo.bar; "; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); var tokens = tree.GetCompilationUnitRoot().DescendantTokens(descendIntoTrivia: true).Where(SyntaxToken.NonZeroWidth).ToList(); Assert.Equal(6, tokens.Count); Assert.Equal("garbage", tokens[0].Text); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeSkipped: true); } Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenExcludingSkippedTokens() { var tree = SyntaxFactory.ParseSyntaxTree( @"garbage using goo.bar; "); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(6, tokens.Count); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: false); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeSkipped: false); } // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); SyntaxToken token = syntaxTree.GetRoot().GetFirstToken(); while (token.RawKind != 0) { list.Add(token); token = token.GetNextToken(); } // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().GetLastToken(); // skip EOF while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(); } list.Reverse(); // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenIncludingSkippedTokens() { var text = @"garbage using goo.bar; "; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); var tokens = tree.GetCompilationUnitRoot().DescendantTokens(descendIntoTrivia: true).Where(SyntaxToken.NonZeroWidth).ToList(); Assert.Equal(6, tokens.Count); Assert.Equal("garbage", tokens[0].Text); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetLastToken(includeSkipped: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(includeSkipped: true); } list.Reverse(); Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenExcludingSkippedTokens() { var text = @"garbage using goo.bar; "; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(6, tokens.Count); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetLastToken(includeSkipped: false); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(includeSkipped: false); } list.Reverse(); // descendant tokens includes EOF Assert.Equal(tokens.Count, list.Count + 1); for (int i = 0; i < list.Count; i++) { Assert.Equal(tokens[i], list[i]); } } [Fact] public void TestGetPreviousTokenCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); var token = syntaxTree.GetRoot().GetLastToken(includeZeroWidth: false); // skip EOF while (token.RawKind != 0) { list.Add(token); token = token.GetPreviousToken(); } list.Reverse(); // descendant tokens include EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeZeroWidth: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeZeroWidth: true); } Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenIncludingZeroWidthCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); SyntaxToken token = syntaxTree.GetRoot().GetFirstToken(includeZeroWidth: true); while (token.RawKind != 0) { list.Add(token); token = token.GetNextToken(includeZeroWidth: true); } Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().EndOfFileToken.GetPreviousToken(includeZeroWidth: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(includeZeroWidth: true); } list.Reverse(); // descendant tokens include EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenIncludingZeroWidthCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); SyntaxToken token = ((SyntaxToken)((SyntaxTree)syntaxTree).GetCompilationUnitRoot().EndOfFileToken).GetPreviousToken(includeZeroWidth: true); while (token.RawKind != 0) { list.Add(token); token = token.GetPreviousToken(includeZeroWidth: true); } list.Reverse(); // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(tokens[i], list[i]); } } [Fact] public void TestGetNextSibling() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var children = tree.GetCompilationUnitRoot().Members[0].ChildNodesAndTokens().ToList(); var list = new List<SyntaxNodeOrToken>(); for (var child = children[0]; child.Kind() != SyntaxKind.None; child = child.GetNextSibling()) { list.Add(child); } Assert.Equal(children.Count, list.Count); for (int i = 0; i < children.Count; i++) { Assert.Equal(list[i], children[i]); } } [Fact] public void TestGetPreviousSibling() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var children = tree.GetCompilationUnitRoot().Members[0].ChildNodesAndTokens().ToList(); var reversed = children.AsEnumerable().Reverse().ToList(); var list = new List<SyntaxNodeOrToken>(); for (var child = children[children.Count - 1]; child.Kind() != SyntaxKind.None; child = child.GetPreviousSibling()) { list.Add(child); } Assert.Equal(children.Count, list.Count); for (int i = 0; i < reversed.Count; i++) { Assert.Equal(list[i], reversed[i]); } } [Fact] public void TestSyntaxNodeOrTokenEquality() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var child = tree.GetCompilationUnitRoot().ChildNodesAndTokens()[0]; var member = (TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]; Assert.Equal((SyntaxNodeOrToken)member, child); var name = member.Identifier; var nameChild = member.ChildNodesAndTokens()[3]; Assert.Equal((SyntaxNodeOrToken)name, nameChild); var closeBraceToken = member.CloseBraceToken; var closeBraceChild = member.GetLastToken(); Assert.Equal((SyntaxNodeOrToken)closeBraceToken, closeBraceChild); } [Fact] public void TestStructuredTriviaHasNoParent() { var tree = SyntaxFactory.ParseSyntaxTree("#define GOO"); var trivia = tree.GetCompilationUnitRoot().EndOfFileToken.GetLeadingTrivia()[0]; Assert.Equal(SyntaxKind.DefineDirectiveTrivia, trivia.Kind()); Assert.True(trivia.HasStructure); Assert.NotNull(trivia.GetStructure()); Assert.Null(trivia.GetStructure().Parent); } [Fact] public void TestStructuredTriviaHasParentTrivia() { var tree = SyntaxFactory.ParseSyntaxTree("#define GOO"); var trivia = tree.GetCompilationUnitRoot().EndOfFileToken.GetLeadingTrivia()[0]; Assert.Equal(SyntaxKind.DefineDirectiveTrivia, trivia.Kind()); Assert.True(trivia.HasStructure); Assert.NotNull(trivia.GetStructure()); var parentTrivia = trivia.GetStructure().ParentTrivia; Assert.NotEqual(SyntaxKind.None, parentTrivia.Kind()); Assert.Equal(trivia, parentTrivia); } [Fact] public void TestStructuredTriviaParentTrivia() { var def = SyntaxFactory.DefineDirectiveTrivia(SyntaxFactory.Identifier("GOO"), false); // unrooted structured trivia should report parent trivia as default Assert.Equal(default(SyntaxTrivia), def.ParentTrivia); var trivia = SyntaxFactory.Trivia(def); var structure = trivia.GetStructure(); Assert.NotEqual(def, structure); // these should not be identity equals Assert.True(def.IsEquivalentTo(structure)); // they should be equivalent though Assert.Equal(trivia, structure.ParentTrivia); // parent trivia should be equal to original trivia // attach trivia to token and walk down to structured trivia and back up again var token = SyntaxFactory.Identifier(default(SyntaxTriviaList), "x", SyntaxTriviaList.Create(trivia)); var tokenTrivia = token.TrailingTrivia[0]; var tokenStructuredTrivia = tokenTrivia.GetStructure(); var tokenStructuredParentTrivia = tokenStructuredTrivia.ParentTrivia; Assert.Equal(tokenTrivia, tokenStructuredParentTrivia); Assert.Equal(token, tokenStructuredParentTrivia.Token); } [Fact] public void TestGetFirstDirective() { var tree = SyntaxFactory.ParseSyntaxTree("#define GOO"); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); } [Fact] public void TestGetLastDirective() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #undef GOO "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.UndefDirectiveTrivia, d.Kind()); } [Fact] public void TestGetNextDirective() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #define BAR class C { #if GOO void M() { } #endif } "); var d1 = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d1); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d1.Kind()); var d2 = d1.GetNextDirective(); Assert.NotNull(d2); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d2.Kind()); var d3 = d2.GetNextDirective(); Assert.NotNull(d3); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d3.Kind()); var d4 = d3.GetNextDirective(); Assert.NotNull(d4); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d4.Kind()); var d5 = d4.GetNextDirective(); Assert.Null(d5); } [Fact] public void TestGetPreviousDirective() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #define BAR class C { #if GOO void M() { } #endif } "); var d1 = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d1); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d1.Kind()); var d2 = d1.GetPreviousDirective(); Assert.NotNull(d2); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d2.Kind()); var d3 = d2.GetPreviousDirective(); Assert.NotNull(d3); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d3.Kind()); var d4 = d3.GetPreviousDirective(); Assert.NotNull(d4); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d4.Kind()); var d5 = d4.GetPreviousDirective(); Assert.Null(d5); } [Fact] public void TestGetDirectivesRelatedToIf() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToIfElements() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); // get directives related to elif var related2 = related[1].GetRelatedDirectives(); Assert.True(related.SequenceEqual(related2)); // get directives related to else var related3 = related[3].GetRelatedDirectives(); Assert.True(related.SequenceEqual(related3)); } [Fact] public void TestGetDirectivesRelatedToEndIf() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToIfWithNestedIfEndIF() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #if ZED class A1 { } #endif #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToIfWithNestedRegionEndRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #region some region class A1 { } #endregion #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToEndIfWithNestedIfEndIf() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #if ZED class A1 { } #endif #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToEndIfWithNestedRegionEndRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO #region some region class A { } #endregion #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @"#region Some Region class A { } #endregion #if GOO #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(2, related.Count); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, related[1].Kind()); } [Fact] public void TestGetDirectivesRelatedToEndRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @" #if GOO #endif #region Some Region class A { } #endregion "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(2, related.Count); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, related[1].Kind()); } [WorkItem(536995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536995")] [Fact] public void TestTextAndSpanWithTrivia1() { var tree = SyntaxFactory.ParseSyntaxTree( @"/*START*/namespace Microsoft.CSharp.Test { }/*END*/"); var rootNode = tree.GetCompilationUnitRoot(); Assert.Equal(rootNode.FullSpan.Length, rootNode.ToFullString().Length); Assert.Equal(rootNode.Span.Length, rootNode.ToString().Length); Assert.True(rootNode.ToString().Contains("/*END*/")); Assert.False(rootNode.ToString().Contains("/*START*/")); } [WorkItem(536996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536996")] [Fact] public void TestTextAndSpanWithTrivia2() { var tree = SyntaxFactory.ParseSyntaxTree( @"/*START*/ namespace Microsoft.CSharp.Test { } /*END*/"); var rootNode = tree.GetCompilationUnitRoot(); Assert.Equal(rootNode.FullSpan.Length, rootNode.ToFullString().Length); Assert.Equal(rootNode.Span.Length, rootNode.ToString().Length); Assert.True(rootNode.ToString().Contains("/*END*/")); Assert.False(rootNode.ToString().Contains("/*START*/")); } [Fact] public void TestCreateCommonSyntaxNode() { var rootNode = SyntaxFactory.ParseSyntaxTree("using X; namespace Y { }").GetCompilationUnitRoot(); var namespaceNode = rootNode.ChildNodesAndTokens()[1].AsNode(); var nodeOrToken = (SyntaxNodeOrToken)namespaceNode; Assert.True(nodeOrToken.IsNode); Assert.Equal(namespaceNode, nodeOrToken.AsNode()); Assert.Equal(rootNode, nodeOrToken.Parent); Assert.Equal(namespaceNode.FullSpan, nodeOrToken.FullSpan); Assert.Equal(namespaceNode.Span, nodeOrToken.Span); } [Fact, WorkItem(537070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537070")] public void TestTraversalUsingCommonSyntaxNodeOrToken() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(@"class c1 { }"); var nodeOrToken = (SyntaxNodeOrToken)syntaxTree.GetRoot(); Assert.Equal(0, syntaxTree.GetDiagnostics().Count()); Action<SyntaxNodeOrToken> walk = null; walk = (SyntaxNodeOrToken nOrT) => { Assert.Equal(0, syntaxTree.GetDiagnostics(nOrT).Count()); foreach (var child in nOrT.ChildNodesAndTokens()) { walk(child); } }; walk(nodeOrToken); } [WorkItem(537747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537747")] [Fact] public void SyntaxTriviaDefaultIsDirective() { SyntaxTrivia trivia = new SyntaxTrivia(); Assert.False(trivia.IsDirective); } [Fact] public void SyntaxNames() { var cc = SyntaxFactory.Token(SyntaxKind.ColonColonToken); var lt = SyntaxFactory.Token(SyntaxKind.LessThanToken); var gt = SyntaxFactory.Token(SyntaxKind.GreaterThanToken); var dot = SyntaxFactory.Token(SyntaxKind.DotToken); var gp = SyntaxFactory.SingletonSeparatedList<TypeSyntax>(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword))); var externAlias = SyntaxFactory.IdentifierName("alias"); var goo = SyntaxFactory.IdentifierName("Goo"); var bar = SyntaxFactory.IdentifierName("Bar"); // Goo.Bar var qualified = SyntaxFactory.QualifiedName(goo, dot, bar); Assert.Equal("Goo.Bar", qualified.ToString()); Assert.Equal("Bar", qualified.GetUnqualifiedName().Identifier.ValueText); // Bar<int> var generic = SyntaxFactory.GenericName(bar.Identifier, SyntaxFactory.TypeArgumentList(lt, gp, gt)); Assert.Equal("Bar<int>", generic.ToString()); Assert.Equal("Bar", generic.GetUnqualifiedName().Identifier.ValueText); // Goo.Bar<int> var qualifiedGeneric = SyntaxFactory.QualifiedName(goo, dot, generic); Assert.Equal("Goo.Bar<int>", qualifiedGeneric.ToString()); Assert.Equal("Bar", qualifiedGeneric.GetUnqualifiedName().Identifier.ValueText); // alias::Goo var alias = SyntaxFactory.AliasQualifiedName(externAlias, cc, goo); Assert.Equal("alias::Goo", alias.ToString()); Assert.Equal("Goo", alias.GetUnqualifiedName().Identifier.ValueText); // alias::Bar<int> var aliasGeneric = SyntaxFactory.AliasQualifiedName(externAlias, cc, generic); Assert.Equal("alias::Bar<int>", aliasGeneric.ToString()); Assert.Equal("Bar", aliasGeneric.GetUnqualifiedName().Identifier.ValueText); // alias::Goo.Bar var aliasQualified = SyntaxFactory.QualifiedName(alias, dot, bar); Assert.Equal("alias::Goo.Bar", aliasQualified.ToString()); Assert.Equal("Bar", aliasQualified.GetUnqualifiedName().Identifier.ValueText); // alias::Goo.Bar<int> var aliasQualifiedGeneric = SyntaxFactory.QualifiedName(alias, dot, generic); Assert.Equal("alias::Goo.Bar<int>", aliasQualifiedGeneric.ToString()); Assert.Equal("Bar", aliasQualifiedGeneric.GetUnqualifiedName().Identifier.ValueText); } [Fact] public void ZeroWidthTokensInListAreUnique() { var someToken = SyntaxFactory.MissingToken(SyntaxKind.IntKeyword); var list = SyntaxFactory.TokenList(someToken, someToken); Assert.Equal(someToken, someToken); Assert.NotEqual(list[0], list[1]); } [Fact] public void ZeroWidthTokensInParentAreUnique() { var missingComma = SyntaxFactory.MissingToken(SyntaxKind.CommaToken); var omittedArraySize = SyntaxFactory.OmittedArraySizeExpression(SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken)); var spec = SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.Token(SyntaxKind.OpenBracketToken), SyntaxFactory.SeparatedList<ExpressionSyntax>(new SyntaxNodeOrToken[] { omittedArraySize, missingComma, omittedArraySize, missingComma, omittedArraySize, missingComma, omittedArraySize }), SyntaxFactory.Token(SyntaxKind.CloseBracketToken) ); var sizes = spec.Sizes; Assert.Equal(4, sizes.Count); Assert.Equal(3, sizes.SeparatorCount); Assert.NotEqual(sizes[0], sizes[1]); Assert.NotEqual(sizes[0], sizes[2]); Assert.NotEqual(sizes[0], sizes[3]); Assert.NotEqual(sizes[1], sizes[2]); Assert.NotEqual(sizes[1], sizes[3]); Assert.NotEqual(sizes[2], sizes[3]); Assert.NotEqual(sizes.GetSeparator(0), sizes.GetSeparator(1)); Assert.NotEqual(sizes.GetSeparator(0), sizes.GetSeparator(2)); Assert.NotEqual(sizes.GetSeparator(1), sizes.GetSeparator(2)); } [Fact] public void ZeroWidthStructuredTrivia() { // create zero width structured trivia (not sure how these come about but its not impossible) var zeroWidth = SyntaxFactory.ElseDirectiveTrivia(SyntaxFactory.MissingToken(SyntaxKind.HashToken), SyntaxFactory.MissingToken(SyntaxKind.ElseKeyword), SyntaxFactory.MissingToken(SyntaxKind.EndOfDirectiveToken), false, false); Assert.Equal(0, zeroWidth.Width); // create token with more than one instance of same zero width structured trivia! var someToken = SyntaxFactory.Identifier(default(SyntaxTriviaList), "goo", SyntaxFactory.TriviaList(SyntaxFactory.Trivia(zeroWidth), SyntaxFactory.Trivia(zeroWidth))); // create node with this token var someNode = SyntaxFactory.IdentifierName(someToken); Assert.Equal(2, someNode.Identifier.TrailingTrivia.Count); Assert.True(someNode.Identifier.TrailingTrivia[0].HasStructure); Assert.True(someNode.Identifier.TrailingTrivia[1].HasStructure); // prove that trivia have different identity Assert.False(someNode.Identifier.TrailingTrivia[0].Equals(someNode.Identifier.TrailingTrivia[1])); var tt0 = someNode.Identifier.TrailingTrivia[0]; var tt1 = someNode.Identifier.TrailingTrivia[1]; var str0 = tt0.GetStructure(); var str1 = tt1.GetStructure(); // prove that structures have different identity Assert.NotEqual(str0, str1); // prove that structured trivia can get back to original trivia with correct identity var tr0 = str0.ParentTrivia; Assert.Equal(tt0, tr0); var tr1 = str1.ParentTrivia; Assert.Equal(tt1, tr1); } [Fact] public void ZeroWidthStructuredTriviaOnZeroWidthToken() { // create zero width structured trivia (not sure how these come about but its not impossible) var zeroWidth = SyntaxFactory.ElseDirectiveTrivia(SyntaxFactory.MissingToken(SyntaxKind.HashToken), SyntaxFactory.MissingToken(SyntaxKind.ElseKeyword), SyntaxFactory.MissingToken(SyntaxKind.EndOfDirectiveToken), false, false); Assert.Equal(0, zeroWidth.Width); // create token with more than one instance of same zero width structured trivia! var someToken = SyntaxFactory.Identifier(default(SyntaxTriviaList), "", SyntaxFactory.TriviaList(SyntaxFactory.Trivia(zeroWidth), SyntaxFactory.Trivia(zeroWidth))); // create node with this token var someNode = SyntaxFactory.IdentifierName(someToken); Assert.Equal(2, someNode.Identifier.TrailingTrivia.Count); Assert.True(someNode.Identifier.TrailingTrivia[0].HasStructure); Assert.True(someNode.Identifier.TrailingTrivia[1].HasStructure); // prove that trivia have different identity Assert.False(someNode.Identifier.TrailingTrivia[0].Equals(someNode.Identifier.TrailingTrivia[1])); var tt0 = someNode.Identifier.TrailingTrivia[0]; var tt1 = someNode.Identifier.TrailingTrivia[1]; var str0 = tt0.GetStructure(); var str1 = tt1.GetStructure(); // prove that structures have different identity Assert.NotEqual(str0, str1); // prove that structured trivia can get back to original trivia with correct identity var tr0 = str0.ParentTrivia; Assert.Equal(tt0, tr0); var tr1 = str1.ParentTrivia; Assert.Equal(tt1, tr1); } [WorkItem(537059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537059")] [Fact] public void TestIncompleteDeclWithDotToken() { var tree = SyntaxFactory.ParseSyntaxTree( @" class Test { int IX.GOO "); // Verify the kind of the CSharpSyntaxNode "int IX.GOO" is MethodDeclaration and NOT FieldDeclaration Assert.Equal(SyntaxKind.MethodDeclaration, tree.GetCompilationUnitRoot().ChildNodesAndTokens()[0].ChildNodesAndTokens()[3].Kind()); } [WorkItem(538360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538360")] [Fact] public void TestGetTokensLanguageAny() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("class C {}"); var actualTokens = syntaxTree.GetCompilationUnitRoot().DescendantTokens(); var expectedTokenKinds = new SyntaxKind[] { SyntaxKind.ClassKeyword, SyntaxKind.IdentifierToken, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, SyntaxKind.EndOfFileToken, }; Assert.Equal(expectedTokenKinds.Count(), actualTokens.Count()); //redundant but helps debug Assert.True(expectedTokenKinds.SequenceEqual(actualTokens.Select(t => t.Kind()))); } [WorkItem(538360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538360")] [Fact] public void TestGetTokensCommonAny() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("class C {}"); var actualTokens = syntaxTree.GetRoot().DescendantTokens(syntaxTree.GetRoot().FullSpan); var expectedTokenKinds = new SyntaxKind[] { SyntaxKind.ClassKeyword, SyntaxKind.IdentifierToken, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, SyntaxKind.EndOfFileToken, }; Assert.Equal(expectedTokenKinds.Count(), actualTokens.Count()); //redundant but helps debug Assert.True(expectedTokenKinds.SequenceEqual(actualTokens.Select(t => (SyntaxKind)t.RawKind))); } [Fact] public void TestGetLocation() { var tree = SyntaxFactory.ParseSyntaxTree("class C { void F() { } }"); dynamic root = tree.GetCompilationUnitRoot(); MethodDeclarationSyntax method = root.Members[0].Members[0]; var nodeLocation = method.GetLocation(); Assert.True(nodeLocation.IsInSource); Assert.Equal(tree, nodeLocation.SourceTree); Assert.Equal(method.Span, nodeLocation.SourceSpan); var tokenLocation = method.Identifier.GetLocation(); Assert.True(tokenLocation.IsInSource); Assert.Equal(tree, tokenLocation.SourceTree); Assert.Equal(method.Identifier.Span, tokenLocation.SourceSpan); var triviaLocation = method.ReturnType.GetLastToken().TrailingTrivia[0].GetLocation(); Assert.True(triviaLocation.IsInSource); Assert.Equal(tree, triviaLocation.SourceTree); Assert.Equal(method.ReturnType.GetLastToken().TrailingTrivia[0].Span, triviaLocation.SourceSpan); var textSpan = new TextSpan(5, 10); var spanLocation = tree.GetLocation(textSpan); Assert.True(spanLocation.IsInSource); Assert.Equal(tree, spanLocation.SourceTree); Assert.Equal(textSpan, spanLocation.SourceSpan); } [Fact] public void TestReplaceNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var bex = (BinaryExpressionSyntax)expr; var expr2 = bex.ReplaceNode(bex.Right, SyntaxFactory.ParseExpression("c")); Assert.Equal("a + c", expr2.ToFullString()); } [Fact] public void TestReplaceNodes() { var expr = SyntaxFactory.ParseExpression("a + b + c + d"); // replace each expression with a parenthesized expression var replaced = expr.ReplaceNodes( expr.DescendantNodes().OfType<ExpressionSyntax>(), (node, rewritten) => SyntaxFactory.ParenthesizedExpression(rewritten)); var replacedText = replaced.ToFullString(); Assert.Equal("(((a )+ (b ))+ (c ))+ (d)", replacedText); } [Fact] public void TestReplaceNodeInListWithMultiple() { var invocation = (InvocationExpressionSyntax)SyntaxFactory.ParseExpression("m(a, b)"); var argC = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c")); var argD = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("d")); // replace first with multiple var newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD }); Assert.Equal("m(c,d, b)", newNode.ToFullString()); // replace last with multiple newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a, c,d)", newNode.ToFullString()); // replace first with empty list newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { }); Assert.Equal("m(b)", newNode.ToFullString()); // replace last with empty list newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { }); Assert.Equal("m(a)", newNode.ToFullString()); } [Fact] public void TestReplaceNonListNodeWithMultiple() { var ifstatement = (IfStatementSyntax)SyntaxFactory.ParseStatement("if (a < b) m(c)"); var then = ifstatement.Statement; var stat1 = SyntaxFactory.ParseStatement("m1(x)"); var stat2 = SyntaxFactory.ParseStatement("m2(y)"); // you cannot replace a node that is a single node member with multiple nodes Assert.Throws<InvalidOperationException>(() => ifstatement.ReplaceNode(then, new[] { stat1, stat2 })); // you cannot replace a node that is a single node member with an empty list Assert.Throws<InvalidOperationException>(() => ifstatement.ReplaceNode(then, new StatementSyntax[] { })); } [Fact] public void TestInsertNodesInList() { var invocation = (InvocationExpressionSyntax)SyntaxFactory.ParseExpression("m(a, b)"); var argC = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c")); var argD = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("d")); // insert before first var newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD }); Assert.Equal("m(c,d,a, b)", newNode.ToFullString()); // insert after first newNode = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a,c,d, b)", newNode.ToFullString()); // insert before last newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a,c,d, b)", newNode.ToFullString()); // insert after last newNode = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a, b,c,d)", newNode.ToFullString()); } [Fact] public void TestInsertNodesRelativeToNonListNode() { var ifstatement = (IfStatementSyntax)SyntaxFactory.ParseStatement("if (a < b) m(c)"); var then = ifstatement.Statement; var stat1 = SyntaxFactory.ParseStatement("m1(x)"); var stat2 = SyntaxFactory.ParseStatement("m2(y)"); // you cannot insert nodes before/after a node that is not part of a list Assert.Throws<InvalidOperationException>(() => ifstatement.InsertNodesBefore(then, new[] { stat1, stat2 })); // you cannot insert nodes before/after a node that is not part of a list Assert.Throws<InvalidOperationException>(() => ifstatement.InsertNodesAfter(then, new StatementSyntax[] { })); } [Fact] public void TestReplaceStatementInListWithMultiple() { var block = (BlockSyntax)SyntaxFactory.ParseStatement("{ var x = 10; var y = 20; }"); var stmt1 = SyntaxFactory.ParseStatement("var z = 30; "); var stmt2 = SyntaxFactory.ParseStatement("var q = 40; "); // replace first with multiple var newBlock = block.ReplaceNode(block.Statements[0], new[] { stmt1, stmt2 }); Assert.Equal("{ var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString()); // replace second with multiple newBlock = block.ReplaceNode(block.Statements[1], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var z = 30; var q = 40; }", newBlock.ToFullString()); // replace first with empty list newBlock = block.ReplaceNode(block.Statements[0], new SyntaxNode[] { }); Assert.Equal("{ var y = 20; }", newBlock.ToFullString()); // replace second with empty list newBlock = block.ReplaceNode(block.Statements[1], new SyntaxNode[] { }); Assert.Equal("{ var x = 10; }", newBlock.ToFullString()); } [Fact] public void TestInsertStatementsInList() { var block = (BlockSyntax)SyntaxFactory.ParseStatement("{ var x = 10; var y = 20; }"); var stmt1 = SyntaxFactory.ParseStatement("var z = 30; "); var stmt2 = SyntaxFactory.ParseStatement("var q = 40; "); // insert before first var newBlock = block.InsertNodesBefore(block.Statements[0], new[] { stmt1, stmt2 }); Assert.Equal("{ var z = 30; var q = 40; var x = 10; var y = 20; }", newBlock.ToFullString()); // insert after first newBlock = block.InsertNodesAfter(block.Statements[0], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString()); // insert before last newBlock = block.InsertNodesBefore(block.Statements[1], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString()); // insert after last newBlock = block.InsertNodesAfter(block.Statements[1], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var y = 20; var z = 30; var q = 40; }", newBlock.ToFullString()); } [Fact] public void TestReplaceSingleToken() { var expr = SyntaxFactory.ParseExpression("a + b"); var bToken = expr.DescendantTokens().First(t => t.Text == "b"); var expr2 = expr.ReplaceToken(bToken, SyntaxFactory.ParseToken("c")); Assert.Equal("a + c", expr2.ToString()); } [Fact] public void TestReplaceMultipleTokens() { var expr = SyntaxFactory.ParseExpression("a + b + c"); var d = SyntaxFactory.ParseToken("d "); var tokens = expr.DescendantTokens().Where(t => t.IsKind(SyntaxKind.IdentifierToken)).ToList(); var replaced = expr.ReplaceTokens(tokens, (tok, tok2) => d); Assert.Equal("d + d + d ", replaced.ToFullString()); } [Fact] public void TestReplaceSingleTokenWithMultipleTokens() { var cu = SyntaxFactory.ParseCompilationUnit("private class C { }"); var privateToken = ((ClassDeclarationSyntax)cu.Members[0]).Modifiers[0]; var publicToken = SyntaxFactory.ParseToken("public "); var partialToken = SyntaxFactory.ParseToken("partial "); var cu1 = cu.ReplaceToken(privateToken, publicToken); Assert.Equal("public class C { }", cu1.ToFullString()); var cu2 = cu.ReplaceToken(privateToken, new[] { publicToken, partialToken }); Assert.Equal("public partial class C { }", cu2.ToFullString()); var cu3 = cu.ReplaceToken(privateToken, new SyntaxToken[] { }); Assert.Equal("class C { }", cu3.ToFullString()); } [Fact] public void TestReplaceNonListTokenWithMultipleTokensFails() { var cu = SyntaxFactory.ParseCompilationUnit("private class C { }"); var identifierC = cu.DescendantTokens().First(t => t.Text == "C"); var identifierA = SyntaxFactory.ParseToken("A"); var identifierB = SyntaxFactory.ParseToken("B"); // you cannot replace a token that is a single token member with multiple tokens Assert.Throws<InvalidOperationException>(() => cu.ReplaceToken(identifierC, new[] { identifierA, identifierB })); // you cannot replace a token that is a single token member with an empty list of tokens Assert.Throws<InvalidOperationException>(() => cu.ReplaceToken(identifierC, new SyntaxToken[] { })); } [Fact] public void TestInsertTokens() { var cu = SyntaxFactory.ParseCompilationUnit("public class C { }"); var publicToken = ((ClassDeclarationSyntax)cu.Members[0]).Modifiers[0]; var partialToken = SyntaxFactory.ParseToken("partial "); var staticToken = SyntaxFactory.ParseToken("static "); var cu1 = cu.InsertTokensBefore(publicToken, new[] { staticToken }); Assert.Equal("static public class C { }", cu1.ToFullString()); var cu2 = cu.InsertTokensAfter(publicToken, new[] { staticToken }); Assert.Equal("public static class C { }", cu2.ToFullString()); } [Fact] public void TestInsertTokensRelativeToNonListToken() { var cu = SyntaxFactory.ParseCompilationUnit("public class C { }"); var identifierC = cu.DescendantTokens().First(t => t.Text == "C"); var identifierA = SyntaxFactory.ParseToken("A"); var identifierB = SyntaxFactory.ParseToken("B"); // you cannot insert a token before/after a token that is not part of a list of tokens Assert.Throws<InvalidOperationException>(() => cu.InsertTokensBefore(identifierC, new[] { identifierA, identifierB })); // you cannot insert a token before/after a token that is not part of a list of tokens Assert.Throws<InvalidOperationException>(() => cu.InsertTokensAfter(identifierC, new[] { identifierA, identifierB })); } [Fact] public void ReplaceMissingToken() { var text = "return x"; var expr = SyntaxFactory.ParseStatement(text); var token = expr.DescendantTokens().First(t => t.IsMissing); var expr2 = expr.ReplaceToken(token, SyntaxFactory.Token(token.Kind())); var text2 = expr2.ToFullString(); Assert.Equal("return x;", text2); } [Fact] public void ReplaceEndOfCommentToken() { var text = "/// Goo\r\n return x;"; var expr = SyntaxFactory.ParseStatement(text); var tokens = expr.DescendantTokens(descendIntoTrivia: true).ToList(); var token = tokens.First(t => t.Kind() == SyntaxKind.EndOfDocumentationCommentToken); var expr2 = expr.ReplaceToken(token, SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.Whitespace("garbage")), token.Kind(), default(SyntaxTriviaList))); var text2 = expr2.ToFullString(); Assert.Equal("/// Goo\r\ngarbage return x;", text2); } [Fact] public void ReplaceEndOfFileToken() { var text = ""; var cu = SyntaxFactory.ParseCompilationUnit(text); var token = cu.DescendantTokens().Single(t => t.Kind() == SyntaxKind.EndOfFileToken); var cu2 = cu.ReplaceToken(token, SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.Whitespace(" ")), token.Kind(), default(SyntaxTriviaList))); var text2 = cu2.ToFullString(); Assert.Equal(" ", text2); } [Fact] public void TestReplaceTriviaDeep() { var expr = SyntaxFactory.ParseExpression("#if true\r\na + \r\n#endif\r\n + b"); // get whitespace trivia inside structured directive trivia var deepTrivia = expr.GetDirectives().SelectMany(d => d.DescendantTrivia().Where(tr => tr.Kind() == SyntaxKind.WhitespaceTrivia)).ToList(); // replace deep trivia with double-whitespace trivia var twoSpace = SyntaxFactory.Whitespace(" "); var expr2 = expr.ReplaceTrivia(deepTrivia, (tr, tr2) => twoSpace); Assert.Equal("#if true\r\na + \r\n#endif\r\n + b", expr2.ToFullString()); } [Fact] public void TestReplaceSingleTriviaInNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var trivia = expr.DescendantTokens().First(t => t.Text == "a").TrailingTrivia[0]; var twoSpaces = SyntaxFactory.Whitespace(" "); var expr2 = expr.ReplaceTrivia(trivia, twoSpaces); Assert.Equal("a + b", expr2.ToFullString()); } [Fact] public void TestReplaceMultipleTriviaInNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var twoSpaces = SyntaxFactory.Whitespace(" "); var trivia = expr.DescendantTrivia().Where(tr => tr.IsKind(SyntaxKind.WhitespaceTrivia)).ToList(); var replaced = expr.ReplaceTrivia(trivia, (tr, tr2) => twoSpaces); Assert.Equal("a + b", replaced.ToFullString()); } [Fact] public void TestReplaceSingleTriviaWithMultipleTriviaInNode() { var ex = SyntaxFactory.ParseExpression("/* c */ identifier"); var leadingTrivia = ex.GetLeadingTrivia(); Assert.Equal(2, leadingTrivia.Count); var comment1 = leadingTrivia[0]; Assert.Equal(SyntaxKind.MultiLineCommentTrivia, comment1.Kind()); var newComment1 = SyntaxFactory.ParseLeadingTrivia("/* a */")[0]; var newComment2 = SyntaxFactory.ParseLeadingTrivia("/* b */")[0]; var ex1 = ex.ReplaceTrivia(comment1, newComment1); Assert.Equal("/* a */ identifier", ex1.ToFullString()); var ex2 = ex.ReplaceTrivia(comment1, new[] { newComment1, newComment2 }); Assert.Equal("/* a *//* b */ identifier", ex2.ToFullString()); var ex3 = ex.ReplaceTrivia(comment1, new SyntaxTrivia[] { }); Assert.Equal(" identifier", ex3.ToFullString()); } [Fact] public void TestInsertTriviaInNode() { var ex = SyntaxFactory.ParseExpression("/* c */ identifier"); var leadingTrivia = ex.GetLeadingTrivia(); Assert.Equal(2, leadingTrivia.Count); var comment1 = leadingTrivia[0]; Assert.Equal(SyntaxKind.MultiLineCommentTrivia, comment1.Kind()); var newComment1 = SyntaxFactory.ParseLeadingTrivia("/* a */")[0]; var newComment2 = SyntaxFactory.ParseLeadingTrivia("/* b */")[0]; var ex1 = ex.InsertTriviaBefore(comment1, new[] { newComment1, newComment2 }); Assert.Equal("/* a *//* b *//* c */ identifier", ex1.ToFullString()); var ex2 = ex.InsertTriviaAfter(comment1, new[] { newComment1, newComment2 }); Assert.Equal("/* c *//* a *//* b */ identifier", ex2.ToFullString()); } [Fact] public void TestReplaceSingleTriviaInToken() { var id = SyntaxFactory.ParseToken("a "); var trivia = id.TrailingTrivia[0]; var twoSpace = SyntaxFactory.Whitespace(" "); var id2 = id.ReplaceTrivia(trivia, twoSpace); Assert.Equal("a ", id2.ToFullString()); } [Fact] public void TestReplaceMultipleTriviaInToken() { var id = SyntaxFactory.ParseToken("a // goo\r\n"); // replace each trivia with a single space var id2 = id.ReplaceTrivia(id.GetAllTrivia(), (tr, tr2) => SyntaxFactory.Space); // should be 3 spaces (one for original space, comment and end-of-line) Assert.Equal("a ", id2.ToFullString()); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(a , /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_2() { var expr = SyntaxFactory.ParseExpression(@"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_3() { var expr = SyntaxFactory.ParseExpression(@"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_4() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(/*arg1:*/ a, /*arg2:*/ b, /*arg3:*/ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(/*arg1:*/ a, /*arg2:*/ /*arg3:*/ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_5() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(// comment about a a, // some comment about b b, // some comment about c c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(// comment about a a, // some comment about b // some comment about c c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia() { var expr = SyntaxFactory.ParseExpression("m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal("m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_2() { var expr = SyntaxFactory.ParseExpression( @"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_3() { var expr = SyntaxFactory.ParseExpression( @"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_4() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(/*arg1:*/ a, /*arg2:*/ b, /*arg3:*/ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(/*arg1:*/ a, /*arg3:*/ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_5() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(// comment about a a, // some comment about b b, // some comment about c c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(// comment about a a, // some comment about c c)", text); } [Fact] public void TestRemoveOnlyNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(/* before */ a /* after */)"); var n = expr.DescendantTokens().Where(t => t.Text == "a").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(n); var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(/* before */ /* after */)", text); } [Fact] public void TestRemoveFirstNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(/* before */ a /* after */, b, c)"); var n = expr.DescendantTokens().Where(t => t.Text == "a").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(n); var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(/* before */ /* after */ b, c)", text); } [Fact] public void TestRemoveLastNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(a, b, /* before */ c /* after */)"); var n = expr.DescendantTokens().Where(t => t.Text == "c").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(n); var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(a, b /* before */ /* after */)", text); } [Fact] public void TestRemoveNode_KeepNoTrivia() { var expr = SyntaxFactory.ParseStatement("{ a; b; /* trivia */ c }"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<StatementSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal("{ a; c }", text); } [Fact] public void TestRemoveNode_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseStatement("{ a; b; /* trivia */ c }"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<StatementSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("{ a; /* trivia */ c }", text); } [Fact] public void TestRemoveLastNode_KeepExteriorTrivia() { // this tests removing the last node in a non-terminal such that there is no token to the right of the removed // node to attach the kept trivia too. The trivia must be attached to the previous token. var cu = SyntaxFactory.ParseCompilationUnit("class C { void M() { } /* trivia */ }"); var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); // remove the body block from the method syntax (since it can be set to null) var m2 = m.RemoveNode(m.Body, SyntaxRemoveOptions.KeepExteriorTrivia); var text = m2.ToFullString(); Assert.Equal("void M() /* trivia */ ", text); } [Fact] public void TestRemove_KeepExteriorTrivia_KeepUnbalancedDirectives() { var cu = SyntaxFactory.ParseCompilationUnit(@" class C { // before void M() { #region Fred } // after #endregion }"); var expectedText = @" class C { // before #region Fred // after #endregion }"; var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepExteriorTrivia | SyntaxRemoveOptions.KeepUnbalancedDirectives); var text = cu2.ToFullString(); Assert.Equal(expectedText, text); } [Fact] public void TestRemove_KeepUnbalancedDirectives() { var inputText = @" class C { // before #region Fred // more before void M() { } // after #endregion }"; var expectedText = @" class C { #region Fred #endregion }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepUnbalancedDirectives); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] public void TestRemove_KeepDirectives() { var inputText = @" class C { // before #region Fred // more before void M() { #if true #endif } // after #endregion }"; var expectedText = @" class C { #region Fred #if true #endif #endregion }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepDirectives); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemove_KeepEndOfLine() { var inputText = @" class C { // before void M() { } // after }"; var expectedText = @" class C { }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveWithoutEOL_KeepEndOfLine() { var cu = SyntaxFactory.ParseCompilationUnit(@"class A { } class B { } // test"); var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal("class A { } ", text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveBadDirectiveWithoutEOL_KeepEndOfLine_KeepDirectives() { var cu = SyntaxFactory.ParseCompilationUnit(@"class A { } class B { } #endregion"); var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine | SyntaxRemoveOptions.KeepDirectives); var text = cu2.ToFullString(); Assert.Equal("class A { } \r\n#endregion", text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveDocument_KeepEndOfLine() { var cu = SyntaxFactory.ParseCompilationUnit(@" #region A class A { } #endregion"); var cu2 = cu.RemoveNode(cu, SyntaxRemoveOptions.KeepEndOfLine); Assert.Null(cu2); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameterEOLCommaTokenTrailingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken TrailingTrivia var inputText = @" class C { void M( // before a int a, // after a // before b int b /* after b*/) { } }"; var expectedText = @" class C { void M( // after a // before b int b /* after b*/) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameterEOLParameterSyntaxTrailingTrivia_KeepEndOfLine() { // EOL should be found on ParameterSyntax TrailingTrivia var inputText = @" class C { void M( // before a int a , /* after comma */ int b /* after b*/) { } }"; var expectedText = @" class C { void M( int b /* after b*/) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameterEOLCommaTokenLeadingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken LeadingTrivia and also on ParameterSyntax TrailingTrivia // but only one will be added var inputText = @" class C { void M( // before a int a // before b , /* after comma */ int b /* after b*/) { } }"; var expectedText = @" class C { void M( int b /* after b*/) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameter_KeepTrailingTrivia() { var cu = SyntaxFactory.ParseCompilationUnit(@" class C { void M( // before a int a // before b , /* after comma */ int b /* after b*/) { } }"); var expectedText = @" class C { void M( // before b /* after comma */ int b /* after b*/) { } }"; var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepTrailingTrivia); var text = cu2.ToFullString(); Assert.Equal(expectedText, text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameterEOLCommaTokenLeadingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken LeadingTrivia var inputText = @" class C { void M( // before a int a // after a , /* after comma*/ int b /* after b*/) { } }"; var expectedText = @" class C { void M( // before a int a ) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameterEOLCommaTokenTrailingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken TrailingTrivia var inputText = @" class C { void M( // before a int a, /* after comma*/ int b /* after b*/) { } }"; var expectedText = @" class C { void M( // before a int a ) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameterEOLParameterSyntaxLeadingTrivia_KeepEndOfLine() { // EOL should be found on ParameterSyntax LeadingTrivia and also on CommaToken TrailingTrivia // but only one will be added var inputText = @" class C { void M( // before a int a, /* after comma */ // before b int b /* after b*/) { } }"; var expectedText = @" class C { void M( // before a int a ) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameter_KeepLeadingTrivia() { var cu = SyntaxFactory.ParseCompilationUnit(@" class C { void M( // before a int a, /* after comma */ // before b int b /* after b*/) { } }"); var expectedText = @" class C { void M( // before a int a /* after comma */ // before b ) { } }"; var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepLeadingTrivia); var text = cu2.ToFullString(); Assert.Equal(expectedText, text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveClassWithEndRegionDirectiveWithoutEOL_KeepEndOfLine_KeepDirectives() { var inputText = @" #region A class A { } #endregion"; var expectedText = @" #region A #endregion"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine | SyntaxRemoveOptions.KeepDirectives); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] public void SeparatorsOfSeparatedSyntaxLists() { var s1 = "int goo(int a, int b, int c) {}"; var tree = SyntaxFactory.ParseSyntaxTree(s1); var root = tree.GetCompilationUnitRoot(); var method = (LocalFunctionStatementSyntax)((GlobalStatementSyntax)root.Members[0]).Statement; var list = (SeparatedSyntaxList<ParameterSyntax>)method.ParameterList.Parameters; Assert.Equal(SyntaxKind.CommaToken, ((SyntaxToken)list.GetSeparator(0)).Kind()); Assert.Equal(SyntaxKind.CommaToken, ((SyntaxToken)list.GetSeparator(1)).Kind()); foreach (var index in new int[] { -1, 2 }) { bool exceptionThrown = false; try { var unused = list.GetSeparator(2); } catch (ArgumentOutOfRangeException) { exceptionThrown = true; } Assert.True(exceptionThrown); } var internalParameterList = (InternalSyntax.ParameterListSyntax)method.ParameterList.Green; var internalParameters = internalParameterList.Parameters; Assert.Equal(2, internalParameters.SeparatorCount); Assert.Equal(SyntaxKind.CommaToken, (new SyntaxToken(internalParameters.GetSeparator(0))).Kind()); Assert.Equal(SyntaxKind.CommaToken, (new SyntaxToken(internalParameters.GetSeparator(1))).Kind()); Assert.Equal(3, internalParameters.Count); Assert.Equal("a", internalParameters[0].Identifier.ValueText); Assert.Equal("b", internalParameters[1].Identifier.ValueText); Assert.Equal("c", internalParameters[2].Identifier.ValueText); } [Fact] public void ThrowIfUnderlyingNodeIsNullForList() { var list = new SyntaxNodeOrTokenList(); Assert.Equal(0, list.Count); foreach (var index in new int[] { -1, 0, 23 }) { bool exceptionThrown = false; try { var unused = list[0]; } catch (ArgumentOutOfRangeException) { exceptionThrown = true; } Assert.True(exceptionThrown); } } [WorkItem(541188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541188")] [Fact] public void GetDiagnosticsOnMissingToken() { var syntaxTree = SyntaxFactory.ParseSyntaxTree(@"namespace n1 { c1<t"); var token = syntaxTree.FindNodeOrTokenByKind(SyntaxKind.GreaterThanToken); var diag = syntaxTree.GetDiagnostics(token).ToList(); Assert.True(token.IsMissing); Assert.Equal(1, diag.Count); } [WorkItem(541325, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541325")] [Fact] public void GetDiagnosticsOnMissingToken2() { var syntaxTree = SyntaxFactory.ParseSyntaxTree(@" class Base<T> { public virtual int Property { get { return 0; } // Note: Repro for bug 7990 requires a missing close brace token i.e. missing } below set { } public virtual void Method() { } }"); foreach (var t in syntaxTree.GetCompilationUnitRoot().DescendantTokens()) { // Bug 7990: Below for loop is an infinite loop. foreach (var e in syntaxTree.GetDiagnostics(t)) { } } // TODO: Please add meaningful checks once the above deadlock issue is fixed. } [WorkItem(541648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541648")] [Fact] public void GetDiagnosticsOnMissingToken4() { string code = @" public class MyClass { using Lib; using Lib2; public class Test1 { } }"; var syntaxTree = SyntaxFactory.ParseSyntaxTree(code); var token = syntaxTree.GetCompilationUnitRoot().FindToken(code.IndexOf("using Lib;", StringComparison.Ordinal)); var diag = syntaxTree.GetDiagnostics(token).ToList(); Assert.True(token.IsMissing); Assert.Equal(3, diag.Count); } [WorkItem(541630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541630")] [Fact] public void GetDiagnosticsOnBadReferenceDirective() { string code = @"class c1 { #r void m1() { } }"; var tree = SyntaxFactory.ParseSyntaxTree(code); var trivia = tree.GetCompilationUnitRoot().FindTrivia(code.IndexOf("#r", StringComparison.Ordinal)); // ReferenceDirective. foreach (var diag in tree.GetDiagnostics(trivia)) { Assert.NotNull(diag); // TODO: Please add any additional validations if necessary. } } [WorkItem(528626, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528626")] [Fact] public void SpanOfNodeWithMissingChildren() { string code = @"delegate = 1;"; var tree = SyntaxFactory.ParseSyntaxTree(code); var compilationUnit = tree.GetCompilationUnitRoot(); var delegateDecl = (DelegateDeclarationSyntax)compilationUnit.Members[0]; var paramList = delegateDecl.ParameterList; // For (non-EOF) tokens, IsMissing is true if and only if Width is 0. Assert.True(compilationUnit.DescendantTokens(node => true). Where(token => token.Kind() != SyntaxKind.EndOfFileToken). All(token => token.IsMissing == (token.Width == 0))); // For non-terminals, Is true if Width is 0, but the converse may not hold. Assert.True(paramList.IsMissing); Assert.NotEqual(0, paramList.Width); Assert.NotEqual(0, paramList.FullWidth); } [WorkItem(542457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542457")] [Fact] public void AddMethodModifier() { var tree = SyntaxFactory.ParseSyntaxTree(@" class Program { static void Main(string[] args) { } }"); var compilationUnit = tree.GetCompilationUnitRoot(); var @class = (ClassDeclarationSyntax)compilationUnit.Members.Single(); var method = (MethodDeclarationSyntax)@class.Members.Single(); var newModifiers = method.Modifiers.Add(SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.UnsafeKeyword, SyntaxFactory.TriviaList(SyntaxFactory.Space))); Assert.Equal(" static unsafe ", newModifiers.ToFullString()); Assert.Equal(2, newModifiers.Count); Assert.Equal(SyntaxKind.StaticKeyword, newModifiers[0].Kind()); Assert.Equal(SyntaxKind.UnsafeKeyword, newModifiers[1].Kind()); } [Fact] public void SeparatedSyntaxListValidation() { var intType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)); var commaToken = SyntaxFactory.Token(SyntaxKind.CommaToken); SyntaxFactory.SingletonSeparatedList<TypeSyntax>(intType); SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken }); SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, intType }); SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, intType, commaToken }); Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { commaToken })); Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, commaToken })); Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, intType })); } [WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")] [Fact] public void SyntaxDotParseCompilationUnitContainingOnlyWhitespace() { var node = SyntaxFactory.ParseCompilationUnit(" "); Assert.True(node.HasLeadingTrivia); Assert.Equal(1, node.GetLeadingTrivia().Count); Assert.Equal(1, node.DescendantTrivia().Count()); Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()); } [WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")] [Fact] public void SyntaxTreeDotParseCompilationUnitContainingOnlyWhitespace() { var node = SyntaxFactory.ParseSyntaxTree(" ").GetCompilationUnitRoot(); Assert.True(node.HasLeadingTrivia); Assert.Equal(1, node.GetLeadingTrivia().Count); Assert.Equal(1, node.DescendantTrivia().Count()); Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()); } [Fact] public void SyntaxNodeAndTokenToString() { var text = @"class A { }"; var root = SyntaxFactory.ParseCompilationUnit(text); var children = root.DescendantNodesAndTokens(); var nodeOrToken = children.First(); Assert.Equal("class A { }", nodeOrToken.ToString()); Assert.Equal(text, nodeOrToken.ToString()); var node = (SyntaxNode)children.First(n => n.IsNode); Assert.Equal("class A { }", node.ToString()); Assert.Equal(text, node.ToFullString()); var token = (SyntaxToken)children.First(n => n.IsToken); Assert.Equal("class", token.ToString()); Assert.Equal("class ", token.ToFullString()); var trivia = root.DescendantTrivia().First(); Assert.Equal(" ", trivia.ToString()); Assert.Equal(" ", trivia.ToFullString()); } [WorkItem(545116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545116")] [Fact] public void FindTriviaOutsideNode() { var text = @"// This is trivia class C { static void Main() { } } "; var root = SyntaxFactory.ParseCompilationUnit(text); Assert.InRange(0, root.FullSpan.Start, root.FullSpan.End); var rootTrivia = root.FindTrivia(0); Assert.Equal("// This is trivia", rootTrivia.ToString().Trim()); var method = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.NotInRange(0, method.FullSpan.Start, method.FullSpan.End); var methodTrivia = method.FindTrivia(0); Assert.Equal(default(SyntaxTrivia), methodTrivia); } [Fact] public void TestSyntaxTriviaListEquals() { var emptyWhitespace = SyntaxFactory.Whitespace(""); var emptyToken = SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken).WithTrailingTrivia(emptyWhitespace, emptyWhitespace); var emptyTokenList = SyntaxFactory.TokenList(emptyToken, emptyToken); // elements should be not equal Assert.NotEqual(emptyTokenList[0].TrailingTrivia[0], emptyTokenList[1].TrailingTrivia[0]); // lists should be not equal Assert.NotEqual(emptyTokenList[0].TrailingTrivia, emptyTokenList[1].TrailingTrivia); // Two lists with the same parent node, but different indexes should NOT be the same. var emptyTriviaList = SyntaxFactory.TriviaList(emptyWhitespace, emptyWhitespace); emptyToken = emptyToken.WithLeadingTrivia(emptyTriviaList).WithTrailingTrivia(emptyTriviaList); // elements should be not equal Assert.NotEqual(emptyToken.LeadingTrivia[0], emptyToken.TrailingTrivia[0]); // lists should be not equal Assert.NotEqual(emptyToken.LeadingTrivia, emptyToken.TrailingTrivia); } [Fact] public void Test_SyntaxTree_ParseTextInvalidArguments() { // Invalid arguments - Validate Exceptions Assert.Throws<System.ArgumentNullException>(delegate { SourceText st = null; var treeFromSource_invalid2 = SyntaxFactory.ParseSyntaxTree(st); }); } [Fact] public void TestSyntaxTree_Changes() { string SourceText = @"using System; using System.Linq; using System.Collections; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText); var root = (CompilationUnitSyntax)tree.GetRoot(); // Get the Imports Clauses var FirstUsingClause = root.Usings[0]; var SecondUsingClause = root.Usings[1]; var ThirdUsingClause = root.Usings[2]; var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChanges(SecondUsingClause.SyntaxTree); Assert.Equal(0, ChangesForDifferentTrees.Count); // Do a transform to Replace and Existing Tree NameSyntax name = SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Collections.Generic")); UsingDirectiveSyntax newUsingClause = ThirdUsingClause.WithName(name); // Replace Node with a different Imports Clause root = root.ReplaceNode(ThirdUsingClause, newUsingClause); var ChangesFromTransform = ThirdUsingClause.SyntaxTree.GetChanges(newUsingClause.SyntaxTree); Assert.Equal(2, ChangesFromTransform.Count); // Using the Common Syntax Changes Method SyntaxTree x = ThirdUsingClause.SyntaxTree; SyntaxTree y = newUsingClause.SyntaxTree; var changes2UsingCommonSyntax = x.GetChanges(y); Assert.Equal(2, changes2UsingCommonSyntax.Count); // Verify Changes from CS Specific SyntaxTree and Common SyntaxTree are the same Assert.Equal(ChangesFromTransform, changes2UsingCommonSyntax); } [Fact, WorkItem(658329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658329")] public void TestSyntaxTree_GetChangesInvalid() { string SourceText = @"using System; using System.Linq; using System.Collections; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText); var root = (CompilationUnitSyntax)tree.GetRoot(); // Get the Imports Clauses var FirstUsingClause = root.Usings[0]; var SecondUsingClause = root.Usings[1]; var ThirdUsingClause = root.Usings[2]; var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChanges(SecondUsingClause.SyntaxTree); Assert.Equal(0, ChangesForDifferentTrees.Count); // With null tree SyntaxTree BlankTree = null; Assert.Throws<ArgumentNullException>(() => FirstUsingClause.SyntaxTree.GetChanges(BlankTree)); } [Fact, WorkItem(658329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658329")] public void TestSyntaxTree_GetChangedSpansInvalid() { string SourceText = @"using System; using System.Linq; using System.Collections; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText); var root = (CompilationUnitSyntax)tree.GetRoot(); // Get the Imports Clauses var FirstUsingClause = root.Usings[0]; var SecondUsingClause = root.Usings[1]; var ThirdUsingClause = root.Usings[2]; var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChangedSpans(SecondUsingClause.SyntaxTree); Assert.Equal(0, ChangesForDifferentTrees.Count); // With null tree SyntaxTree BlankTree = null; Assert.Throws<ArgumentNullException>(() => FirstUsingClause.SyntaxTree.GetChangedSpans(BlankTree)); } [Fact] public void TestTriviaExists() { // token constructed using factory w/o specifying trivia (should have zero-width elastic trivia) var idToken = SyntaxFactory.Identifier("goo"); Assert.True(idToken.HasLeadingTrivia); Assert.Equal(1, idToken.LeadingTrivia.Count); Assert.Equal(0, idToken.LeadingTrivia.Span.Length); // zero-width elastic trivia Assert.True(idToken.HasTrailingTrivia); Assert.Equal(1, idToken.TrailingTrivia.Count); Assert.Equal(0, idToken.TrailingTrivia.Span.Length); // zero-width elastic trivia // token constructed by parser w/o trivia idToken = SyntaxFactory.ParseToken("x"); Assert.False(idToken.HasLeadingTrivia); Assert.Equal(0, idToken.LeadingTrivia.Count); Assert.False(idToken.HasTrailingTrivia); Assert.Equal(0, idToken.TrailingTrivia.Count); // token constructed by parser with trivia idToken = SyntaxFactory.ParseToken(" x "); Assert.True(idToken.HasLeadingTrivia); Assert.Equal(1, idToken.LeadingTrivia.Count); Assert.Equal(1, idToken.LeadingTrivia.Span.Length); Assert.True(idToken.HasTrailingTrivia); Assert.Equal(1, idToken.TrailingTrivia.Count); Assert.Equal(2, idToken.TrailingTrivia.Span.Length); // node constructed using factory w/o specifying trivia SyntaxNode namedNode = SyntaxFactory.IdentifierName("goo"); Assert.True(namedNode.HasLeadingTrivia); Assert.Equal(1, namedNode.GetLeadingTrivia().Count); Assert.Equal(0, namedNode.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(namedNode.HasTrailingTrivia); Assert.Equal(1, namedNode.GetTrailingTrivia().Count); Assert.Equal(0, namedNode.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // node constructed by parse w/o trivia namedNode = SyntaxFactory.ParseExpression("goo"); Assert.False(namedNode.HasLeadingTrivia); Assert.Equal(0, namedNode.GetLeadingTrivia().Count); Assert.False(namedNode.HasTrailingTrivia); Assert.Equal(0, namedNode.GetTrailingTrivia().Count); // node constructed by parse with trivia namedNode = SyntaxFactory.ParseExpression(" goo "); Assert.True(namedNode.HasLeadingTrivia); Assert.Equal(1, namedNode.GetLeadingTrivia().Count); Assert.Equal(1, namedNode.GetLeadingTrivia().Span.Length); Assert.True(namedNode.HasTrailingTrivia); Assert.Equal(1, namedNode.GetTrailingTrivia().Count); Assert.Equal(2, namedNode.GetTrailingTrivia().Span.Length); // nodeOrToken with token constructed from factory w/o specifying trivia SyntaxNodeOrToken nodeOrToken = SyntaxFactory.Identifier("goo"); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // nodeOrToken with node constructed from factory w/o specifying trivia nodeOrToken = SyntaxFactory.IdentifierName("goo"); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // nodeOrToken with token parsed from factory w/o trivia nodeOrToken = SyntaxFactory.ParseToken("goo"); Assert.False(nodeOrToken.HasLeadingTrivia); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Count); Assert.False(nodeOrToken.HasTrailingTrivia); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Count); // nodeOrToken with node parsed from factory w/o trivia nodeOrToken = SyntaxFactory.ParseExpression("goo"); Assert.False(nodeOrToken.HasLeadingTrivia); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Count); Assert.False(nodeOrToken.HasTrailingTrivia); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Count); // nodeOrToken with token parsed from factory with trivia nodeOrToken = SyntaxFactory.ParseToken(" goo "); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(2, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // nodeOrToken with node parsed from factory with trivia nodeOrToken = SyntaxFactory.ParseExpression(" goo "); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(2, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia } [WorkItem(6536, "https://github.com/dotnet/roslyn/issues/6536")] [Fact] public void TestFindTrivia_NoStackOverflowOnLargeExpression() { StringBuilder code = new StringBuilder(); code.Append( @"class Goo { void Bar() { string test = "); for (var i = 0; i < 3000; i++) { code.Append(@"""asdf"" + "); } code.Append(@"""last""; } }"); var tree = SyntaxFactory.ParseSyntaxTree(code.ToString()); var position = 4000; var trivia = tree.GetCompilationUnitRoot().FindTrivia(position); // no stack overflow } [Fact, WorkItem(8625, "https://github.com/dotnet/roslyn/issues/8625")] public void SyntaxNodeContains() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var a = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var firstParens = e.FirstAncestorOrSelf<ExpressionSyntax>(n => n.Kind() == SyntaxKind.ParenthesizedExpression); Assert.False(firstParens.Contains(a)); // fixing #8625 allows this to return quicker Assert.True(firstParens.Contains(e)); } private static void TestWithWindowsAndUnixEndOfLines(string inputText, string expectedText, Action<CompilationUnitSyntax, string> action) { inputText = inputText.NormalizeLineEndings(); expectedText = expectedText.NormalizeLineEndings(); var tests = new Dictionary<string, string> { {inputText, expectedText}, // Test CRLF (Windows) {inputText.Replace("\r", ""), expectedText.Replace("\r", "")}, // Test LF (Unix) }; foreach (var test in tests) { action(SyntaxFactory.ParseCompilationUnit(test.Key), test.Value); } } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Lsif/Generator/Graph/Capabilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Newtonsoft.Json; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph { /// <summary> /// Represents a single Capabilities vertex for serialization. See https://github.com/microsoft/lsif-node/blob/main/protocol/src/protocol.ts#L973 for further details. /// </summary> internal sealed class Capabilities : Vertex { [JsonProperty("hoverProvider")] public bool HoverProvider { get; } [JsonProperty("declarationProvider")] public bool DeclarationProvider { get; } [JsonProperty("definitionProvider")] public bool DefinitionProvider { get; } [JsonProperty("referencesProvider")] public bool ReferencesProvider { get; } [JsonProperty("typeDefinitionProvider")] public bool TypeDefinitionProvider { get; } [JsonProperty("documentSymbolProvider")] public bool DocumentSymbolProvider { get; } [JsonProperty("foldingRangeProvider")] public bool FoldingRangeProvider { get; } [JsonProperty("diagnosticProvider")] public bool DiagnosticProvider { get; } public Capabilities( IdFactory idFactory, bool hoverProvider, bool declarationProvider, bool definitionProvider, bool referencesProvider, bool typeDefinitionProvider, bool documentSymbolProvider, bool foldingRangeProvider, bool diagnosticProvider) : base(label: "capabilities", idFactory) { HoverProvider = hoverProvider; DeclarationProvider = declarationProvider; DefinitionProvider = definitionProvider; ReferencesProvider = referencesProvider; TypeDefinitionProvider = typeDefinitionProvider; DocumentSymbolProvider = documentSymbolProvider; FoldingRangeProvider = foldingRangeProvider; DiagnosticProvider = diagnosticProvider; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Newtonsoft.Json; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph { /// <summary> /// Represents a single Capabilities vertex for serialization. See https://github.com/microsoft/lsif-node/blob/main/protocol/src/protocol.ts#L973 for further details. /// </summary> internal sealed class Capabilities : Vertex { [JsonProperty("hoverProvider")] public bool HoverProvider { get; } [JsonProperty("declarationProvider")] public bool DeclarationProvider { get; } [JsonProperty("definitionProvider")] public bool DefinitionProvider { get; } [JsonProperty("referencesProvider")] public bool ReferencesProvider { get; } [JsonProperty("typeDefinitionProvider")] public bool TypeDefinitionProvider { get; } [JsonProperty("documentSymbolProvider")] public bool DocumentSymbolProvider { get; } [JsonProperty("foldingRangeProvider")] public bool FoldingRangeProvider { get; } [JsonProperty("diagnosticProvider")] public bool DiagnosticProvider { get; } public Capabilities( IdFactory idFactory, bool hoverProvider, bool declarationProvider, bool definitionProvider, bool referencesProvider, bool typeDefinitionProvider, bool documentSymbolProvider, bool foldingRangeProvider, bool diagnosticProvider) : base(label: "capabilities", idFactory) { HoverProvider = hoverProvider; DeclarationProvider = declarationProvider; DefinitionProvider = definitionProvider; ReferencesProvider = referencesProvider; TypeDefinitionProvider = typeDefinitionProvider; DocumentSymbolProvider = documentSymbolProvider; FoldingRangeProvider = foldingRangeProvider; DiagnosticProvider = diagnosticProvider; } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/DocumentKey.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.PersistentStorage { /// <summary> /// Handle that can be used with <see cref="IChecksummedPersistentStorage"/> to read data for a /// <see cref="Document"/> without needing to have the entire <see cref="Document"/> snapshot available. /// This is useful for cases where acquiring an entire snapshot might be expensive (for example, during /// solution load), but querying the data is still desired. /// </summary> [DataContract] internal readonly struct DocumentKey : IEqualityComparer<DocumentKey> { [DataMember(Order = 0)] public readonly ProjectKey Project; [DataMember(Order = 1)] public readonly DocumentId Id; [DataMember(Order = 2)] public readonly string? FilePath; [DataMember(Order = 3)] public readonly string Name; public DocumentKey(ProjectKey project, DocumentId id, string? filePath, string name) { Project = project; Id = id; FilePath = filePath; Name = name; } public static DocumentKey ToDocumentKey(Document document) => ToDocumentKey(ProjectKey.ToProjectKey(document.Project), document.State); public static DocumentKey ToDocumentKey(ProjectKey projectKey, TextDocumentState state) => new(projectKey, state.Id, state.FilePath, state.Name); public bool Equals(DocumentKey x, DocumentKey y) => x.Id == y.Id; public int GetHashCode(DocumentKey obj) => obj.Id.GetHashCode(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.PersistentStorage { /// <summary> /// Handle that can be used with <see cref="IChecksummedPersistentStorage"/> to read data for a /// <see cref="Document"/> without needing to have the entire <see cref="Document"/> snapshot available. /// This is useful for cases where acquiring an entire snapshot might be expensive (for example, during /// solution load), but querying the data is still desired. /// </summary> [DataContract] internal readonly struct DocumentKey : IEqualityComparer<DocumentKey> { [DataMember(Order = 0)] public readonly ProjectKey Project; [DataMember(Order = 1)] public readonly DocumentId Id; [DataMember(Order = 2)] public readonly string? FilePath; [DataMember(Order = 3)] public readonly string Name; public DocumentKey(ProjectKey project, DocumentId id, string? filePath, string name) { Project = project; Id = id; FilePath = filePath; Name = name; } public static DocumentKey ToDocumentKey(Document document) => ToDocumentKey(ProjectKey.ToProjectKey(document.Project), document.State); public static DocumentKey ToDocumentKey(ProjectKey projectKey, TextDocumentState state) => new(projectKey, state.Id, state.FilePath, state.Name); public bool Equals(DocumentKey x, DocumentKey y) => x.Id == y.Id; public int GetHashCode(DocumentKey obj) => obj.Id.GetHashCode(); } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/CSharp/Impl/CodeModel/ParameterFlags.cs
// 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. #nullable disable using System; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { [Flags] internal enum ParameterFlags { Ref = 1 << 0, Out = 1 << 1, Params = 1 << 2 } }
// 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. #nullable disable using System; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { [Flags] internal enum ParameterFlags { Ref = 1 << 0, Out = 1 << 1, Params = 1 << 2 } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Symbol/Symbols/Source/MethodTests.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MethodTests : CSharpTestBase { [Fact] public void Simple1() { var text = @" class A { void M(int x) {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.GetMembers("M").Single() as MethodSymbol; Assert.NotNull(m); Assert.True(m.ReturnsVoid); var x = m.Parameters[0]; Assert.Equal("x", x.Name); Assert.Equal(SymbolKind.NamedType, x.Type.Kind); Assert.Equal("Int32", x.Type.Name); // fully qualified to work around a metadata reader bug Assert.Equal(SymbolKind.Parameter, x.Kind); Assert.Equal(Accessibility.Private, m.DeclaredAccessibility); } [Fact] public void NoParameterlessCtorForStruct() { var text = "struct A { A() {} }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,12): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // struct A { A() {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "A").WithArguments("parameterless struct constructors", "10.0").WithLocation(1, 12), // (1,12): error CS8938: The parameterless struct constructor must be 'public'. // struct A { A() {} } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "A").WithLocation(1, 12)); } [WorkItem(537194, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537194")] [Fact] public void DefaultCtor1() { Action<string, string, int, Accessibility?> check = (source, className, ctorCount, accessibility) => { var comp = CreateCompilation(source); var global = comp.GlobalNamespace; var a = global.GetTypeMembers(className, 0).Single(); var ctors = a.InstanceConstructors; // Note, this only returns *instance* constructors. Assert.Equal(ctorCount, ctors.Length); foreach (var ct in ctors) { Assert.Equal( ct.IsStatic ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName, ct.Name ); if (accessibility != null) Assert.Equal(accessibility, ct.DeclaredAccessibility); } }; Accessibility? doNotCheckAccessibility = null; // A class without any defined constructors should generator a public constructor. check(@"internal class A { }", "A", 1, Accessibility.Public); // An abstract class without any defined constructors should generator a protected constructor. check(@"abstract internal class A { }", "A", 1, Accessibility.Protected); // A static class should not generate a default constructor check(@"static internal class A { }", "A", 0, doNotCheckAccessibility); // A class with a defined instance constructor should not generate a default constructor. check(@"internal class A { A(int x) {} }", "A", 1, doNotCheckAccessibility); // A class with only a static constructor defined should still generate a default instance constructor. check(@"internal class A { static A(int x) {} }", "A", 1, doNotCheckAccessibility); } [WorkItem(537345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537345")] [Fact] public void Ctor1() { var text = @" class A { A(int x) {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.InstanceConstructors.Single(); Assert.NotNull(m); Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m.Name); Assert.True(m.ReturnsVoid); Assert.Equal(MethodKind.Constructor, m.MethodKind); var x = m.Parameters[0]; Assert.Equal("x", x.Name); Assert.Equal(SymbolKind.NamedType, x.Type.Kind); Assert.Equal("Int32", x.Type.Name); // fully qualified to work around a metadata reader bug Assert.Equal(SymbolKind.Parameter, x.Kind); Assert.Equal(Accessibility.Private, m.DeclaredAccessibility); } [Fact] public void Simple2() { var text = @" class A { void M<T>(int x) {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.GetMembers("M").Single() as MethodSymbol; Assert.NotNull(m); Assert.True(m.ReturnsVoid); Assert.Equal(MethodKind.Ordinary, m.MethodKind); var x = m.Parameters[0]; Assert.Equal("x", x.Name); Assert.Equal(SymbolKind.NamedType, x.Type.Kind); Assert.Equal("Int32", x.Type.Name); // fully qualified to work around a metadata reader bug Assert.Equal(SymbolKind.Parameter, x.Kind); Assert.Equal(Accessibility.Private, m.DeclaredAccessibility); } [Fact] public void Access1() { var text = @" class A { void M1() {} } interface B { void M2() {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m1 = a.GetMembers("M1").Single() as MethodSymbol; var b = global.GetTypeMembers("B", 0).Single(); var m2 = b.GetMembers("M2").Single() as MethodSymbol; Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility); } [Fact] public void GenericParameter() { var text = @" public class MyList<T> { public void Add(T element) { } } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var mylist = global.GetTypeMembers("MyList", 1).Single(); var t1 = mylist.TypeParameters[0]; var add = mylist.GetMembers("Add").Single() as MethodSymbol; var element = add.Parameters[0]; var t2 = element.Type; Assert.Equal(t1, t2); } [Fact] public void PartialLocation() { var text = @" public partial class A { partial void M(); } public partial class A { partial void M() {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.GetMembers("M"); Assert.Equal(1, m.Length); Assert.Equal(1, m.First().Locations.Length); } [Fact] public void PartialExtractSyntaxLocation_DeclBeforeDef() { var text = @"public partial class A { partial void M(); } public partial class A { partial void M() {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = (MethodSymbol)a.GetMembers("M").Single(); Assert.True(m.IsPartialDefinition()); var returnSyntax = m.ExtractReturnTypeSyntax(); var tree = comp.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).First(); var otherSymbol = m.PartialImplementationPart; Assert.True(otherSymbol.IsPartialImplementation()); Assert.Equal(node, returnSyntax); Assert.Equal(node, otherSymbol.ExtractReturnTypeSyntax()); } [Fact] public void PartialExtractSyntaxLocation_DefBeforeDecl() { var text = @"public partial class A { partial void M() {} } public partial class A { partial void M(); } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = (MethodSymbol)a.GetMembers("M").Single(); Assert.True(m.IsPartialDefinition()); var returnSyntax = m.ExtractReturnTypeSyntax(); var tree = comp.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).Last(); var otherSymbol = m.PartialImplementationPart; Assert.True(otherSymbol.IsPartialImplementation()); Assert.Equal(node, returnSyntax); Assert.Equal(node, otherSymbol.ExtractReturnTypeSyntax()); } [Fact] public void PartialExtractSyntaxLocation_OnlyDef() { var text = @"public partial class A { partial void M() {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = (MethodSymbol)a.GetMembers("M").Single(); Assert.True(m.IsPartialImplementation()); var returnSyntax = m.ExtractReturnTypeSyntax(); var tree = comp.SyntaxTrees.Single().GetRoot(); var node = tree.DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).Single(); Assert.Equal(node, returnSyntax); } [Fact] public void PartialExtractSyntaxLocation_OnlyDecl() { var text = @"public partial class A { partial void M(); } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = (MethodSymbol)a.GetMembers("M").Single(); Assert.True(m.IsPartialDefinition()); var returnSyntax = m.ExtractReturnTypeSyntax(); var tree = comp.SyntaxTrees.Single().GetRoot(); var node = tree.DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).Single(); Assert.Equal(node, returnSyntax); } [Fact] public void FullName() { var text = @" public class A { public string M(int x); } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.GetMembers("M").Single() as MethodSymbol; Assert.Equal("System.String A.M(System.Int32 x)", m.ToTestDisplayString()); } [Fact] public void TypeParameterScope() { var text = @" public interface A { T M<T>(T t); } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.GetMembers("M").Single() as MethodSymbol; var t = m.TypeParameters[0]; Assert.Equal(t, m.Parameters[0].Type); Assert.Equal(t, m.ReturnType); } [WorkItem(931142, "DevDiv/Personal")] [Fact] public void RefOutParameterType() { var text = @"public class A { void M(ref A refp, out long outp) { } } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.GetMembers("M").Single() as MethodSymbol; var p1 = m.Parameters[0]; var p2 = m.Parameters[1]; Assert.Equal(RefKind.Ref, p1.RefKind); Assert.Equal(RefKind.Out, p2.RefKind); var refP = p1.Type; Assert.Equal(TypeKind.Class, refP.TypeKind); Assert.True(refP.IsReferenceType); Assert.False(refP.IsValueType); Assert.Equal("Object", refP.BaseType().Name); Assert.Equal(2, refP.GetMembers().Length); // M + generated constructor. Assert.Equal(1, refP.GetMembers("M").Length); var outP = p2.Type; Assert.Equal(TypeKind.Struct, outP.TypeKind); Assert.False(outP.IsReferenceType); Assert.True(outP.IsValueType); Assert.False(outP.IsStatic); Assert.False(outP.IsAbstract); Assert.True(outP.IsSealed); Assert.Equal(Accessibility.Public, outP.DeclaredAccessibility); Assert.Equal(5, outP.Interfaces().Length); Assert.Equal(0, outP.GetTypeMembers().Length); // Enumerable.Empty<NamedTypeSymbol>() Assert.Equal(0, outP.GetTypeMembers(String.Empty).Length); Assert.Equal(0, outP.GetTypeMembers(String.Empty, 0).Length); } [Fact] public void RefReturn() { var text = @"public class A { ref int M(ref int i) { return ref i; } } "; var comp = CreateCompilationWithMscorlib45(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.GetMembers("M").Single() as MethodSymbol; Assert.Equal(RefKind.Ref, m.RefKind); Assert.Equal(TypeKind.Struct, m.ReturnType.TypeKind); Assert.False(m.ReturnType.IsReferenceType); Assert.True(m.ReturnType.IsValueType); var p1 = m.Parameters[0]; Assert.Equal(RefKind.Ref, p1.RefKind); Assert.Equal("ref System.Int32 A.M(ref System.Int32 i)", m.ToTestDisplayString()); } [Fact] public void BothKindsOfCtors() { var text = @"public class Test { public Test() {} public static Test() {} }"; var comp = CreateCompilation(text); var classTest = comp.GlobalNamespace.GetTypeMembers("Test", 0).Single(); var members = classTest.GetMembers(); Assert.Equal(2, members.Length); } [WorkItem(931663, "DevDiv/Personal")] [Fact] public void RefOutArrayParameter() { var text = @"public class Test { public void MethodWithRefOutArray(ref int[] ary1, out string[] ary2) { ary2 = null; } }"; var comp = CreateCompilation(text); var classTest = comp.GlobalNamespace.GetTypeMembers("Test", 0).Single(); var method = classTest.GetMembers("MethodWithRefOutArray").Single() as MethodSymbol; Assert.Equal(classTest, method.ContainingSymbol); Assert.Equal(SymbolKind.Method, method.Kind); Assert.True(method.IsDefinition); // var paramList = (method as MethodSymbol).Parameters; var p1 = method.Parameters[0]; var p2 = method.Parameters[1]; Assert.Equal(RefKind.Ref, p1.RefKind); Assert.Equal(RefKind.Out, p2.RefKind); } [Theory, MemberData(nameof(FileScopedOrBracedNamespace))] public void InterfaceImplementsCrossTrees(string ob, string cb) { var text1 = @"using System; using System.Collections.Generic; namespace NS " + ob + @" public class Abc {} public interface IGoo<T> { void M(ref T t); } public interface I1 { void M(ref string p); int M1(short p1, params object[] ary); } public interface I2 : I1 { void M21(); Abc M22(ref Abc p); } " + cb; var text2 = @"using System; using System.Collections.Generic; namespace NS.NS1 " + ob + @" public class Impl : I2, IGoo<string>, I1 { void IGoo<string>.M(ref string p) { } void I1.M(ref string p) { } public int M1(short p1, params object[] ary) { return p1; } public void M21() {} public Abc M22(ref Abc p) { return p; } } struct S<T>: IGoo<T> { void IGoo<T>.M(ref T t) {} } " + cb; var comp = CreateCompilation(new[] { text1, text2 }); Assert.Equal(0, comp.GetDeclarationDiagnostics().Count()); var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var ns1 = ns.GetMembers("NS1").Single() as NamespaceSymbol; var classImpl = ns1.GetTypeMembers("Impl", 0).Single() as NamedTypeSymbol; Assert.Equal(3, classImpl.Interfaces().Length); // var itfc = classImpl.Interfaces().First() as NamedTypeSymbol; Assert.Equal(1, itfc.Interfaces().Length); itfc = itfc.Interfaces().First() as NamedTypeSymbol; Assert.Equal("I1", itfc.Name); // explicit interface member names include the explicit interface var mems = classImpl.GetMembers("M"); Assert.Equal(0, mems.Length); //var mem1 = mems.First() as MethodSymbol; // not impl // Assert.Equal(MethodKind.ExplicitInterfaceImplementation, mem1.MethodKind); // Assert.Equal(1, mem1.ExplicitInterfaceImplementation.Count()); var mem1 = classImpl.GetMembers("M22").Single() as MethodSymbol; // not impl // Assert.Equal(0, mem1.ExplicitInterfaceImplementation.Count()); var param = mem1.Parameters.First() as ParameterSymbol; Assert.Equal(RefKind.Ref, param.RefKind); Assert.Equal("ref NS.Abc p", param.ToTestDisplayString()); var structImpl = ns1.GetTypeMembers("S").Single() as NamedTypeSymbol; Assert.Equal(1, structImpl.Interfaces().Length); itfc = structImpl.Interfaces().First() as NamedTypeSymbol; Assert.Equal("NS.IGoo<T>", itfc.ToTestDisplayString()); //var mem2 = structImpl.GetMembers("M").Single() as MethodSymbol; // not impl // Assert.Equal(1, mem2.ExplicitInterfaceImplementation.Count()); } [Fact] public void AbstractVirtualMethodsCrossTrees() { var text = @" namespace MT { public interface IGoo { void M0(); } } "; var text1 = @" namespace N1 { using MT; public abstract class Abc : IGoo { public abstract void M0(); public char M1; public abstract object M2(ref object p1); public virtual void M3(ulong p1, out ulong p2) { p2 = p1; } public virtual object M4(params object[] ary) { return null; } public static void M5<T>(T t) { } public abstract ref int M6(ref int i); } } "; var text2 = @" namespace N1.N2 { public class Bbc : Abc { public override void M0() { } public override object M2(ref object p1) { M1 = 'a'; return p1; } public sealed override void M3(ulong p1, out ulong p2) { p2 = p1; } public override object M4(params object[] ary) { return null; } public static new void M5<T>(T t) { } public override ref int M6(ref int i) { return ref i; } } } "; var comp = CreateCompilationWithMscorlib45(new[] { text, text1, text2 }); Assert.Equal(0, comp.GetDiagnostics().Count()); var ns = comp.GlobalNamespace.GetMembers("N1").Single() as NamespaceSymbol; var ns1 = ns.GetMembers("N2").Single() as NamespaceSymbol; #region "Bbc" var type1 = ns1.GetTypeMembers("Bbc", 0).Single() as NamedTypeSymbol; var mems = type1.GetMembers(); Assert.Equal(7, mems.Length); // var sorted = mems.Orderby(m => m.Name).ToArray(); var sorted = (from m in mems orderby m.Name select m).ToArray(); var m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); Assert.False(m0.IsAbstract); Assert.False(m0.IsOverride); Assert.False(m0.IsSealed); Assert.False(m0.IsVirtual); var m1 = sorted[1] as MethodSymbol; Assert.Equal("M0", m1.Name); Assert.False(m1.IsAbstract); Assert.True(m1.IsOverride); Assert.False(m1.IsSealed); Assert.False(m1.IsVirtual); var m2 = sorted[2] as MethodSymbol; Assert.Equal("M2", m2.Name); Assert.False(m2.IsAbstract); Assert.True(m2.IsOverride); Assert.False(m2.IsSealed); Assert.False(m2.IsVirtual); var m3 = sorted[3] as MethodSymbol; Assert.Equal("M3", m3.Name); Assert.False(m3.IsAbstract); Assert.True(m3.IsOverride); Assert.True(m3.IsSealed); Assert.False(m3.IsVirtual); var m4 = sorted[4] as MethodSymbol; Assert.Equal("M4", m4.Name); Assert.False(m4.IsAbstract); Assert.True(m4.IsOverride); Assert.False(m4.IsSealed); Assert.False(m4.IsVirtual); var m5 = sorted[5] as MethodSymbol; Assert.Equal("M5", m5.Name); Assert.False(m5.IsAbstract); Assert.False(m5.IsOverride); Assert.False(m5.IsSealed); Assert.False(m5.IsVirtual); Assert.True(m5.IsStatic); var m6 = sorted[6] as MethodSymbol; Assert.Equal("M6", m6.Name); Assert.False(m6.IsAbstract); Assert.True(m6.IsOverride); Assert.False(m6.IsSealed); Assert.False(m6.IsVirtual); #endregion #region "Abc" var type2 = type1.BaseType(); Assert.Equal("Abc", type2.Name); mems = type2.GetMembers(); Assert.Equal(8, mems.Length); sorted = (from m in mems orderby m.Name select m).ToArray(); var mm = sorted[2] as FieldSymbol; Assert.Equal("M1", mm.Name); Assert.False(mm.IsAbstract); Assert.False(mm.IsOverride); Assert.False(mm.IsSealed); Assert.False(mm.IsVirtual); m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); Assert.Equal(Accessibility.Protected, m0.DeclaredAccessibility); m1 = sorted[1] as MethodSymbol; Assert.Equal("M0", m1.Name); Assert.True(m1.IsAbstract); Assert.False(m1.IsOverride); Assert.False(m1.IsSealed); Assert.False(m1.IsVirtual); m2 = sorted[3] as MethodSymbol; Assert.Equal("M2", m2.Name); Assert.True(m2.IsAbstract); Assert.False(m2.IsOverride); Assert.False(m2.IsSealed); Assert.False(m2.IsVirtual); m3 = sorted[4] as MethodSymbol; Assert.Equal("M3", m3.Name); Assert.False(m3.IsAbstract); Assert.False(m3.IsOverride); Assert.False(m3.IsSealed); Assert.True(m3.IsVirtual); m4 = sorted[5] as MethodSymbol; Assert.Equal("M4", m4.Name); Assert.False(m4.IsAbstract); Assert.False(m4.IsOverride); Assert.False(m4.IsSealed); Assert.True(m4.IsVirtual); m5 = sorted[6] as MethodSymbol; Assert.Equal("M5", m5.Name); Assert.False(m5.IsAbstract); Assert.False(m5.IsOverride); Assert.False(m5.IsSealed); Assert.False(m5.IsVirtual); Assert.True(m5.IsStatic); m6 = sorted[7] as MethodSymbol; Assert.Equal("M6", m6.Name); Assert.True(m6.IsAbstract); Assert.False(m6.IsOverride); Assert.False(m6.IsSealed); Assert.False(m6.IsVirtual); #endregion } [WorkItem(537752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537752")] [Fact] public void AbstractVirtualMethodsCrossComps() { var text = @" namespace MT { public interface IGoo { void M0(); } } "; var text1 = @" namespace N1 { using MT; public abstract class Abc : IGoo { public abstract void M0(); public char M1; public abstract object M2(ref object p1); public virtual void M3(ulong p1, out ulong p2) { p2 = p1; } public virtual object M4(params object[] ary) { return null; } public static void M5<T>(T t) { } public abstract ref int M6(ref int i); } } "; var text2 = @" namespace N1.N2 { public class Bbc : Abc { public override void M0() { } public override object M2(ref object p1) { M1 = 'a'; return p1; } public sealed override void M3(ulong p1, out ulong p2) { p2 = p1; } public override object M4(params object[] ary) { return null; } public static new void M5<T>(T t) { } public override ref int M6(ref int i) { return ref i; } } } "; var comp1 = CreateCompilationWithMscorlib45(text); var compRef1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilationWithMscorlib45(new string[] { text1 }, new List<MetadataReference>() { compRef1 }, assemblyName: "Test2"); //Compilation.Create(outputName: "Test2", options: CompilationOptions.Default, // syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text1) }, // references: new MetadataReference[] { compRef1, GetCorlibReference() }); var compRef2 = new CSharpCompilationReference(comp2); var comp = CreateCompilationWithMscorlib45(new string[] { text2 }, new List<MetadataReference>() { compRef1, compRef2 }, assemblyName: "Test3"); //Compilation.Create(outputName: "Test3", options: CompilationOptions.Default, // syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text2) }, // references: new MetadataReference[] { compRef1, compRef2, GetCorlibReference() }); Assert.Equal(0, comp1.GetDiagnostics().Count()); Assert.Equal(0, comp2.GetDiagnostics().Count()); Assert.Equal(0, comp.GetDiagnostics().Count()); //string errs = String.Empty; //foreach (var e in comp.GetDiagnostics()) //{ // errs += e.Info.ToString() + "\r\n"; //} //Assert.Equal("Errs", errs); var ns = comp.GlobalNamespace.GetMembers("N1").Single() as NamespaceSymbol; var ns1 = ns.GetMembers("N2").Single() as NamespaceSymbol; #region "Bbc" var type1 = ns1.GetTypeMembers("Bbc", 0).Single() as NamedTypeSymbol; var mems = type1.GetMembers(); Assert.Equal(7, mems.Length); // var sorted = mems.Orderby(m => m.Name).ToArray(); var sorted = (from m in mems orderby m.Name select m).ToArray(); var m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); Assert.False(m0.IsAbstract); Assert.False(m0.IsOverride); Assert.False(m0.IsSealed); Assert.False(m0.IsVirtual); var m1 = sorted[1] as MethodSymbol; Assert.Equal("M0", m1.Name); Assert.False(m1.IsAbstract); Assert.True(m1.IsOverride); Assert.False(m1.IsSealed); Assert.False(m1.IsVirtual); var m2 = sorted[2] as MethodSymbol; Assert.Equal("M2", m2.Name); Assert.False(m2.IsAbstract); Assert.True(m2.IsOverride); Assert.False(m2.IsSealed); Assert.False(m2.IsVirtual); var m3 = sorted[3] as MethodSymbol; Assert.Equal("M3", m3.Name); Assert.False(m3.IsAbstract); Assert.True(m3.IsOverride); Assert.True(m3.IsSealed); Assert.False(m3.IsVirtual); var m4 = sorted[4] as MethodSymbol; Assert.Equal("M4", m4.Name); Assert.False(m4.IsAbstract); Assert.True(m4.IsOverride); Assert.False(m4.IsSealed); Assert.False(m4.IsVirtual); var m5 = sorted[5] as MethodSymbol; Assert.Equal("M5", m5.Name); Assert.False(m5.IsAbstract); Assert.False(m5.IsOverride); Assert.False(m5.IsSealed); Assert.False(m5.IsVirtual); Assert.True(m5.IsStatic); var m6 = sorted[6] as MethodSymbol; Assert.Equal("M6", m6.Name); Assert.False(m6.IsAbstract); Assert.True(m6.IsOverride); Assert.False(m6.IsSealed); Assert.False(m6.IsVirtual); #endregion #region "Abc" var type2 = type1.BaseType(); Assert.Equal("Abc", type2.Name); mems = type2.GetMembers(); Assert.Equal(8, mems.Length); sorted = (from m in mems orderby m.Name select m).ToArray(); var mm = sorted[2] as FieldSymbol; Assert.Equal("M1", mm.Name); Assert.False(mm.IsAbstract); Assert.False(mm.IsOverride); Assert.False(mm.IsSealed); Assert.False(mm.IsVirtual); m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); Assert.False(m0.IsAbstract); Assert.False(m0.IsOverride); Assert.False(m0.IsSealed); Assert.False(m0.IsVirtual); m1 = sorted[1] as MethodSymbol; Assert.Equal("M0", m1.Name); Assert.True(m1.IsAbstract); Assert.False(m1.IsOverride); Assert.False(m1.IsSealed); Assert.False(m1.IsVirtual); m2 = sorted[3] as MethodSymbol; Assert.Equal("M2", m2.Name); Assert.True(m2.IsAbstract); Assert.False(m2.IsOverride); Assert.False(m2.IsSealed); Assert.False(m2.IsVirtual); m3 = sorted[4] as MethodSymbol; Assert.Equal("M3", m3.Name); Assert.False(m3.IsAbstract); Assert.False(m3.IsOverride); Assert.False(m3.IsSealed); Assert.True(m3.IsVirtual); m4 = sorted[5] as MethodSymbol; Assert.Equal("M4", m4.Name); Assert.False(m4.IsAbstract); Assert.False(m4.IsOverride); Assert.False(m4.IsSealed); Assert.True(m4.IsVirtual); m5 = sorted[6] as MethodSymbol; Assert.Equal("M5", m5.Name); Assert.False(m5.IsAbstract); Assert.False(m5.IsOverride); Assert.False(m5.IsSealed); Assert.False(m5.IsVirtual); Assert.True(m5.IsStatic); m6 = sorted[7] as MethodSymbol; Assert.Equal("M6", m6.Name); Assert.True(m6.IsAbstract); Assert.False(m6.IsOverride); Assert.False(m6.IsSealed); Assert.False(m6.IsVirtual); #endregion } [Fact] public void OverloadMethodsCrossTrees() { var text = @" using System; namespace NS { public class A { public void Overloads(ushort p) { } public void Overloads(A p) { } } } "; var text1 = @" namespace NS { using System; public class B : A { public void Overloads(ref A p) { } public string Overloads(B p) { return null; } protected long Overloads(A p, long p2) { return p2; } } } "; var text2 = @" namespace NS { public class Test { public class C : B { protected long Overloads(A p, B p2) { return 1; } } public static void Main() { var obj = new C(); A a = obj; obj.Overloads(ref a); obj.Overloads(obj); } } } "; var comp = CreateCompilation(new[] { text, text1, text2 }); // Not impl errors // Assert.Equal(0, comp.GetDiagnostics().Count()); var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = (ns.GetTypeMembers("Test").Single() as NamedTypeSymbol).GetTypeMembers("C", 0).Single() as NamedTypeSymbol; Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); var mems = type1.GetMembers(); Assert.Equal(2, mems.Length); var mems1 = type1.BaseType().GetMembers(); Assert.Equal(4, mems1.Length); var mems2 = type1.BaseType().BaseType().GetMembers(); Assert.Equal(3, mems2.Length); var list = new List<Symbol>(); list.AddRange(mems); list.AddRange(mems1); list.AddRange(mems2); var sorted = (from m in list orderby m.Name select m).ToArray(); var m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); m0 = sorted[1] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); m0 = sorted[2] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); var m1 = sorted[3] as MethodSymbol; Assert.Equal("System.Int64 NS.Test.C.Overloads(NS.A p, NS.B p2)", m1.ToTestDisplayString()); m1 = sorted[4] as MethodSymbol; Assert.Equal("void NS.B.Overloads(ref NS.A p)", m1.ToTestDisplayString()); m1 = sorted[5] as MethodSymbol; Assert.Equal("System.String NS.B.Overloads(NS.B p)", m1.ToTestDisplayString()); m1 = sorted[6] as MethodSymbol; Assert.Equal("System.Int64 NS.B.Overloads(NS.A p, System.Int64 p2)", m1.ToTestDisplayString()); m1 = sorted[7] as MethodSymbol; Assert.Equal("void NS.A.Overloads(System.UInt16 p)", m1.ToTestDisplayString()); m1 = sorted[8] as MethodSymbol; Assert.Equal("void NS.A.Overloads(NS.A p)", m1.ToTestDisplayString()); } [WorkItem(537752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537752")] [Fact] public void OverloadMethodsCrossComps() { var text = @" namespace NS { public class A { public void Overloads(ushort p) { } public void Overloads(A p) { } } } "; var text1 = @" namespace NS { public class B : A { public void Overloads(ref A p) { } public string Overloads(B p) { return null; } protected long Overloads(A p, long p2) { return p2; } } } "; var text2 = @" namespace NS { public class Test { public class C : B { protected long Overloads(A p, B p2) { return 1; } } public static void Main() { C obj = new C(); // var NotImpl ??? A a = obj; obj.Overloads(ref a); obj.Overloads(obj); } } } "; var comp1 = CreateCompilation(text); var compRef1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilation(new string[] { text1 }, new List<MetadataReference>() { compRef1 }, assemblyName: "Test2"); //Compilation.Create(outputName: "Test2", options: CompilationOptions.Default, // syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text1) }, // references: new MetadataReference[] { compRef1, GetCorlibReference() }); var compRef2 = new CSharpCompilationReference(comp2); var comp = CreateCompilation(new string[] { text2 }, new List<MetadataReference>() { compRef1, compRef2 }, assemblyName: "Test3"); //Compilation.Create(outputName: "Test3", options: CompilationOptions.Default, // syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text2) }, // references: new MetadataReference[] { compRef1, compRef2, GetCorlibReference() }); Assert.Equal(0, comp1.GetDiagnostics().Count()); Assert.Equal(0, comp2.GetDiagnostics().Count()); Assert.Equal(0, comp.GetDiagnostics().Count()); //string errs = String.Empty; //foreach (var e in comp.GetDiagnostics()) //{ // errs += e.Info.ToString() + "\r\n"; //} //Assert.Equal(String.Empty, errs); var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = (ns.GetTypeMembers("Test").Single() as NamedTypeSymbol).GetTypeMembers("C", 0).Single() as NamedTypeSymbol; Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); var mems = type1.GetMembers(); Assert.Equal(2, mems.Length); var mems1 = type1.BaseType().GetMembers(); Assert.Equal(4, mems1.Length); var mems2 = type1.BaseType().BaseType().GetMembers(); Assert.Equal(3, mems2.Length); var list = new List<Symbol>(); list.AddRange(mems); list.AddRange(mems1); list.AddRange(mems2); var sorted = (from m in list orderby m.Name select m).ToArray(); var m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); m0 = sorted[1] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); m0 = sorted[2] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); var m1 = sorted[3] as MethodSymbol; Assert.Equal("System.Int64 NS.Test.C.Overloads(NS.A p, NS.B p2)", m1.ToTestDisplayString()); m1 = sorted[4] as MethodSymbol; Assert.Equal("void NS.B.Overloads(ref NS.A p)", m1.ToTestDisplayString()); m1 = sorted[5] as MethodSymbol; Assert.Equal("System.String NS.B.Overloads(NS.B p)", m1.ToTestDisplayString()); m1 = sorted[6] as MethodSymbol; Assert.Equal("System.Int64 NS.B.Overloads(NS.A p, System.Int64 p2)", m1.ToTestDisplayString()); m1 = sorted[7] as MethodSymbol; Assert.Equal("void NS.A.Overloads(System.UInt16 p)", m1.ToTestDisplayString()); m1 = sorted[8] as MethodSymbol; Assert.Equal("void NS.A.Overloads(NS.A p)", m1.ToTestDisplayString()); } [WorkItem(537754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537754")] [Fact] public void PartialMethodsCrossTrees() { var text = @" namespace NS { public partial struct PS { partial void M0(string p); partial class GPC<T> { partial void GM0(T p1, short p2); } } } "; var text1 = @" namespace NS { partial struct PS { partial void M0(string p) { } partial void M1(params ulong[] ary); public partial class GPC<T> { partial void GM0(T p1, short p2) { } partial void GM1<V>(T p1, V p2); } } } "; var text2 = @" namespace NS { partial struct PS { partial void M1(params ulong[] ary) {} partial void M2(sbyte p); partial class GPC<T> { partial void GM1<V>(T p1, V p2) { } } } } "; var comp = CreateCompilation(new[] { text, text1, text2 }); Assert.Equal(0, comp.GetDiagnostics().Count()); var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("PS", 0).Single() as NamedTypeSymbol; // Bug // Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.Equal(3, type1.Locations.Length); Assert.False(type1.IsReferenceType); Assert.True(type1.IsValueType); var mems = type1.GetMembers(); Assert.Equal(5, mems.Length); var sorted = (from m in mems orderby m.Name select m).ToArray(); var m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); Assert.Equal(Accessibility.Public, m0.DeclaredAccessibility); Assert.Equal(3, m0.Locations.Length); var m2 = sorted[2] as MethodSymbol; Assert.Equal("M0", m2.Name); Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility); Assert.Equal(1, m2.Locations.Length); Assert.True(m2.ReturnsVoid); var m3 = sorted[3] as MethodSymbol; Assert.Equal("M1", m3.Name); Assert.Equal(Accessibility.Private, m3.DeclaredAccessibility); Assert.Equal(1, m3.Locations.Length); var m4 = sorted[4] as MethodSymbol; Assert.Equal("M2", m4.Name); Assert.Equal(Accessibility.Private, m4.DeclaredAccessibility); Assert.Equal(1, m4.Locations.Length); #region "GPC" var type2 = sorted[1] as NamedTypeSymbol; Assert.Equal("NS.PS.GPC<T>", type2.ToTestDisplayString()); Assert.True(type2.IsNestedType()); // Bug Assert.Equal(Accessibility.Public, type2.DeclaredAccessibility); Assert.Equal(3, type2.Locations.Length); Assert.False(type2.IsValueType); Assert.True(type2.IsReferenceType); mems = type2.GetMembers(); // Assert.Equal(3, mems.Count()); sorted = (from m in mems orderby m.Name select m).ToArray(); m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); Assert.Equal(Accessibility.Public, m0.DeclaredAccessibility); Assert.Equal(3, m0.Locations.Length); var mm = sorted[1] as MethodSymbol; Assert.Equal("GM0", mm.Name); Assert.Equal(Accessibility.Private, mm.DeclaredAccessibility); Assert.Equal(1, mm.Locations.Length); m2 = sorted[2] as MethodSymbol; Assert.Equal("GM1", m2.Name); Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility); Assert.Equal(1, m2.Locations.Length); Assert.True(m2.ReturnsVoid); #endregion } [WorkItem(537755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537755")] [Fact] public void PartialMethodsWithRefParams() { var text = @" namespace NS { public partial class PC { partial void M0(ref long p); partial void M1(ref string p); } partial class PC { partial void M0(ref long p) {} partial void M1(ref string p) {} } } "; var comp = CreateCompilation(text); Assert.Equal(0, comp.GetDiagnostics().Count()); var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("PC", 0).Single() as NamedTypeSymbol; Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.Equal(2, type1.Locations.Length); Assert.True(type1.IsReferenceType); Assert.False(type1.IsValueType); var mems = type1.GetMembers(); // Bug: actual 5 Assert.Equal(3, mems.Length); var sorted = (from m in mems orderby m.Name select m).ToArray(); var m1 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m1.Name); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Equal(2, m1.Locations.Length); var m2 = sorted[1] as MethodSymbol; Assert.Equal("M0", m2.Name); Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility); Assert.Equal(1, m2.Locations.Length); Assert.True(m2.ReturnsVoid); var m3 = sorted[2] as MethodSymbol; Assert.Equal("M1", m3.Name); Assert.Equal(Accessibility.Private, m3.DeclaredAccessibility); Assert.Equal(1, m3.Locations.Length); Assert.True(m3.ReturnsVoid); } [WorkItem(2358, "DevDiv_Projects/Roslyn")] [Fact] public void ExplicitInterfaceImplementation() { var text = @" interface ISubFuncProp { } interface Interface3 { System.Collections.Generic.List<ISubFuncProp> Goo(); } interface Interface3Derived : Interface3 { } public class DerivedClass : Interface3Derived { System.Collections.Generic.List<ISubFuncProp> Interface3.Goo() { return null; } System.Collections.Generic.List<ISubFuncProp> Goo() { return null; } }"; var comp = CreateCompilation(text); var derivedClass = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("DerivedClass")[0]; var members = derivedClass.GetMembers(); Assert.Equal(3, members.Length); } [Fact] public void SubstitutedExplicitInterfaceImplementation() { var text = @" public class A<T> { public interface I<U> { void M<V>(T t, U u, V v); } } public class B<Q, R> : A<Q>.I<R> { void A<Q>.I<R>.M<S>(Q q, R r, S s) { } } public class C : B<int, long> { }"; var comp = CreateCompilation(text); var classB = (NamedTypeSymbol)comp.GlobalNamespace.GetMembers("B").Single(); var classBTypeArguments = classB.TypeArguments(); Assert.Equal(2, classBTypeArguments.Length); Assert.Equal("Q", classBTypeArguments[0].Name); Assert.Equal("R", classBTypeArguments[1].Name); var classBMethodM = (MethodSymbol)classB.GetMembers().Single(sym => sym.Name.EndsWith("M", StringComparison.Ordinal)); var classBMethodMTypeParameters = classBMethodM.TypeParameters; Assert.Equal(1, classBMethodMTypeParameters.Length); Assert.Equal("S", classBMethodMTypeParameters[0].Name); var classBMethodMParameters = classBMethodM.Parameters; Assert.Equal(3, classBMethodMParameters.Length); Assert.Equal(classBTypeArguments[0], classBMethodMParameters[0].Type); Assert.Equal(classBTypeArguments[1], classBMethodMParameters[1].Type); Assert.Equal(classBMethodMTypeParameters[0], classBMethodMParameters[2].Type); var classC = (NamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").Single(); var classCBase = classC.BaseType(); Assert.Equal(classB, classCBase.ConstructedFrom); var classCBaseTypeArguments = classCBase.TypeArguments(); Assert.Equal(2, classCBaseTypeArguments.Length); Assert.Equal(SpecialType.System_Int32, classCBaseTypeArguments[0].SpecialType); Assert.Equal(SpecialType.System_Int64, classCBaseTypeArguments[1].SpecialType); var classCBaseMethodM = (MethodSymbol)classCBase.GetMembers().Single(sym => sym.Name.EndsWith("M", StringComparison.Ordinal)); Assert.NotEqual(classBMethodM, classCBaseMethodM); var classCBaseMethodMTypeParameters = classCBaseMethodM.TypeParameters; Assert.Equal(1, classCBaseMethodMTypeParameters.Length); Assert.Equal("S", classCBaseMethodMTypeParameters[0].Name); var classCBaseMethodMParameters = classCBaseMethodM.Parameters; Assert.Equal(3, classCBaseMethodMParameters.Length); Assert.Equal(classCBaseTypeArguments[0], classCBaseMethodMParameters[0].Type); Assert.Equal(classCBaseTypeArguments[1], classCBaseMethodMParameters[1].Type); Assert.Equal(classCBaseMethodMTypeParameters[0], classCBaseMethodMParameters[2].Type); } #region Regressions [WorkItem(527149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527149")] [Fact] public void MethodWithParamsInParameters() { var text = @"class C { void F1(params int[] a) { } } "; var comp = CreateEmptyCompilation(text); var c = comp.GlobalNamespace.GetTypeMembers("C").Single(); var f1 = c.GetMembers("F1").Single() as MethodSymbol; Assert.Equal("void C.F1(params System.Int32[missing][] a)", f1.ToTestDisplayString()); } [WorkItem(537352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537352")] [Fact] public void Arglist() { string code = @" class AA { public static int Method1(__arglist) { } }"; var comp = CreateCompilation(code); NamedTypeSymbol nts = comp.Assembly.GlobalNamespace.GetTypeMembers()[0]; Assert.Equal("AA", nts.ToTestDisplayString()); Assert.Empty(comp.GetDeclarationDiagnostics()); Assert.Equal("System.Int32 AA.Method1(__arglist)", nts.GetMembers("Method1").Single().ToTestDisplayString()); } [WorkItem(537877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537877")] [Fact] public void ExpImpInterfaceWithGlobal() { var text = @" using System; namespace N1 { interface I1 { int Method(); } } namespace N2 { class ExpImpl : N1.I1 { int global::N1.I1.Method() { return 42; } ExpImpl(){} } } "; var comp = CreateCompilation(text); Assert.Equal(0, comp.GetDeclarationDiagnostics().Count()); var ns = comp.GlobalNamespace.GetMembers("N2").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("ExpImpl", 0).Single() as NamedTypeSymbol; var m1 = type1.GetMembers().FirstOrDefault() as MethodSymbol; Assert.Equal("System.Int32 N2.ExpImpl.N1.I1.Method()", m1.ToTestDisplayString()); var em1 = m1.ExplicitInterfaceImplementations.First() as MethodSymbol; Assert.Equal("System.Int32 N1.I1.Method()", em1.ToTestDisplayString()); } [WorkItem(537877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537877")] [Fact] public void BaseInterfaceNameWithAlias() { var text = @" using N1Alias = N1; namespace N1 { interface I1 {} } namespace N2 { class N1Alias {} class Test : N1Alias::I1 { static int Main() { Test t = new Test(); return 0; } } } "; var comp = CreateCompilation(text); Assert.Equal(0, comp.GetDeclarationDiagnostics().Count()); var n2 = comp.GlobalNamespace.GetMembers("N2").Single() as NamespaceSymbol; var test = n2.GetTypeMembers("Test").Single() as NamedTypeSymbol; var bt = test.Interfaces().Single() as NamedTypeSymbol; Assert.Equal("N1.I1", bt.ToTestDisplayString()); } [WorkItem(538209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538209")] [Fact] public void ParameterAccessibility01() { var text = @" using System; class MyClass { private class MyInner { public int MyMeth(MyInner2 arg) { return arg.intI; } } protected class MyInner2 { public int intI = 2; } public static int Main() { MyInner MI = new MyInner(); if (MI.MyMeth(new MyInner2()) == 2) { return 0; } else { return 1; } } } "; var comp = CreateCompilation(text); Assert.Equal(0, comp.GetDeclarationDiagnostics().Count()); } [WorkItem(537877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537877")] [Fact] public void MethodsWithSameSigDiffReturnType() { var text = @" class Test { public int M1() { } float M1() { } } "; var comp = CreateCompilation(text); var test = comp.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol; var members = test.GetMembers("M1"); Assert.Equal(2, members.Length); Assert.Equal("System.Int32 Test.M1()", members[0].ToTestDisplayString()); Assert.Equal("System.Single Test.M1()", members[1].ToTestDisplayString()); } [Fact] public void OverriddenMethod01() { var text = @" class A { public virtual void F(object[] args) {} } class B : A { public override void F(params object[] args) {} public static void Main(B b) { b.F(// yes, there is a parse error here } } "; var comp = CreateCompilation(text); var a = comp.GlobalNamespace.GetTypeMembers("A").Single() as NamedTypeSymbol; var b = comp.GlobalNamespace.GetTypeMembers("B").Single() as NamedTypeSymbol; var f = b.GetMembers("F").Single() as MethodSymbol; Assert.True(f.IsOverride); var f2 = f.OverriddenMethod; Assert.NotNull(f2); Assert.Equal("A", f2.ContainingSymbol.Name); } #endregion [WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")] [Fact] public void MethodEscapedIdentifier() { var text = @" interface @void { @void @return(@void @in); }; class @int { virtual @int @float(@int @in); }; class C1 : @int, @void { @void @void.@return(@void @in) { return null; } override @int @float(@int @in) { return null; } } "; var comp = CreateCompilation(Parse(text)); NamedTypeSymbol c1 = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("C1").Single(); // Per explanation from NGafter: // // We intentionally escape keywords that appear in the type qualification of the interface name // on interface implementation members. That is necessary to distinguish I<int>.F from I<@int>.F, // for example, which might both be members in a class. An alternative would be to stop using the // abbreviated names for the built-in types, but since we may want to use these names in // diagnostics the @-escaped version is preferred. // MethodSymbol mreturn = (MethodSymbol)c1.GetMembers("@void.return").Single(); Assert.Equal("@void.return", mreturn.Name); Assert.Equal("C1.@void.@return(@void)", mreturn.ToString()); NamedTypeSymbol rvoid = (NamedTypeSymbol)mreturn.ReturnType; Assert.Equal("void", rvoid.Name); Assert.Equal("@void", rvoid.ToString()); MethodSymbol mvoidreturn = (MethodSymbol)mreturn.ExplicitInterfaceImplementations.Single(); Assert.Equal("return", mvoidreturn.Name); Assert.Equal("@void.@return(@void)", mvoidreturn.ToString()); ParameterSymbol pin = mreturn.Parameters.Single(); Assert.Equal("in", pin.Name); Assert.Equal("@in", pin.ToDisplayString( new SymbolDisplayFormat( parameterOptions: SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers))); MethodSymbol mfloat = (MethodSymbol)c1.GetMembers("float").Single(); Assert.Equal("float", mfloat.Name); Assert.Empty(c1.GetMembers("@float")); } [Fact] public void ExplicitInterfaceImplementationSimple() { string text = @" interface I { void Method(); } class C : I { void I.Method() { } } "; var comp = CreateCompilation(Parse(text)); var globalNamespace = comp.GlobalNamespace; var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.True(@class.Interfaces().Contains(@interface)); var classMethod = (MethodSymbol)@class.GetMembers("I.Method").Single(); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind); var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single(); Assert.Equal(interfaceMethod, explicitImpl); var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single(); Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol()); Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod.GetInternalSymbol()); context.Diagnostics.Verify(); } [Fact] public void ExplicitInterfaceImplementationCorLib() { string text = @" class F : System.IFormattable { string System.IFormattable.ToString(string format, System.IFormatProvider formatProvider) { return null; } } "; var comp = CreateCompilation(Parse(text)); var globalNamespace = comp.GlobalNamespace; var systemNamespace = (NamespaceSymbol)globalNamespace.GetMembers("System").Single(); var @interface = (NamedTypeSymbol)systemNamespace.GetTypeMembers("IFormattable").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceMethod = (MethodSymbol)@interface.GetMembers("ToString").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("F").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.True(@class.Interfaces().Contains(@interface)); var classMethod = (MethodSymbol)@class.GetMembers("System.IFormattable.ToString").Single(); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind); var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single(); Assert.Equal(interfaceMethod, explicitImpl); var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single(); Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol()); Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod.GetInternalSymbol()); context.Diagnostics.Verify(); } [Fact] public void ExplicitInterfaceImplementationRef() { string text = @" interface I { ref int Method(ref int i); } class C : I { ref int I.Method(ref int i) { return ref i; } } "; var comp = CreateCompilationWithMscorlib45(text); var globalNamespace = comp.GlobalNamespace; var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single(); Assert.Equal(RefKind.Ref, interfaceMethod.RefKind); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.True(@class.Interfaces().Contains(@interface)); var classMethod = (MethodSymbol)@class.GetMembers("I.Method").Single(); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind); Assert.Equal(RefKind.Ref, classMethod.RefKind); var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single(); Assert.Equal(interfaceMethod, explicitImpl); var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single(); Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol()); Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod.GetInternalSymbol()); context.Diagnostics.Verify(); } [Fact] public void ExplicitInterfaceImplementationGeneric() { string text = @" namespace Namespace { interface I<T> { void Method(T t); } } class IC : Namespace.I<int> { void Namespace.I<int>.Method(int i) { } } "; var comp = CreateCompilation(Parse(text)); var globalNamespace = comp.GlobalNamespace; var systemNamespace = (NamespaceSymbol)globalNamespace.GetMembers("Namespace").Single(); var @interface = (NamedTypeSymbol)systemNamespace.GetTypeMembers("I", 1).Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IC").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); var substitutedInterface = @class.Interfaces().Single(); Assert.Equal(@interface, substitutedInterface.ConstructedFrom); var substitutedInterfaceMethod = (MethodSymbol)substitutedInterface.GetMembers("Method").Single(); var classMethod = (MethodSymbol)@class.GetMembers("Namespace.I<System.Int32>.Method").Single(); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind); var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single(); Assert.Equal(substitutedInterface, explicitImpl.ContainingType); Assert.Equal(substitutedInterfaceMethod.OriginalDefinition, explicitImpl.OriginalDefinition); var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single(); Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol()); Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol()); var explicitOverrideImplementedMethod = explicitOverride.ImplementedMethod; Assert.Equal(substitutedInterface, explicitOverrideImplementedMethod.GetContainingType(context).GetInternalSymbol()); Assert.Equal(substitutedInterfaceMethod.Name, explicitOverrideImplementedMethod.Name); Assert.Equal(substitutedInterfaceMethod.Arity, explicitOverrideImplementedMethod.GenericParameterCount); context.Diagnostics.Verify(); } [Fact()] public void TestMetadataVirtual() { string text = @" class C { virtual void Method1() { } virtual void Method2() { } void Method3() { } void Method4() { } } "; var comp = CreateCompilation(Parse(text)); var @class = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("C").Single(); var method1 = (SourceMemberMethodSymbol)@class.GetMembers("Method1").Single(); var method2 = (SourceMemberMethodSymbol)@class.GetMembers("Method2").Single(); var method3 = (SourceMemberMethodSymbol)@class.GetMembers("Method3").Single(); var method4 = (SourceMemberMethodSymbol)@class.GetMembers("Method4").Single(); Assert.True(method1.IsVirtual); Assert.True(method2.IsVirtual); Assert.False(method3.IsVirtual); Assert.False(method4.IsVirtual); //1 and 3 - read before set Assert.True(((Cci.IMethodDefinition)method1.GetCciAdapter()).IsVirtual); Assert.False(((Cci.IMethodDefinition)method3.GetCciAdapter()).IsVirtual); //2 and 4 - set before read method2.EnsureMetadataVirtual(); method4.EnsureMetadataVirtual(); //can set twice (e.g. if the method implicitly implements more than one interface method) method2.EnsureMetadataVirtual(); method4.EnsureMetadataVirtual(); Assert.True(((Cci.IMethodDefinition)method2.GetCciAdapter()).IsVirtual); Assert.True(((Cci.IMethodDefinition)method4.GetCciAdapter()).IsVirtual); //API view unchanged Assert.True(method1.IsVirtual); Assert.True(method2.IsVirtual); Assert.False(method3.IsVirtual); Assert.False(method4.IsVirtual); } [Fact] public void ExplicitStaticConstructor() { string text = @" class C { static C() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); var staticConstructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.StaticConstructorName); Assert.Equal(MethodKind.StaticConstructor, staticConstructor.MethodKind); Assert.Equal(Accessibility.Private, staticConstructor.DeclaredAccessibility); Assert.True(staticConstructor.IsStatic, "Static constructor should be static"); Assert.Equal(SpecialType.System_Void, staticConstructor.ReturnType.SpecialType); } [Fact] public void ImplicitStaticConstructor() { string text = @" class C { static int f = 1; //initialized in implicit static constructor } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,16): warning CS0414: The field 'C.f' is assigned but its value is never used // static int f = 1; //initialized in implicit static constructor Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "f").WithArguments("C.f") ); var staticConstructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.StaticConstructorName); Assert.Equal(MethodKind.StaticConstructor, staticConstructor.MethodKind); Assert.Equal(Accessibility.Private, staticConstructor.DeclaredAccessibility); Assert.True(staticConstructor.IsStatic, "Static constructor should be static"); Assert.Equal(SpecialType.System_Void, staticConstructor.ReturnType.SpecialType); } [WorkItem(541834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541834")] [Fact] public void AccessorMethodAccessorOverriding() { var text = @" public class A { public virtual int P { get; set; } } public class B : A { public virtual int get_P() { return 0; } } public class C : B { public override int P { get; set; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); var globalNamespace = comp.GlobalNamespace; var classA = globalNamespace.GetMember<NamedTypeSymbol>("A"); var classB = globalNamespace.GetMember<NamedTypeSymbol>("B"); var classC = globalNamespace.GetMember<NamedTypeSymbol>("C"); var methodA = classA.GetMember<PropertySymbol>("P").GetMethod; var methodB = classB.GetMember<MethodSymbol>("get_P"); var methodC = classC.GetMember<PropertySymbol>("P").GetMethod; var typeDefC = (Cci.ITypeDefinition)classC.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)classC.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverride = typeDefC.GetExplicitImplementationOverrides(context).Single(); Assert.Equal(classC, explicitOverride.ContainingType.GetInternalSymbol()); Assert.Equal(methodC, explicitOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(methodA, explicitOverride.ImplementedMethod.GetInternalSymbol()); context.Diagnostics.Verify(); } [WorkItem(541834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541834")] [Fact] public void MethodAccessorMethodOverriding() { var text = @" public class A { public virtual int get_P() { return 0; } } public class B : A { public virtual int P { get; set; } } public class C : B { public override int get_P() { return 0; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); var globalNamespace = comp.GlobalNamespace; var classA = globalNamespace.GetMember<NamedTypeSymbol>("A"); var classB = globalNamespace.GetMember<NamedTypeSymbol>("B"); var classC = globalNamespace.GetMember<NamedTypeSymbol>("C"); var methodA = classA.GetMember<MethodSymbol>("get_P"); var methodB = classB.GetMember<PropertySymbol>("P").GetMethod; var methodC = classC.GetMember<MethodSymbol>("get_P"); var typeDefC = (Cci.ITypeDefinition)classC.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)classC.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverride = typeDefC.GetExplicitImplementationOverrides(context).Single(); Assert.Equal(classC, explicitOverride.ContainingType.GetInternalSymbol()); Assert.Equal(methodC, explicitOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(methodA, explicitOverride.ImplementedMethod.GetInternalSymbol()); context.Diagnostics.Verify(); } [WorkItem(543444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543444")] [Fact] public void BadArityInOperatorDeclaration() { var text = @"class A { public static bool operator true(A x, A y) { return false; } } class B { public static B operator *(B x) { return null; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,33): error CS1020: Overloadable binary operator expected // public static bool operator true(A x, A y) { return false; } Diagnostic(ErrorCode.ERR_OvlBinaryOperatorExpected, "true"), // (8,30): error CS1019: Overloadable unary operator expected // public static B operator *(B x) { return null; } Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "*"), // (3,33): error CS0216: The operator 'A.operator true(A, A)' requires a matching operator 'false' to also be defined // public static bool operator true(A x, A y) { return false; } Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "true").WithArguments("A.operator true(A, A)", "false") ); } [WorkItem(779441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779441")] [Fact] public void UserDefinedOperatorLocation() { var source = @" public class C { public static C operator +(C c) { return null; } } "; var keywordPos = source.IndexOf('+'); var parenPos = source.IndexOf('('); var comp = CreateCompilation(source); var symbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName).Single(); var span = symbol.Locations.Single().SourceSpan; Assert.Equal(keywordPos, span.Start); Assert.Equal(parenPos, span.End); } [WorkItem(779441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779441")] [Fact] public void UserDefinedConversionLocation() { var source = @" public class C { public static explicit operator string(C c) { return null; } } "; var keywordPos = source.IndexOf("string", StringComparison.Ordinal); var parenPos = source.IndexOf('('); var comp = CreateCompilation(source); var symbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.ExplicitConversionName).Single(); var span = symbol.Locations.Single().SourceSpan; Assert.Equal(keywordPos, span.Start); Assert.Equal(parenPos, span.End); } [WorkItem(787708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/787708")] [Fact] public void PartialAsyncMethodInTypeWithAttributes() { var source = @" using System; class Attr : Attribute { public int P { get; set; } } [Attr(P = F)] partial class C { const int F = 1; partial void M(); async partial void M() { } } "; CreateCompilation(source).VerifyDiagnostics( // (15,24): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async partial void M() { } Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M")); } [WorkItem(910100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910100")] [Fact] public void SubstitutedParameterEquality() { var source = @" class C { void M<T>(T t) { } } "; var comp = CreateCompilation(source); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var constructedMethod1 = method.Construct(type); var constructedMethod2 = method.Construct(type); Assert.Equal(constructedMethod1, constructedMethod2); Assert.NotSame(constructedMethod1, constructedMethod2); var substitutedParameter1 = constructedMethod1.Parameters.Single(); var substitutedParameter2 = constructedMethod2.Parameters.Single(); Assert.Equal(substitutedParameter1, substitutedParameter2); Assert.NotSame(substitutedParameter1, substitutedParameter2); } [WorkItem(910100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910100")] [Fact] public void ReducedExtensionMethodParameterEquality() { var source = @" static class C { static void M(this int i, string s) { } } "; var comp = CreateCompilation(source); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var reducedMethod1 = method.ReduceExtensionMethod(); var reducedMethod2 = method.ReduceExtensionMethod(); Assert.Equal(reducedMethod1, reducedMethod2); Assert.NotSame(reducedMethod1, reducedMethod2); var extensionParameter1 = reducedMethod1.Parameters.Single(); var extensionParameter2 = reducedMethod2.Parameters.Single(); Assert.Equal(extensionParameter1, extensionParameter2); Assert.NotSame(extensionParameter1, extensionParameter2); } [Fact] public void RefReturningVoidMethod() { var source = @" static class C { static ref void M() { } } "; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (4,16): error CS1547: Keyword 'void' cannot be used in this context // static ref void M() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(4, 16) ); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningVoidMethod() { var source = @" static class C { static ref readonly void M() { } } "; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (4,25): error CS1547: Keyword 'void' cannot be used in this context // static ref readonly void M() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(4, 25) ); } [Fact] public void RefReturningVoidMethodNested() { var source = @" static class C { static void Main() { ref void M() { } } } "; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,13): error CS1547: Keyword 'void' cannot be used in this context // ref void M() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(6, 13), // (6,18): warning CS8321: The local function 'M' is declared but never used // ref void M() { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "M").WithArguments("M").WithLocation(6, 18) ); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningVoidMethodNested() { var source = @" static class C { static void Main() { // valid ref readonly int M1() {throw null;} // not valid ref readonly void M2() {M1(); throw null;} M2(); } } "; var parseOptions = TestOptions.Regular; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,22): error CS1547: Keyword 'void' cannot be used in this context // ref readonly void M2() {M1(); throw null;} Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(10, 22) ); } [Fact] public void RefReturningAsyncMethod() { var source = @" static class C { static async ref int M() { } } "; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (4,18): error CS1073: Unexpected token 'ref' // static async ref int M() { } Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(4, 18), // (4,26): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // static async ref int M() { } Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 26), // (4,26): error CS0161: 'C.M()': not all code paths return a value // static async ref int M() { } Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("C.M()").WithLocation(4, 26) ); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningAsyncMethod() { var source = @" static class C { static async ref readonly int M() { } } "; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (4,18): error CS1073: Unexpected token 'ref' // static async ref readonly int M() { } Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(4, 18), // (4,35): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // static async ref readonly int M() { } Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 35), // (4,35): error CS0161: 'C.M()': not all code paths return a value // static async ref readonly int M() { } Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("C.M()").WithLocation(4, 35) ); } [Fact] public void StaticMethodDoesNotRequireInstanceReceiver() { var source = @" class C { public static int M() => 42; }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var method = compilation.GetMember<MethodSymbol>("C.M"); Assert.False(method.RequiresInstanceReceiver); } [Fact] public void InstanceMethodRequiresInstanceReceiver() { var source = @" class C { public int M() => 42; }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var method = compilation.GetMember<MethodSymbol>("C.M"); Assert.True(method.RequiresInstanceReceiver); } [Fact] public void OrdinaryMethodIsNotConditional() { var source = @" class C { public void M() {} }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var method = compilation.GetMember<MethodSymbol>("C.M"); Assert.False(method.IsConditional); } [Fact] public void ConditionalMethodIsConditional() { var source = @" using System.Diagnostics; class C { [Conditional(""Debug"")] public void M() {} }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var method = compilation.GetMember<MethodSymbol>("C.M"); Assert.True(method.IsConditional); } [Fact] public void ConditionalMethodOverrideIsConditional() { var source = @" using System.Diagnostics; class Base { [Conditional(""Debug"")] public virtual void M() {} } class Derived : Base { public override void M() {} }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var method = compilation.GetMember<MethodSymbol>("Derived.M"); Assert.True(method.IsConditional); } [Fact] public void InvalidConditionalMethodIsConditional() { var source = @" using System.Diagnostics; class C { [Conditional(""Debug"")] public int M() => 42; }"; var compilation = CreateCompilation(source).VerifyDiagnostics( // (5,6): error CS0578: The Conditional attribute is not valid on 'C.M()' because its return type is not void // [Conditional("Debug")] Diagnostic(ErrorCode.ERR_ConditionalMustReturnVoid, @"Conditional(""Debug"")").WithArguments("C.M()").WithLocation(5, 6)); var method = compilation.GetMember<MethodSymbol>("C.M"); Assert.True(method.IsConditional); } [Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")] public void IsPartialDefinitionOnNonPartial() { var source = @" class C { void M() {} } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol(); Assert.False(m.IsPartialDefinition); } [Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")] public void IsPartialDefinitionOnPartialDefinitionOnly() { var source = @" partial class C { partial void M(); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol(); Assert.True(m.IsPartialDefinition); Assert.Null(m.PartialDefinitionPart); Assert.Null(m.PartialImplementationPart); } [Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")] public void IsPartialDefinitionWithPartialImplementation() { var source = @" partial class C { partial void M(); partial void M() {} } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol(); Assert.True(m.IsPartialDefinition); Assert.Null(m.PartialDefinitionPart); Assert.False(m.PartialImplementationPart.IsPartialDefinition); } [Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")] public void IsPartialDefinitionOnPartialImplementation_NonPartialClass() { var source = @" class C { partial void M(); partial void M() {} } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,18): error CS0751: A partial method must be declared within a partial type // partial void M(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(4, 18), // (5,18): error CS0751: A partial method must be declared within a partial type // partial void M() {} Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(5, 18) ); var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol(); Assert.True(m.IsPartialDefinition); Assert.Null(m.PartialDefinitionPart); Assert.False(m.PartialImplementationPart.IsPartialDefinition); } [Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")] public void IsPartialDefinitionOnPartialImplementationOnly() { var source = @" partial class C { partial void M() {} } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M()' // partial void M() {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M()").WithLocation(4, 18) ); var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol(); Assert.False(m.IsPartialDefinition); Assert.Null(m.PartialDefinitionPart); Assert.Null(m.PartialImplementationPart); } [Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")] public void IsPartialDefinition_ReturnsFalseFromMetadata() { var source = @" public partial class C { public partial void M(); public partial void M() {} } "; CompileAndVerify(source, sourceSymbolValidator: module => { var m = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").GetPublicSymbol(); Assert.True(m.IsPartialDefinition); Assert.Null(m.PartialDefinitionPart); Assert.False(m.PartialImplementationPart.IsPartialDefinition); }, symbolValidator: module => { var m = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").GetPublicSymbol(); Assert.False(m.IsPartialDefinition); Assert.Null(m.PartialDefinitionPart); Assert.Null(m.PartialImplementationPart); }); } [Fact] public void IsPartialDefinition_OnPartialExtern() { var source = @" public partial class C { private partial void M(); private extern partial void M(); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var syntax = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntax); var methods = syntax.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ToArray(); var partialDef = model.GetDeclaredSymbol(methods[0]); Assert.True(partialDef.IsPartialDefinition); var partialImpl = model.GetDeclaredSymbol(methods[1]); Assert.False(partialImpl.IsPartialDefinition); Assert.Same(partialDef.PartialImplementationPart, partialImpl); Assert.Same(partialImpl.PartialDefinitionPart, partialDef); Assert.Null(partialDef.PartialDefinitionPart); Assert.Null(partialImpl.PartialImplementationPart); } } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MethodTests : CSharpTestBase { [Fact] public void Simple1() { var text = @" class A { void M(int x) {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.GetMembers("M").Single() as MethodSymbol; Assert.NotNull(m); Assert.True(m.ReturnsVoid); var x = m.Parameters[0]; Assert.Equal("x", x.Name); Assert.Equal(SymbolKind.NamedType, x.Type.Kind); Assert.Equal("Int32", x.Type.Name); // fully qualified to work around a metadata reader bug Assert.Equal(SymbolKind.Parameter, x.Kind); Assert.Equal(Accessibility.Private, m.DeclaredAccessibility); } [Fact] public void NoParameterlessCtorForStruct() { var text = "struct A { A() {} }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,12): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // struct A { A() {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "A").WithArguments("parameterless struct constructors", "10.0").WithLocation(1, 12), // (1,12): error CS8938: The parameterless struct constructor must be 'public'. // struct A { A() {} } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "A").WithLocation(1, 12)); } [WorkItem(537194, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537194")] [Fact] public void DefaultCtor1() { Action<string, string, int, Accessibility?> check = (source, className, ctorCount, accessibility) => { var comp = CreateCompilation(source); var global = comp.GlobalNamespace; var a = global.GetTypeMembers(className, 0).Single(); var ctors = a.InstanceConstructors; // Note, this only returns *instance* constructors. Assert.Equal(ctorCount, ctors.Length); foreach (var ct in ctors) { Assert.Equal( ct.IsStatic ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName, ct.Name ); if (accessibility != null) Assert.Equal(accessibility, ct.DeclaredAccessibility); } }; Accessibility? doNotCheckAccessibility = null; // A class without any defined constructors should generator a public constructor. check(@"internal class A { }", "A", 1, Accessibility.Public); // An abstract class without any defined constructors should generator a protected constructor. check(@"abstract internal class A { }", "A", 1, Accessibility.Protected); // A static class should not generate a default constructor check(@"static internal class A { }", "A", 0, doNotCheckAccessibility); // A class with a defined instance constructor should not generate a default constructor. check(@"internal class A { A(int x) {} }", "A", 1, doNotCheckAccessibility); // A class with only a static constructor defined should still generate a default instance constructor. check(@"internal class A { static A(int x) {} }", "A", 1, doNotCheckAccessibility); } [WorkItem(537345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537345")] [Fact] public void Ctor1() { var text = @" class A { A(int x) {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.InstanceConstructors.Single(); Assert.NotNull(m); Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m.Name); Assert.True(m.ReturnsVoid); Assert.Equal(MethodKind.Constructor, m.MethodKind); var x = m.Parameters[0]; Assert.Equal("x", x.Name); Assert.Equal(SymbolKind.NamedType, x.Type.Kind); Assert.Equal("Int32", x.Type.Name); // fully qualified to work around a metadata reader bug Assert.Equal(SymbolKind.Parameter, x.Kind); Assert.Equal(Accessibility.Private, m.DeclaredAccessibility); } [Fact] public void Simple2() { var text = @" class A { void M<T>(int x) {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.GetMembers("M").Single() as MethodSymbol; Assert.NotNull(m); Assert.True(m.ReturnsVoid); Assert.Equal(MethodKind.Ordinary, m.MethodKind); var x = m.Parameters[0]; Assert.Equal("x", x.Name); Assert.Equal(SymbolKind.NamedType, x.Type.Kind); Assert.Equal("Int32", x.Type.Name); // fully qualified to work around a metadata reader bug Assert.Equal(SymbolKind.Parameter, x.Kind); Assert.Equal(Accessibility.Private, m.DeclaredAccessibility); } [Fact] public void Access1() { var text = @" class A { void M1() {} } interface B { void M2() {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m1 = a.GetMembers("M1").Single() as MethodSymbol; var b = global.GetTypeMembers("B", 0).Single(); var m2 = b.GetMembers("M2").Single() as MethodSymbol; Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility); } [Fact] public void GenericParameter() { var text = @" public class MyList<T> { public void Add(T element) { } } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var mylist = global.GetTypeMembers("MyList", 1).Single(); var t1 = mylist.TypeParameters[0]; var add = mylist.GetMembers("Add").Single() as MethodSymbol; var element = add.Parameters[0]; var t2 = element.Type; Assert.Equal(t1, t2); } [Fact] public void PartialLocation() { var text = @" public partial class A { partial void M(); } public partial class A { partial void M() {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.GetMembers("M"); Assert.Equal(1, m.Length); Assert.Equal(1, m.First().Locations.Length); } [Fact] public void PartialExtractSyntaxLocation_DeclBeforeDef() { var text = @"public partial class A { partial void M(); } public partial class A { partial void M() {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = (MethodSymbol)a.GetMembers("M").Single(); Assert.True(m.IsPartialDefinition()); var returnSyntax = m.ExtractReturnTypeSyntax(); var tree = comp.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).First(); var otherSymbol = m.PartialImplementationPart; Assert.True(otherSymbol.IsPartialImplementation()); Assert.Equal(node, returnSyntax); Assert.Equal(node, otherSymbol.ExtractReturnTypeSyntax()); } [Fact] public void PartialExtractSyntaxLocation_DefBeforeDecl() { var text = @"public partial class A { partial void M() {} } public partial class A { partial void M(); } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = (MethodSymbol)a.GetMembers("M").Single(); Assert.True(m.IsPartialDefinition()); var returnSyntax = m.ExtractReturnTypeSyntax(); var tree = comp.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).Last(); var otherSymbol = m.PartialImplementationPart; Assert.True(otherSymbol.IsPartialImplementation()); Assert.Equal(node, returnSyntax); Assert.Equal(node, otherSymbol.ExtractReturnTypeSyntax()); } [Fact] public void PartialExtractSyntaxLocation_OnlyDef() { var text = @"public partial class A { partial void M() {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = (MethodSymbol)a.GetMembers("M").Single(); Assert.True(m.IsPartialImplementation()); var returnSyntax = m.ExtractReturnTypeSyntax(); var tree = comp.SyntaxTrees.Single().GetRoot(); var node = tree.DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).Single(); Assert.Equal(node, returnSyntax); } [Fact] public void PartialExtractSyntaxLocation_OnlyDecl() { var text = @"public partial class A { partial void M(); } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = (MethodSymbol)a.GetMembers("M").Single(); Assert.True(m.IsPartialDefinition()); var returnSyntax = m.ExtractReturnTypeSyntax(); var tree = comp.SyntaxTrees.Single().GetRoot(); var node = tree.DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).Single(); Assert.Equal(node, returnSyntax); } [Fact] public void FullName() { var text = @" public class A { public string M(int x); } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.GetMembers("M").Single() as MethodSymbol; Assert.Equal("System.String A.M(System.Int32 x)", m.ToTestDisplayString()); } [Fact] public void TypeParameterScope() { var text = @" public interface A { T M<T>(T t); } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.GetMembers("M").Single() as MethodSymbol; var t = m.TypeParameters[0]; Assert.Equal(t, m.Parameters[0].Type); Assert.Equal(t, m.ReturnType); } [WorkItem(931142, "DevDiv/Personal")] [Fact] public void RefOutParameterType() { var text = @"public class A { void M(ref A refp, out long outp) { } } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.GetMembers("M").Single() as MethodSymbol; var p1 = m.Parameters[0]; var p2 = m.Parameters[1]; Assert.Equal(RefKind.Ref, p1.RefKind); Assert.Equal(RefKind.Out, p2.RefKind); var refP = p1.Type; Assert.Equal(TypeKind.Class, refP.TypeKind); Assert.True(refP.IsReferenceType); Assert.False(refP.IsValueType); Assert.Equal("Object", refP.BaseType().Name); Assert.Equal(2, refP.GetMembers().Length); // M + generated constructor. Assert.Equal(1, refP.GetMembers("M").Length); var outP = p2.Type; Assert.Equal(TypeKind.Struct, outP.TypeKind); Assert.False(outP.IsReferenceType); Assert.True(outP.IsValueType); Assert.False(outP.IsStatic); Assert.False(outP.IsAbstract); Assert.True(outP.IsSealed); Assert.Equal(Accessibility.Public, outP.DeclaredAccessibility); Assert.Equal(5, outP.Interfaces().Length); Assert.Equal(0, outP.GetTypeMembers().Length); // Enumerable.Empty<NamedTypeSymbol>() Assert.Equal(0, outP.GetTypeMembers(String.Empty).Length); Assert.Equal(0, outP.GetTypeMembers(String.Empty, 0).Length); } [Fact] public void RefReturn() { var text = @"public class A { ref int M(ref int i) { return ref i; } } "; var comp = CreateCompilationWithMscorlib45(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var m = a.GetMembers("M").Single() as MethodSymbol; Assert.Equal(RefKind.Ref, m.RefKind); Assert.Equal(TypeKind.Struct, m.ReturnType.TypeKind); Assert.False(m.ReturnType.IsReferenceType); Assert.True(m.ReturnType.IsValueType); var p1 = m.Parameters[0]; Assert.Equal(RefKind.Ref, p1.RefKind); Assert.Equal("ref System.Int32 A.M(ref System.Int32 i)", m.ToTestDisplayString()); } [Fact] public void BothKindsOfCtors() { var text = @"public class Test { public Test() {} public static Test() {} }"; var comp = CreateCompilation(text); var classTest = comp.GlobalNamespace.GetTypeMembers("Test", 0).Single(); var members = classTest.GetMembers(); Assert.Equal(2, members.Length); } [WorkItem(931663, "DevDiv/Personal")] [Fact] public void RefOutArrayParameter() { var text = @"public class Test { public void MethodWithRefOutArray(ref int[] ary1, out string[] ary2) { ary2 = null; } }"; var comp = CreateCompilation(text); var classTest = comp.GlobalNamespace.GetTypeMembers("Test", 0).Single(); var method = classTest.GetMembers("MethodWithRefOutArray").Single() as MethodSymbol; Assert.Equal(classTest, method.ContainingSymbol); Assert.Equal(SymbolKind.Method, method.Kind); Assert.True(method.IsDefinition); // var paramList = (method as MethodSymbol).Parameters; var p1 = method.Parameters[0]; var p2 = method.Parameters[1]; Assert.Equal(RefKind.Ref, p1.RefKind); Assert.Equal(RefKind.Out, p2.RefKind); } [Theory, MemberData(nameof(FileScopedOrBracedNamespace))] public void InterfaceImplementsCrossTrees(string ob, string cb) { var text1 = @"using System; using System.Collections.Generic; namespace NS " + ob + @" public class Abc {} public interface IGoo<T> { void M(ref T t); } public interface I1 { void M(ref string p); int M1(short p1, params object[] ary); } public interface I2 : I1 { void M21(); Abc M22(ref Abc p); } " + cb; var text2 = @"using System; using System.Collections.Generic; namespace NS.NS1 " + ob + @" public class Impl : I2, IGoo<string>, I1 { void IGoo<string>.M(ref string p) { } void I1.M(ref string p) { } public int M1(short p1, params object[] ary) { return p1; } public void M21() {} public Abc M22(ref Abc p) { return p; } } struct S<T>: IGoo<T> { void IGoo<T>.M(ref T t) {} } " + cb; var comp = CreateCompilation(new[] { text1, text2 }); Assert.Equal(0, comp.GetDeclarationDiagnostics().Count()); var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var ns1 = ns.GetMembers("NS1").Single() as NamespaceSymbol; var classImpl = ns1.GetTypeMembers("Impl", 0).Single() as NamedTypeSymbol; Assert.Equal(3, classImpl.Interfaces().Length); // var itfc = classImpl.Interfaces().First() as NamedTypeSymbol; Assert.Equal(1, itfc.Interfaces().Length); itfc = itfc.Interfaces().First() as NamedTypeSymbol; Assert.Equal("I1", itfc.Name); // explicit interface member names include the explicit interface var mems = classImpl.GetMembers("M"); Assert.Equal(0, mems.Length); //var mem1 = mems.First() as MethodSymbol; // not impl // Assert.Equal(MethodKind.ExplicitInterfaceImplementation, mem1.MethodKind); // Assert.Equal(1, mem1.ExplicitInterfaceImplementation.Count()); var mem1 = classImpl.GetMembers("M22").Single() as MethodSymbol; // not impl // Assert.Equal(0, mem1.ExplicitInterfaceImplementation.Count()); var param = mem1.Parameters.First() as ParameterSymbol; Assert.Equal(RefKind.Ref, param.RefKind); Assert.Equal("ref NS.Abc p", param.ToTestDisplayString()); var structImpl = ns1.GetTypeMembers("S").Single() as NamedTypeSymbol; Assert.Equal(1, structImpl.Interfaces().Length); itfc = structImpl.Interfaces().First() as NamedTypeSymbol; Assert.Equal("NS.IGoo<T>", itfc.ToTestDisplayString()); //var mem2 = structImpl.GetMembers("M").Single() as MethodSymbol; // not impl // Assert.Equal(1, mem2.ExplicitInterfaceImplementation.Count()); } [Fact] public void AbstractVirtualMethodsCrossTrees() { var text = @" namespace MT { public interface IGoo { void M0(); } } "; var text1 = @" namespace N1 { using MT; public abstract class Abc : IGoo { public abstract void M0(); public char M1; public abstract object M2(ref object p1); public virtual void M3(ulong p1, out ulong p2) { p2 = p1; } public virtual object M4(params object[] ary) { return null; } public static void M5<T>(T t) { } public abstract ref int M6(ref int i); } } "; var text2 = @" namespace N1.N2 { public class Bbc : Abc { public override void M0() { } public override object M2(ref object p1) { M1 = 'a'; return p1; } public sealed override void M3(ulong p1, out ulong p2) { p2 = p1; } public override object M4(params object[] ary) { return null; } public static new void M5<T>(T t) { } public override ref int M6(ref int i) { return ref i; } } } "; var comp = CreateCompilationWithMscorlib45(new[] { text, text1, text2 }); Assert.Equal(0, comp.GetDiagnostics().Count()); var ns = comp.GlobalNamespace.GetMembers("N1").Single() as NamespaceSymbol; var ns1 = ns.GetMembers("N2").Single() as NamespaceSymbol; #region "Bbc" var type1 = ns1.GetTypeMembers("Bbc", 0).Single() as NamedTypeSymbol; var mems = type1.GetMembers(); Assert.Equal(7, mems.Length); // var sorted = mems.Orderby(m => m.Name).ToArray(); var sorted = (from m in mems orderby m.Name select m).ToArray(); var m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); Assert.False(m0.IsAbstract); Assert.False(m0.IsOverride); Assert.False(m0.IsSealed); Assert.False(m0.IsVirtual); var m1 = sorted[1] as MethodSymbol; Assert.Equal("M0", m1.Name); Assert.False(m1.IsAbstract); Assert.True(m1.IsOverride); Assert.False(m1.IsSealed); Assert.False(m1.IsVirtual); var m2 = sorted[2] as MethodSymbol; Assert.Equal("M2", m2.Name); Assert.False(m2.IsAbstract); Assert.True(m2.IsOverride); Assert.False(m2.IsSealed); Assert.False(m2.IsVirtual); var m3 = sorted[3] as MethodSymbol; Assert.Equal("M3", m3.Name); Assert.False(m3.IsAbstract); Assert.True(m3.IsOverride); Assert.True(m3.IsSealed); Assert.False(m3.IsVirtual); var m4 = sorted[4] as MethodSymbol; Assert.Equal("M4", m4.Name); Assert.False(m4.IsAbstract); Assert.True(m4.IsOverride); Assert.False(m4.IsSealed); Assert.False(m4.IsVirtual); var m5 = sorted[5] as MethodSymbol; Assert.Equal("M5", m5.Name); Assert.False(m5.IsAbstract); Assert.False(m5.IsOverride); Assert.False(m5.IsSealed); Assert.False(m5.IsVirtual); Assert.True(m5.IsStatic); var m6 = sorted[6] as MethodSymbol; Assert.Equal("M6", m6.Name); Assert.False(m6.IsAbstract); Assert.True(m6.IsOverride); Assert.False(m6.IsSealed); Assert.False(m6.IsVirtual); #endregion #region "Abc" var type2 = type1.BaseType(); Assert.Equal("Abc", type2.Name); mems = type2.GetMembers(); Assert.Equal(8, mems.Length); sorted = (from m in mems orderby m.Name select m).ToArray(); var mm = sorted[2] as FieldSymbol; Assert.Equal("M1", mm.Name); Assert.False(mm.IsAbstract); Assert.False(mm.IsOverride); Assert.False(mm.IsSealed); Assert.False(mm.IsVirtual); m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); Assert.Equal(Accessibility.Protected, m0.DeclaredAccessibility); m1 = sorted[1] as MethodSymbol; Assert.Equal("M0", m1.Name); Assert.True(m1.IsAbstract); Assert.False(m1.IsOverride); Assert.False(m1.IsSealed); Assert.False(m1.IsVirtual); m2 = sorted[3] as MethodSymbol; Assert.Equal("M2", m2.Name); Assert.True(m2.IsAbstract); Assert.False(m2.IsOverride); Assert.False(m2.IsSealed); Assert.False(m2.IsVirtual); m3 = sorted[4] as MethodSymbol; Assert.Equal("M3", m3.Name); Assert.False(m3.IsAbstract); Assert.False(m3.IsOverride); Assert.False(m3.IsSealed); Assert.True(m3.IsVirtual); m4 = sorted[5] as MethodSymbol; Assert.Equal("M4", m4.Name); Assert.False(m4.IsAbstract); Assert.False(m4.IsOverride); Assert.False(m4.IsSealed); Assert.True(m4.IsVirtual); m5 = sorted[6] as MethodSymbol; Assert.Equal("M5", m5.Name); Assert.False(m5.IsAbstract); Assert.False(m5.IsOverride); Assert.False(m5.IsSealed); Assert.False(m5.IsVirtual); Assert.True(m5.IsStatic); m6 = sorted[7] as MethodSymbol; Assert.Equal("M6", m6.Name); Assert.True(m6.IsAbstract); Assert.False(m6.IsOverride); Assert.False(m6.IsSealed); Assert.False(m6.IsVirtual); #endregion } [WorkItem(537752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537752")] [Fact] public void AbstractVirtualMethodsCrossComps() { var text = @" namespace MT { public interface IGoo { void M0(); } } "; var text1 = @" namespace N1 { using MT; public abstract class Abc : IGoo { public abstract void M0(); public char M1; public abstract object M2(ref object p1); public virtual void M3(ulong p1, out ulong p2) { p2 = p1; } public virtual object M4(params object[] ary) { return null; } public static void M5<T>(T t) { } public abstract ref int M6(ref int i); } } "; var text2 = @" namespace N1.N2 { public class Bbc : Abc { public override void M0() { } public override object M2(ref object p1) { M1 = 'a'; return p1; } public sealed override void M3(ulong p1, out ulong p2) { p2 = p1; } public override object M4(params object[] ary) { return null; } public static new void M5<T>(T t) { } public override ref int M6(ref int i) { return ref i; } } } "; var comp1 = CreateCompilationWithMscorlib45(text); var compRef1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilationWithMscorlib45(new string[] { text1 }, new List<MetadataReference>() { compRef1 }, assemblyName: "Test2"); //Compilation.Create(outputName: "Test2", options: CompilationOptions.Default, // syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text1) }, // references: new MetadataReference[] { compRef1, GetCorlibReference() }); var compRef2 = new CSharpCompilationReference(comp2); var comp = CreateCompilationWithMscorlib45(new string[] { text2 }, new List<MetadataReference>() { compRef1, compRef2 }, assemblyName: "Test3"); //Compilation.Create(outputName: "Test3", options: CompilationOptions.Default, // syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text2) }, // references: new MetadataReference[] { compRef1, compRef2, GetCorlibReference() }); Assert.Equal(0, comp1.GetDiagnostics().Count()); Assert.Equal(0, comp2.GetDiagnostics().Count()); Assert.Equal(0, comp.GetDiagnostics().Count()); //string errs = String.Empty; //foreach (var e in comp.GetDiagnostics()) //{ // errs += e.Info.ToString() + "\r\n"; //} //Assert.Equal("Errs", errs); var ns = comp.GlobalNamespace.GetMembers("N1").Single() as NamespaceSymbol; var ns1 = ns.GetMembers("N2").Single() as NamespaceSymbol; #region "Bbc" var type1 = ns1.GetTypeMembers("Bbc", 0).Single() as NamedTypeSymbol; var mems = type1.GetMembers(); Assert.Equal(7, mems.Length); // var sorted = mems.Orderby(m => m.Name).ToArray(); var sorted = (from m in mems orderby m.Name select m).ToArray(); var m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); Assert.False(m0.IsAbstract); Assert.False(m0.IsOverride); Assert.False(m0.IsSealed); Assert.False(m0.IsVirtual); var m1 = sorted[1] as MethodSymbol; Assert.Equal("M0", m1.Name); Assert.False(m1.IsAbstract); Assert.True(m1.IsOverride); Assert.False(m1.IsSealed); Assert.False(m1.IsVirtual); var m2 = sorted[2] as MethodSymbol; Assert.Equal("M2", m2.Name); Assert.False(m2.IsAbstract); Assert.True(m2.IsOverride); Assert.False(m2.IsSealed); Assert.False(m2.IsVirtual); var m3 = sorted[3] as MethodSymbol; Assert.Equal("M3", m3.Name); Assert.False(m3.IsAbstract); Assert.True(m3.IsOverride); Assert.True(m3.IsSealed); Assert.False(m3.IsVirtual); var m4 = sorted[4] as MethodSymbol; Assert.Equal("M4", m4.Name); Assert.False(m4.IsAbstract); Assert.True(m4.IsOverride); Assert.False(m4.IsSealed); Assert.False(m4.IsVirtual); var m5 = sorted[5] as MethodSymbol; Assert.Equal("M5", m5.Name); Assert.False(m5.IsAbstract); Assert.False(m5.IsOverride); Assert.False(m5.IsSealed); Assert.False(m5.IsVirtual); Assert.True(m5.IsStatic); var m6 = sorted[6] as MethodSymbol; Assert.Equal("M6", m6.Name); Assert.False(m6.IsAbstract); Assert.True(m6.IsOverride); Assert.False(m6.IsSealed); Assert.False(m6.IsVirtual); #endregion #region "Abc" var type2 = type1.BaseType(); Assert.Equal("Abc", type2.Name); mems = type2.GetMembers(); Assert.Equal(8, mems.Length); sorted = (from m in mems orderby m.Name select m).ToArray(); var mm = sorted[2] as FieldSymbol; Assert.Equal("M1", mm.Name); Assert.False(mm.IsAbstract); Assert.False(mm.IsOverride); Assert.False(mm.IsSealed); Assert.False(mm.IsVirtual); m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); Assert.False(m0.IsAbstract); Assert.False(m0.IsOverride); Assert.False(m0.IsSealed); Assert.False(m0.IsVirtual); m1 = sorted[1] as MethodSymbol; Assert.Equal("M0", m1.Name); Assert.True(m1.IsAbstract); Assert.False(m1.IsOverride); Assert.False(m1.IsSealed); Assert.False(m1.IsVirtual); m2 = sorted[3] as MethodSymbol; Assert.Equal("M2", m2.Name); Assert.True(m2.IsAbstract); Assert.False(m2.IsOverride); Assert.False(m2.IsSealed); Assert.False(m2.IsVirtual); m3 = sorted[4] as MethodSymbol; Assert.Equal("M3", m3.Name); Assert.False(m3.IsAbstract); Assert.False(m3.IsOverride); Assert.False(m3.IsSealed); Assert.True(m3.IsVirtual); m4 = sorted[5] as MethodSymbol; Assert.Equal("M4", m4.Name); Assert.False(m4.IsAbstract); Assert.False(m4.IsOverride); Assert.False(m4.IsSealed); Assert.True(m4.IsVirtual); m5 = sorted[6] as MethodSymbol; Assert.Equal("M5", m5.Name); Assert.False(m5.IsAbstract); Assert.False(m5.IsOverride); Assert.False(m5.IsSealed); Assert.False(m5.IsVirtual); Assert.True(m5.IsStatic); m6 = sorted[7] as MethodSymbol; Assert.Equal("M6", m6.Name); Assert.True(m6.IsAbstract); Assert.False(m6.IsOverride); Assert.False(m6.IsSealed); Assert.False(m6.IsVirtual); #endregion } [Fact] public void OverloadMethodsCrossTrees() { var text = @" using System; namespace NS { public class A { public void Overloads(ushort p) { } public void Overloads(A p) { } } } "; var text1 = @" namespace NS { using System; public class B : A { public void Overloads(ref A p) { } public string Overloads(B p) { return null; } protected long Overloads(A p, long p2) { return p2; } } } "; var text2 = @" namespace NS { public class Test { public class C : B { protected long Overloads(A p, B p2) { return 1; } } public static void Main() { var obj = new C(); A a = obj; obj.Overloads(ref a); obj.Overloads(obj); } } } "; var comp = CreateCompilation(new[] { text, text1, text2 }); // Not impl errors // Assert.Equal(0, comp.GetDiagnostics().Count()); var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = (ns.GetTypeMembers("Test").Single() as NamedTypeSymbol).GetTypeMembers("C", 0).Single() as NamedTypeSymbol; Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); var mems = type1.GetMembers(); Assert.Equal(2, mems.Length); var mems1 = type1.BaseType().GetMembers(); Assert.Equal(4, mems1.Length); var mems2 = type1.BaseType().BaseType().GetMembers(); Assert.Equal(3, mems2.Length); var list = new List<Symbol>(); list.AddRange(mems); list.AddRange(mems1); list.AddRange(mems2); var sorted = (from m in list orderby m.Name select m).ToArray(); var m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); m0 = sorted[1] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); m0 = sorted[2] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); var m1 = sorted[3] as MethodSymbol; Assert.Equal("System.Int64 NS.Test.C.Overloads(NS.A p, NS.B p2)", m1.ToTestDisplayString()); m1 = sorted[4] as MethodSymbol; Assert.Equal("void NS.B.Overloads(ref NS.A p)", m1.ToTestDisplayString()); m1 = sorted[5] as MethodSymbol; Assert.Equal("System.String NS.B.Overloads(NS.B p)", m1.ToTestDisplayString()); m1 = sorted[6] as MethodSymbol; Assert.Equal("System.Int64 NS.B.Overloads(NS.A p, System.Int64 p2)", m1.ToTestDisplayString()); m1 = sorted[7] as MethodSymbol; Assert.Equal("void NS.A.Overloads(System.UInt16 p)", m1.ToTestDisplayString()); m1 = sorted[8] as MethodSymbol; Assert.Equal("void NS.A.Overloads(NS.A p)", m1.ToTestDisplayString()); } [WorkItem(537752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537752")] [Fact] public void OverloadMethodsCrossComps() { var text = @" namespace NS { public class A { public void Overloads(ushort p) { } public void Overloads(A p) { } } } "; var text1 = @" namespace NS { public class B : A { public void Overloads(ref A p) { } public string Overloads(B p) { return null; } protected long Overloads(A p, long p2) { return p2; } } } "; var text2 = @" namespace NS { public class Test { public class C : B { protected long Overloads(A p, B p2) { return 1; } } public static void Main() { C obj = new C(); // var NotImpl ??? A a = obj; obj.Overloads(ref a); obj.Overloads(obj); } } } "; var comp1 = CreateCompilation(text); var compRef1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilation(new string[] { text1 }, new List<MetadataReference>() { compRef1 }, assemblyName: "Test2"); //Compilation.Create(outputName: "Test2", options: CompilationOptions.Default, // syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text1) }, // references: new MetadataReference[] { compRef1, GetCorlibReference() }); var compRef2 = new CSharpCompilationReference(comp2); var comp = CreateCompilation(new string[] { text2 }, new List<MetadataReference>() { compRef1, compRef2 }, assemblyName: "Test3"); //Compilation.Create(outputName: "Test3", options: CompilationOptions.Default, // syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text2) }, // references: new MetadataReference[] { compRef1, compRef2, GetCorlibReference() }); Assert.Equal(0, comp1.GetDiagnostics().Count()); Assert.Equal(0, comp2.GetDiagnostics().Count()); Assert.Equal(0, comp.GetDiagnostics().Count()); //string errs = String.Empty; //foreach (var e in comp.GetDiagnostics()) //{ // errs += e.Info.ToString() + "\r\n"; //} //Assert.Equal(String.Empty, errs); var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = (ns.GetTypeMembers("Test").Single() as NamedTypeSymbol).GetTypeMembers("C", 0).Single() as NamedTypeSymbol; Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); var mems = type1.GetMembers(); Assert.Equal(2, mems.Length); var mems1 = type1.BaseType().GetMembers(); Assert.Equal(4, mems1.Length); var mems2 = type1.BaseType().BaseType().GetMembers(); Assert.Equal(3, mems2.Length); var list = new List<Symbol>(); list.AddRange(mems); list.AddRange(mems1); list.AddRange(mems2); var sorted = (from m in list orderby m.Name select m).ToArray(); var m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); m0 = sorted[1] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); m0 = sorted[2] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); var m1 = sorted[3] as MethodSymbol; Assert.Equal("System.Int64 NS.Test.C.Overloads(NS.A p, NS.B p2)", m1.ToTestDisplayString()); m1 = sorted[4] as MethodSymbol; Assert.Equal("void NS.B.Overloads(ref NS.A p)", m1.ToTestDisplayString()); m1 = sorted[5] as MethodSymbol; Assert.Equal("System.String NS.B.Overloads(NS.B p)", m1.ToTestDisplayString()); m1 = sorted[6] as MethodSymbol; Assert.Equal("System.Int64 NS.B.Overloads(NS.A p, System.Int64 p2)", m1.ToTestDisplayString()); m1 = sorted[7] as MethodSymbol; Assert.Equal("void NS.A.Overloads(System.UInt16 p)", m1.ToTestDisplayString()); m1 = sorted[8] as MethodSymbol; Assert.Equal("void NS.A.Overloads(NS.A p)", m1.ToTestDisplayString()); } [WorkItem(537754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537754")] [Fact] public void PartialMethodsCrossTrees() { var text = @" namespace NS { public partial struct PS { partial void M0(string p); partial class GPC<T> { partial void GM0(T p1, short p2); } } } "; var text1 = @" namespace NS { partial struct PS { partial void M0(string p) { } partial void M1(params ulong[] ary); public partial class GPC<T> { partial void GM0(T p1, short p2) { } partial void GM1<V>(T p1, V p2); } } } "; var text2 = @" namespace NS { partial struct PS { partial void M1(params ulong[] ary) {} partial void M2(sbyte p); partial class GPC<T> { partial void GM1<V>(T p1, V p2) { } } } } "; var comp = CreateCompilation(new[] { text, text1, text2 }); Assert.Equal(0, comp.GetDiagnostics().Count()); var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("PS", 0).Single() as NamedTypeSymbol; // Bug // Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.Equal(3, type1.Locations.Length); Assert.False(type1.IsReferenceType); Assert.True(type1.IsValueType); var mems = type1.GetMembers(); Assert.Equal(5, mems.Length); var sorted = (from m in mems orderby m.Name select m).ToArray(); var m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); Assert.Equal(Accessibility.Public, m0.DeclaredAccessibility); Assert.Equal(3, m0.Locations.Length); var m2 = sorted[2] as MethodSymbol; Assert.Equal("M0", m2.Name); Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility); Assert.Equal(1, m2.Locations.Length); Assert.True(m2.ReturnsVoid); var m3 = sorted[3] as MethodSymbol; Assert.Equal("M1", m3.Name); Assert.Equal(Accessibility.Private, m3.DeclaredAccessibility); Assert.Equal(1, m3.Locations.Length); var m4 = sorted[4] as MethodSymbol; Assert.Equal("M2", m4.Name); Assert.Equal(Accessibility.Private, m4.DeclaredAccessibility); Assert.Equal(1, m4.Locations.Length); #region "GPC" var type2 = sorted[1] as NamedTypeSymbol; Assert.Equal("NS.PS.GPC<T>", type2.ToTestDisplayString()); Assert.True(type2.IsNestedType()); // Bug Assert.Equal(Accessibility.Public, type2.DeclaredAccessibility); Assert.Equal(3, type2.Locations.Length); Assert.False(type2.IsValueType); Assert.True(type2.IsReferenceType); mems = type2.GetMembers(); // Assert.Equal(3, mems.Count()); sorted = (from m in mems orderby m.Name select m).ToArray(); m0 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name); Assert.Equal(Accessibility.Public, m0.DeclaredAccessibility); Assert.Equal(3, m0.Locations.Length); var mm = sorted[1] as MethodSymbol; Assert.Equal("GM0", mm.Name); Assert.Equal(Accessibility.Private, mm.DeclaredAccessibility); Assert.Equal(1, mm.Locations.Length); m2 = sorted[2] as MethodSymbol; Assert.Equal("GM1", m2.Name); Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility); Assert.Equal(1, m2.Locations.Length); Assert.True(m2.ReturnsVoid); #endregion } [WorkItem(537755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537755")] [Fact] public void PartialMethodsWithRefParams() { var text = @" namespace NS { public partial class PC { partial void M0(ref long p); partial void M1(ref string p); } partial class PC { partial void M0(ref long p) {} partial void M1(ref string p) {} } } "; var comp = CreateCompilation(text); Assert.Equal(0, comp.GetDiagnostics().Count()); var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("PC", 0).Single() as NamedTypeSymbol; Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.Equal(2, type1.Locations.Length); Assert.True(type1.IsReferenceType); Assert.False(type1.IsValueType); var mems = type1.GetMembers(); // Bug: actual 5 Assert.Equal(3, mems.Length); var sorted = (from m in mems orderby m.Name select m).ToArray(); var m1 = sorted[0] as MethodSymbol; Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m1.Name); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Equal(2, m1.Locations.Length); var m2 = sorted[1] as MethodSymbol; Assert.Equal("M0", m2.Name); Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility); Assert.Equal(1, m2.Locations.Length); Assert.True(m2.ReturnsVoid); var m3 = sorted[2] as MethodSymbol; Assert.Equal("M1", m3.Name); Assert.Equal(Accessibility.Private, m3.DeclaredAccessibility); Assert.Equal(1, m3.Locations.Length); Assert.True(m3.ReturnsVoid); } [WorkItem(2358, "DevDiv_Projects/Roslyn")] [Fact] public void ExplicitInterfaceImplementation() { var text = @" interface ISubFuncProp { } interface Interface3 { System.Collections.Generic.List<ISubFuncProp> Goo(); } interface Interface3Derived : Interface3 { } public class DerivedClass : Interface3Derived { System.Collections.Generic.List<ISubFuncProp> Interface3.Goo() { return null; } System.Collections.Generic.List<ISubFuncProp> Goo() { return null; } }"; var comp = CreateCompilation(text); var derivedClass = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("DerivedClass")[0]; var members = derivedClass.GetMembers(); Assert.Equal(3, members.Length); } [Fact] public void SubstitutedExplicitInterfaceImplementation() { var text = @" public class A<T> { public interface I<U> { void M<V>(T t, U u, V v); } } public class B<Q, R> : A<Q>.I<R> { void A<Q>.I<R>.M<S>(Q q, R r, S s) { } } public class C : B<int, long> { }"; var comp = CreateCompilation(text); var classB = (NamedTypeSymbol)comp.GlobalNamespace.GetMembers("B").Single(); var classBTypeArguments = classB.TypeArguments(); Assert.Equal(2, classBTypeArguments.Length); Assert.Equal("Q", classBTypeArguments[0].Name); Assert.Equal("R", classBTypeArguments[1].Name); var classBMethodM = (MethodSymbol)classB.GetMembers().Single(sym => sym.Name.EndsWith("M", StringComparison.Ordinal)); var classBMethodMTypeParameters = classBMethodM.TypeParameters; Assert.Equal(1, classBMethodMTypeParameters.Length); Assert.Equal("S", classBMethodMTypeParameters[0].Name); var classBMethodMParameters = classBMethodM.Parameters; Assert.Equal(3, classBMethodMParameters.Length); Assert.Equal(classBTypeArguments[0], classBMethodMParameters[0].Type); Assert.Equal(classBTypeArguments[1], classBMethodMParameters[1].Type); Assert.Equal(classBMethodMTypeParameters[0], classBMethodMParameters[2].Type); var classC = (NamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").Single(); var classCBase = classC.BaseType(); Assert.Equal(classB, classCBase.ConstructedFrom); var classCBaseTypeArguments = classCBase.TypeArguments(); Assert.Equal(2, classCBaseTypeArguments.Length); Assert.Equal(SpecialType.System_Int32, classCBaseTypeArguments[0].SpecialType); Assert.Equal(SpecialType.System_Int64, classCBaseTypeArguments[1].SpecialType); var classCBaseMethodM = (MethodSymbol)classCBase.GetMembers().Single(sym => sym.Name.EndsWith("M", StringComparison.Ordinal)); Assert.NotEqual(classBMethodM, classCBaseMethodM); var classCBaseMethodMTypeParameters = classCBaseMethodM.TypeParameters; Assert.Equal(1, classCBaseMethodMTypeParameters.Length); Assert.Equal("S", classCBaseMethodMTypeParameters[0].Name); var classCBaseMethodMParameters = classCBaseMethodM.Parameters; Assert.Equal(3, classCBaseMethodMParameters.Length); Assert.Equal(classCBaseTypeArguments[0], classCBaseMethodMParameters[0].Type); Assert.Equal(classCBaseTypeArguments[1], classCBaseMethodMParameters[1].Type); Assert.Equal(classCBaseMethodMTypeParameters[0], classCBaseMethodMParameters[2].Type); } #region Regressions [WorkItem(527149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527149")] [Fact] public void MethodWithParamsInParameters() { var text = @"class C { void F1(params int[] a) { } } "; var comp = CreateEmptyCompilation(text); var c = comp.GlobalNamespace.GetTypeMembers("C").Single(); var f1 = c.GetMembers("F1").Single() as MethodSymbol; Assert.Equal("void C.F1(params System.Int32[missing][] a)", f1.ToTestDisplayString()); } [WorkItem(537352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537352")] [Fact] public void Arglist() { string code = @" class AA { public static int Method1(__arglist) { } }"; var comp = CreateCompilation(code); NamedTypeSymbol nts = comp.Assembly.GlobalNamespace.GetTypeMembers()[0]; Assert.Equal("AA", nts.ToTestDisplayString()); Assert.Empty(comp.GetDeclarationDiagnostics()); Assert.Equal("System.Int32 AA.Method1(__arglist)", nts.GetMembers("Method1").Single().ToTestDisplayString()); } [WorkItem(537877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537877")] [Fact] public void ExpImpInterfaceWithGlobal() { var text = @" using System; namespace N1 { interface I1 { int Method(); } } namespace N2 { class ExpImpl : N1.I1 { int global::N1.I1.Method() { return 42; } ExpImpl(){} } } "; var comp = CreateCompilation(text); Assert.Equal(0, comp.GetDeclarationDiagnostics().Count()); var ns = comp.GlobalNamespace.GetMembers("N2").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("ExpImpl", 0).Single() as NamedTypeSymbol; var m1 = type1.GetMembers().FirstOrDefault() as MethodSymbol; Assert.Equal("System.Int32 N2.ExpImpl.N1.I1.Method()", m1.ToTestDisplayString()); var em1 = m1.ExplicitInterfaceImplementations.First() as MethodSymbol; Assert.Equal("System.Int32 N1.I1.Method()", em1.ToTestDisplayString()); } [WorkItem(537877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537877")] [Fact] public void BaseInterfaceNameWithAlias() { var text = @" using N1Alias = N1; namespace N1 { interface I1 {} } namespace N2 { class N1Alias {} class Test : N1Alias::I1 { static int Main() { Test t = new Test(); return 0; } } } "; var comp = CreateCompilation(text); Assert.Equal(0, comp.GetDeclarationDiagnostics().Count()); var n2 = comp.GlobalNamespace.GetMembers("N2").Single() as NamespaceSymbol; var test = n2.GetTypeMembers("Test").Single() as NamedTypeSymbol; var bt = test.Interfaces().Single() as NamedTypeSymbol; Assert.Equal("N1.I1", bt.ToTestDisplayString()); } [WorkItem(538209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538209")] [Fact] public void ParameterAccessibility01() { var text = @" using System; class MyClass { private class MyInner { public int MyMeth(MyInner2 arg) { return arg.intI; } } protected class MyInner2 { public int intI = 2; } public static int Main() { MyInner MI = new MyInner(); if (MI.MyMeth(new MyInner2()) == 2) { return 0; } else { return 1; } } } "; var comp = CreateCompilation(text); Assert.Equal(0, comp.GetDeclarationDiagnostics().Count()); } [WorkItem(537877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537877")] [Fact] public void MethodsWithSameSigDiffReturnType() { var text = @" class Test { public int M1() { } float M1() { } } "; var comp = CreateCompilation(text); var test = comp.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol; var members = test.GetMembers("M1"); Assert.Equal(2, members.Length); Assert.Equal("System.Int32 Test.M1()", members[0].ToTestDisplayString()); Assert.Equal("System.Single Test.M1()", members[1].ToTestDisplayString()); } [Fact] public void OverriddenMethod01() { var text = @" class A { public virtual void F(object[] args) {} } class B : A { public override void F(params object[] args) {} public static void Main(B b) { b.F(// yes, there is a parse error here } } "; var comp = CreateCompilation(text); var a = comp.GlobalNamespace.GetTypeMembers("A").Single() as NamedTypeSymbol; var b = comp.GlobalNamespace.GetTypeMembers("B").Single() as NamedTypeSymbol; var f = b.GetMembers("F").Single() as MethodSymbol; Assert.True(f.IsOverride); var f2 = f.OverriddenMethod; Assert.NotNull(f2); Assert.Equal("A", f2.ContainingSymbol.Name); } #endregion [WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")] [Fact] public void MethodEscapedIdentifier() { var text = @" interface @void { @void @return(@void @in); }; class @int { virtual @int @float(@int @in); }; class C1 : @int, @void { @void @void.@return(@void @in) { return null; } override @int @float(@int @in) { return null; } } "; var comp = CreateCompilation(Parse(text)); NamedTypeSymbol c1 = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("C1").Single(); // Per explanation from NGafter: // // We intentionally escape keywords that appear in the type qualification of the interface name // on interface implementation members. That is necessary to distinguish I<int>.F from I<@int>.F, // for example, which might both be members in a class. An alternative would be to stop using the // abbreviated names for the built-in types, but since we may want to use these names in // diagnostics the @-escaped version is preferred. // MethodSymbol mreturn = (MethodSymbol)c1.GetMembers("@void.return").Single(); Assert.Equal("@void.return", mreturn.Name); Assert.Equal("C1.@void.@return(@void)", mreturn.ToString()); NamedTypeSymbol rvoid = (NamedTypeSymbol)mreturn.ReturnType; Assert.Equal("void", rvoid.Name); Assert.Equal("@void", rvoid.ToString()); MethodSymbol mvoidreturn = (MethodSymbol)mreturn.ExplicitInterfaceImplementations.Single(); Assert.Equal("return", mvoidreturn.Name); Assert.Equal("@void.@return(@void)", mvoidreturn.ToString()); ParameterSymbol pin = mreturn.Parameters.Single(); Assert.Equal("in", pin.Name); Assert.Equal("@in", pin.ToDisplayString( new SymbolDisplayFormat( parameterOptions: SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers))); MethodSymbol mfloat = (MethodSymbol)c1.GetMembers("float").Single(); Assert.Equal("float", mfloat.Name); Assert.Empty(c1.GetMembers("@float")); } [Fact] public void ExplicitInterfaceImplementationSimple() { string text = @" interface I { void Method(); } class C : I { void I.Method() { } } "; var comp = CreateCompilation(Parse(text)); var globalNamespace = comp.GlobalNamespace; var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.True(@class.Interfaces().Contains(@interface)); var classMethod = (MethodSymbol)@class.GetMembers("I.Method").Single(); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind); var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single(); Assert.Equal(interfaceMethod, explicitImpl); var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single(); Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol()); Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod.GetInternalSymbol()); context.Diagnostics.Verify(); } [Fact] public void ExplicitInterfaceImplementationCorLib() { string text = @" class F : System.IFormattable { string System.IFormattable.ToString(string format, System.IFormatProvider formatProvider) { return null; } } "; var comp = CreateCompilation(Parse(text)); var globalNamespace = comp.GlobalNamespace; var systemNamespace = (NamespaceSymbol)globalNamespace.GetMembers("System").Single(); var @interface = (NamedTypeSymbol)systemNamespace.GetTypeMembers("IFormattable").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceMethod = (MethodSymbol)@interface.GetMembers("ToString").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("F").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.True(@class.Interfaces().Contains(@interface)); var classMethod = (MethodSymbol)@class.GetMembers("System.IFormattable.ToString").Single(); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind); var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single(); Assert.Equal(interfaceMethod, explicitImpl); var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single(); Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol()); Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod.GetInternalSymbol()); context.Diagnostics.Verify(); } [Fact] public void ExplicitInterfaceImplementationRef() { string text = @" interface I { ref int Method(ref int i); } class C : I { ref int I.Method(ref int i) { return ref i; } } "; var comp = CreateCompilationWithMscorlib45(text); var globalNamespace = comp.GlobalNamespace; var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single(); Assert.Equal(RefKind.Ref, interfaceMethod.RefKind); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.True(@class.Interfaces().Contains(@interface)); var classMethod = (MethodSymbol)@class.GetMembers("I.Method").Single(); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind); Assert.Equal(RefKind.Ref, classMethod.RefKind); var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single(); Assert.Equal(interfaceMethod, explicitImpl); var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single(); Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol()); Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod.GetInternalSymbol()); context.Diagnostics.Verify(); } [Fact] public void ExplicitInterfaceImplementationGeneric() { string text = @" namespace Namespace { interface I<T> { void Method(T t); } } class IC : Namespace.I<int> { void Namespace.I<int>.Method(int i) { } } "; var comp = CreateCompilation(Parse(text)); var globalNamespace = comp.GlobalNamespace; var systemNamespace = (NamespaceSymbol)globalNamespace.GetMembers("Namespace").Single(); var @interface = (NamedTypeSymbol)systemNamespace.GetTypeMembers("I", 1).Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IC").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); var substitutedInterface = @class.Interfaces().Single(); Assert.Equal(@interface, substitutedInterface.ConstructedFrom); var substitutedInterfaceMethod = (MethodSymbol)substitutedInterface.GetMembers("Method").Single(); var classMethod = (MethodSymbol)@class.GetMembers("Namespace.I<System.Int32>.Method").Single(); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind); var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single(); Assert.Equal(substitutedInterface, explicitImpl.ContainingType); Assert.Equal(substitutedInterfaceMethod.OriginalDefinition, explicitImpl.OriginalDefinition); var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single(); Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol()); Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol()); var explicitOverrideImplementedMethod = explicitOverride.ImplementedMethod; Assert.Equal(substitutedInterface, explicitOverrideImplementedMethod.GetContainingType(context).GetInternalSymbol()); Assert.Equal(substitutedInterfaceMethod.Name, explicitOverrideImplementedMethod.Name); Assert.Equal(substitutedInterfaceMethod.Arity, explicitOverrideImplementedMethod.GenericParameterCount); context.Diagnostics.Verify(); } [Fact()] public void TestMetadataVirtual() { string text = @" class C { virtual void Method1() { } virtual void Method2() { } void Method3() { } void Method4() { } } "; var comp = CreateCompilation(Parse(text)); var @class = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("C").Single(); var method1 = (SourceMemberMethodSymbol)@class.GetMembers("Method1").Single(); var method2 = (SourceMemberMethodSymbol)@class.GetMembers("Method2").Single(); var method3 = (SourceMemberMethodSymbol)@class.GetMembers("Method3").Single(); var method4 = (SourceMemberMethodSymbol)@class.GetMembers("Method4").Single(); Assert.True(method1.IsVirtual); Assert.True(method2.IsVirtual); Assert.False(method3.IsVirtual); Assert.False(method4.IsVirtual); //1 and 3 - read before set Assert.True(((Cci.IMethodDefinition)method1.GetCciAdapter()).IsVirtual); Assert.False(((Cci.IMethodDefinition)method3.GetCciAdapter()).IsVirtual); //2 and 4 - set before read method2.EnsureMetadataVirtual(); method4.EnsureMetadataVirtual(); //can set twice (e.g. if the method implicitly implements more than one interface method) method2.EnsureMetadataVirtual(); method4.EnsureMetadataVirtual(); Assert.True(((Cci.IMethodDefinition)method2.GetCciAdapter()).IsVirtual); Assert.True(((Cci.IMethodDefinition)method4.GetCciAdapter()).IsVirtual); //API view unchanged Assert.True(method1.IsVirtual); Assert.True(method2.IsVirtual); Assert.False(method3.IsVirtual); Assert.False(method4.IsVirtual); } [Fact] public void ExplicitStaticConstructor() { string text = @" class C { static C() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); var staticConstructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.StaticConstructorName); Assert.Equal(MethodKind.StaticConstructor, staticConstructor.MethodKind); Assert.Equal(Accessibility.Private, staticConstructor.DeclaredAccessibility); Assert.True(staticConstructor.IsStatic, "Static constructor should be static"); Assert.Equal(SpecialType.System_Void, staticConstructor.ReturnType.SpecialType); } [Fact] public void ImplicitStaticConstructor() { string text = @" class C { static int f = 1; //initialized in implicit static constructor } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,16): warning CS0414: The field 'C.f' is assigned but its value is never used // static int f = 1; //initialized in implicit static constructor Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "f").WithArguments("C.f") ); var staticConstructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.StaticConstructorName); Assert.Equal(MethodKind.StaticConstructor, staticConstructor.MethodKind); Assert.Equal(Accessibility.Private, staticConstructor.DeclaredAccessibility); Assert.True(staticConstructor.IsStatic, "Static constructor should be static"); Assert.Equal(SpecialType.System_Void, staticConstructor.ReturnType.SpecialType); } [WorkItem(541834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541834")] [Fact] public void AccessorMethodAccessorOverriding() { var text = @" public class A { public virtual int P { get; set; } } public class B : A { public virtual int get_P() { return 0; } } public class C : B { public override int P { get; set; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); var globalNamespace = comp.GlobalNamespace; var classA = globalNamespace.GetMember<NamedTypeSymbol>("A"); var classB = globalNamespace.GetMember<NamedTypeSymbol>("B"); var classC = globalNamespace.GetMember<NamedTypeSymbol>("C"); var methodA = classA.GetMember<PropertySymbol>("P").GetMethod; var methodB = classB.GetMember<MethodSymbol>("get_P"); var methodC = classC.GetMember<PropertySymbol>("P").GetMethod; var typeDefC = (Cci.ITypeDefinition)classC.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)classC.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverride = typeDefC.GetExplicitImplementationOverrides(context).Single(); Assert.Equal(classC, explicitOverride.ContainingType.GetInternalSymbol()); Assert.Equal(methodC, explicitOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(methodA, explicitOverride.ImplementedMethod.GetInternalSymbol()); context.Diagnostics.Verify(); } [WorkItem(541834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541834")] [Fact] public void MethodAccessorMethodOverriding() { var text = @" public class A { public virtual int get_P() { return 0; } } public class B : A { public virtual int P { get; set; } } public class C : B { public override int get_P() { return 0; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); var globalNamespace = comp.GlobalNamespace; var classA = globalNamespace.GetMember<NamedTypeSymbol>("A"); var classB = globalNamespace.GetMember<NamedTypeSymbol>("B"); var classC = globalNamespace.GetMember<NamedTypeSymbol>("C"); var methodA = classA.GetMember<MethodSymbol>("get_P"); var methodB = classB.GetMember<PropertySymbol>("P").GetMethod; var methodC = classC.GetMember<MethodSymbol>("get_P"); var typeDefC = (Cci.ITypeDefinition)classC.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)classC.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverride = typeDefC.GetExplicitImplementationOverrides(context).Single(); Assert.Equal(classC, explicitOverride.ContainingType.GetInternalSymbol()); Assert.Equal(methodC, explicitOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(methodA, explicitOverride.ImplementedMethod.GetInternalSymbol()); context.Diagnostics.Verify(); } [WorkItem(543444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543444")] [Fact] public void BadArityInOperatorDeclaration() { var text = @"class A { public static bool operator true(A x, A y) { return false; } } class B { public static B operator *(B x) { return null; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,33): error CS1020: Overloadable binary operator expected // public static bool operator true(A x, A y) { return false; } Diagnostic(ErrorCode.ERR_OvlBinaryOperatorExpected, "true"), // (8,30): error CS1019: Overloadable unary operator expected // public static B operator *(B x) { return null; } Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "*"), // (3,33): error CS0216: The operator 'A.operator true(A, A)' requires a matching operator 'false' to also be defined // public static bool operator true(A x, A y) { return false; } Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "true").WithArguments("A.operator true(A, A)", "false") ); } [WorkItem(779441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779441")] [Fact] public void UserDefinedOperatorLocation() { var source = @" public class C { public static C operator +(C c) { return null; } } "; var keywordPos = source.IndexOf('+'); var parenPos = source.IndexOf('('); var comp = CreateCompilation(source); var symbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName).Single(); var span = symbol.Locations.Single().SourceSpan; Assert.Equal(keywordPos, span.Start); Assert.Equal(parenPos, span.End); } [WorkItem(779441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779441")] [Fact] public void UserDefinedConversionLocation() { var source = @" public class C { public static explicit operator string(C c) { return null; } } "; var keywordPos = source.IndexOf("string", StringComparison.Ordinal); var parenPos = source.IndexOf('('); var comp = CreateCompilation(source); var symbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.ExplicitConversionName).Single(); var span = symbol.Locations.Single().SourceSpan; Assert.Equal(keywordPos, span.Start); Assert.Equal(parenPos, span.End); } [WorkItem(787708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/787708")] [Fact] public void PartialAsyncMethodInTypeWithAttributes() { var source = @" using System; class Attr : Attribute { public int P { get; set; } } [Attr(P = F)] partial class C { const int F = 1; partial void M(); async partial void M() { } } "; CreateCompilation(source).VerifyDiagnostics( // (15,24): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async partial void M() { } Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M")); } [WorkItem(910100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910100")] [Fact] public void SubstitutedParameterEquality() { var source = @" class C { void M<T>(T t) { } } "; var comp = CreateCompilation(source); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var constructedMethod1 = method.Construct(type); var constructedMethod2 = method.Construct(type); Assert.Equal(constructedMethod1, constructedMethod2); Assert.NotSame(constructedMethod1, constructedMethod2); var substitutedParameter1 = constructedMethod1.Parameters.Single(); var substitutedParameter2 = constructedMethod2.Parameters.Single(); Assert.Equal(substitutedParameter1, substitutedParameter2); Assert.NotSame(substitutedParameter1, substitutedParameter2); } [WorkItem(910100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910100")] [Fact] public void ReducedExtensionMethodParameterEquality() { var source = @" static class C { static void M(this int i, string s) { } } "; var comp = CreateCompilation(source); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var reducedMethod1 = method.ReduceExtensionMethod(); var reducedMethod2 = method.ReduceExtensionMethod(); Assert.Equal(reducedMethod1, reducedMethod2); Assert.NotSame(reducedMethod1, reducedMethod2); var extensionParameter1 = reducedMethod1.Parameters.Single(); var extensionParameter2 = reducedMethod2.Parameters.Single(); Assert.Equal(extensionParameter1, extensionParameter2); Assert.NotSame(extensionParameter1, extensionParameter2); } [Fact] public void RefReturningVoidMethod() { var source = @" static class C { static ref void M() { } } "; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (4,16): error CS1547: Keyword 'void' cannot be used in this context // static ref void M() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(4, 16) ); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningVoidMethod() { var source = @" static class C { static ref readonly void M() { } } "; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (4,25): error CS1547: Keyword 'void' cannot be used in this context // static ref readonly void M() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(4, 25) ); } [Fact] public void RefReturningVoidMethodNested() { var source = @" static class C { static void Main() { ref void M() { } } } "; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,13): error CS1547: Keyword 'void' cannot be used in this context // ref void M() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(6, 13), // (6,18): warning CS8321: The local function 'M' is declared but never used // ref void M() { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "M").WithArguments("M").WithLocation(6, 18) ); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningVoidMethodNested() { var source = @" static class C { static void Main() { // valid ref readonly int M1() {throw null;} // not valid ref readonly void M2() {M1(); throw null;} M2(); } } "; var parseOptions = TestOptions.Regular; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,22): error CS1547: Keyword 'void' cannot be used in this context // ref readonly void M2() {M1(); throw null;} Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(10, 22) ); } [Fact] public void RefReturningAsyncMethod() { var source = @" static class C { static async ref int M() { } } "; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (4,18): error CS1073: Unexpected token 'ref' // static async ref int M() { } Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(4, 18), // (4,26): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // static async ref int M() { } Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 26), // (4,26): error CS0161: 'C.M()': not all code paths return a value // static async ref int M() { } Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("C.M()").WithLocation(4, 26) ); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningAsyncMethod() { var source = @" static class C { static async ref readonly int M() { } } "; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (4,18): error CS1073: Unexpected token 'ref' // static async ref readonly int M() { } Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(4, 18), // (4,35): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // static async ref readonly int M() { } Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 35), // (4,35): error CS0161: 'C.M()': not all code paths return a value // static async ref readonly int M() { } Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("C.M()").WithLocation(4, 35) ); } [Fact] public void StaticMethodDoesNotRequireInstanceReceiver() { var source = @" class C { public static int M() => 42; }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var method = compilation.GetMember<MethodSymbol>("C.M"); Assert.False(method.RequiresInstanceReceiver); } [Fact] public void InstanceMethodRequiresInstanceReceiver() { var source = @" class C { public int M() => 42; }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var method = compilation.GetMember<MethodSymbol>("C.M"); Assert.True(method.RequiresInstanceReceiver); } [Fact] public void OrdinaryMethodIsNotConditional() { var source = @" class C { public void M() {} }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var method = compilation.GetMember<MethodSymbol>("C.M"); Assert.False(method.IsConditional); } [Fact] public void ConditionalMethodIsConditional() { var source = @" using System.Diagnostics; class C { [Conditional(""Debug"")] public void M() {} }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var method = compilation.GetMember<MethodSymbol>("C.M"); Assert.True(method.IsConditional); } [Fact] public void ConditionalMethodOverrideIsConditional() { var source = @" using System.Diagnostics; class Base { [Conditional(""Debug"")] public virtual void M() {} } class Derived : Base { public override void M() {} }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var method = compilation.GetMember<MethodSymbol>("Derived.M"); Assert.True(method.IsConditional); } [Fact] public void InvalidConditionalMethodIsConditional() { var source = @" using System.Diagnostics; class C { [Conditional(""Debug"")] public int M() => 42; }"; var compilation = CreateCompilation(source).VerifyDiagnostics( // (5,6): error CS0578: The Conditional attribute is not valid on 'C.M()' because its return type is not void // [Conditional("Debug")] Diagnostic(ErrorCode.ERR_ConditionalMustReturnVoid, @"Conditional(""Debug"")").WithArguments("C.M()").WithLocation(5, 6)); var method = compilation.GetMember<MethodSymbol>("C.M"); Assert.True(method.IsConditional); } [Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")] public void IsPartialDefinitionOnNonPartial() { var source = @" class C { void M() {} } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol(); Assert.False(m.IsPartialDefinition); } [Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")] public void IsPartialDefinitionOnPartialDefinitionOnly() { var source = @" partial class C { partial void M(); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol(); Assert.True(m.IsPartialDefinition); Assert.Null(m.PartialDefinitionPart); Assert.Null(m.PartialImplementationPart); } [Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")] public void IsPartialDefinitionWithPartialImplementation() { var source = @" partial class C { partial void M(); partial void M() {} } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol(); Assert.True(m.IsPartialDefinition); Assert.Null(m.PartialDefinitionPart); Assert.False(m.PartialImplementationPart.IsPartialDefinition); } [Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")] public void IsPartialDefinitionOnPartialImplementation_NonPartialClass() { var source = @" class C { partial void M(); partial void M() {} } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,18): error CS0751: A partial method must be declared within a partial type // partial void M(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(4, 18), // (5,18): error CS0751: A partial method must be declared within a partial type // partial void M() {} Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(5, 18) ); var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol(); Assert.True(m.IsPartialDefinition); Assert.Null(m.PartialDefinitionPart); Assert.False(m.PartialImplementationPart.IsPartialDefinition); } [Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")] public void IsPartialDefinitionOnPartialImplementationOnly() { var source = @" partial class C { partial void M() {} } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M()' // partial void M() {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M()").WithLocation(4, 18) ); var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol(); Assert.False(m.IsPartialDefinition); Assert.Null(m.PartialDefinitionPart); Assert.Null(m.PartialImplementationPart); } [Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")] public void IsPartialDefinition_ReturnsFalseFromMetadata() { var source = @" public partial class C { public partial void M(); public partial void M() {} } "; CompileAndVerify(source, sourceSymbolValidator: module => { var m = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").GetPublicSymbol(); Assert.True(m.IsPartialDefinition); Assert.Null(m.PartialDefinitionPart); Assert.False(m.PartialImplementationPart.IsPartialDefinition); }, symbolValidator: module => { var m = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").GetPublicSymbol(); Assert.False(m.IsPartialDefinition); Assert.Null(m.PartialDefinitionPart); Assert.Null(m.PartialImplementationPart); }); } [Fact] public void IsPartialDefinition_OnPartialExtern() { var source = @" public partial class C { private partial void M(); private extern partial void M(); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var syntax = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntax); var methods = syntax.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ToArray(); var partialDef = model.GetDeclaredSymbol(methods[0]); Assert.True(partialDef.IsPartialDefinition); var partialImpl = model.GetDeclaredSymbol(methods[1]); Assert.False(partialImpl.IsPartialDefinition); Assert.Same(partialDef.PartialImplementationPart, partialImpl); Assert.Same(partialImpl.PartialDefinitionPart, partialDef); Assert.Null(partialDef.PartialDefinitionPart); Assert.Null(partialImpl.PartialImplementationPart); } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/CSharp/Impl/LanguageService/CSharpEditorFactory.cs
// 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. #nullable disable using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.FileHeaders; using Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.FileHeaders; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation; namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService { [ExcludeFromCodeCoverage] [Guid(Guids.CSharpEditorFactoryIdString)] internal class CSharpEditorFactory : AbstractEditorFactory { public CSharpEditorFactory(IComponentModel componentModel) : base(componentModel) { } protected override string ContentTypeName => ContentTypeNames.CSharpContentType; protected override string LanguageName => LanguageNames.CSharp; } }
// 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. #nullable disable using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.FileHeaders; using Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.FileHeaders; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation; namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService { [ExcludeFromCodeCoverage] [Guid(Guids.CSharpEditorFactoryIdString)] internal class CSharpEditorFactory : AbstractEditorFactory { public CSharpEditorFactory(IComponentModel componentModel) : base(componentModel) { } protected override string ContentTypeName => ContentTypeNames.CSharpContentType; protected override string LanguageName => LanguageNames.CSharp; } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_AnonymousObjectCreation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { // We should never encounter an interpolated string handler conversion that was implicitly inferred, because // there are no target types for an anonymous object creation. AssertNoImplicitInterpolatedStringHandlerConversions(node.Arguments); // Rewrite the arguments. var rewrittenArguments = VisitList(node.Arguments); return new BoundObjectCreationExpression( syntax: node.Syntax, constructor: node.Constructor, arguments: rewrittenArguments, argumentNamesOpt: default(ImmutableArray<string>), argumentRefKindsOpt: default(ImmutableArray<RefKind>), expanded: false, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), constantValueOpt: null, initializerExpressionOpt: null, type: node.Type); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { // We should never encounter an interpolated string handler conversion that was implicitly inferred, because // there are no target types for an anonymous object creation. AssertNoImplicitInterpolatedStringHandlerConversions(node.Arguments); // Rewrite the arguments. var rewrittenArguments = VisitList(node.Arguments); return new BoundObjectCreationExpression( syntax: node.Syntax, constructor: node.Constructor, arguments: rewrittenArguments, argumentNamesOpt: default(ImmutableArray<string>), argumentRefKindsOpt: default(ImmutableArray<RefKind>), expanded: false, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), constantValueOpt: null, initializerExpressionOpt: null, type: node.Type); } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Def/Implementation/Experimentation/KeybindingResetDetector.cs
// 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. #nullable disable using System; using System.ComponentModel.Composition; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Experimentation; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Experimentation; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.PlatformUI.OleComponentSupport; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Experimentation { /// <summary> /// Detects if keybindings have been messed up by ReSharper disable, and offers the user the ability /// to reset if so. /// </summary> /// <remarks> /// The only objects to hold permanent references to this object should be callbacks that are registered for in /// <see cref="InitializeCore"/>. No other external objects should hold a reference to this. Unless the user clicks /// 'Never show this again', this will persist for the life of the VS instance, and does not need to be manually disposed /// in that case. /// </remarks> /// <para> /// We've written this in a generic mechanism we can extend to any extension as we know of them, /// but at this time ReSharper is the only one we know of that has this behavior. /// If we find other extensions that do this in the future, we'll re-use this same mechanism /// </para> [Export(typeof(IExperiment))] internal sealed class KeybindingResetDetector : ForegroundThreadAffinitizedObject, IExperiment, IOleCommandTarget { private const string KeybindingsFwLink = "https://go.microsoft.com/fwlink/?linkid=864209"; private const string ReSharperExtensionName = "ReSharper Ultimate"; private const string ReSharperKeyboardMappingName = "ReSharper (Visual Studio)"; private const string VSCodeKeyboardMappingName = "Visual Studio Code"; // Resharper commands and package private const uint ResumeId = 707; private const uint SuspendId = 708; private const uint ToggleSuspendId = 709; private static readonly Guid ReSharperPackageGuid = new("0C6E6407-13FC-4878-869A-C8B4016C57FE"); private static readonly Guid ReSharperCommandGroup = new("{47F03277-5055-4922-899C-0F7F30D26BF1}"); private readonly VisualStudioWorkspace _workspace; private readonly System.IServiceProvider _serviceProvider; // All mutable fields are UI-thread affinitized private IVsUIShell _uiShell; private IOleCommandTarget _oleCommandTarget; private OleComponent _oleComponent; private uint _priorityCommandTargetCookie = VSConstants.VSCOOKIE_NIL; private CancellationTokenSource _cancellationTokenSource = new(); /// <summary> /// If false, ReSharper is either not installed, or has been disabled in the extension manager. /// If true, the ReSharper extension is enabled. ReSharper's internal status could be either suspended or enabled. /// </summary> private bool _resharperExtensionInstalledAndEnabled = false; private bool _infoBarOpen = false; /// <summary> /// Chain all update tasks so that task runs serially /// </summary> private Task _lastTask = Task.CompletedTask; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public KeybindingResetDetector(IThreadingContext threadingContext, VisualStudioWorkspace workspace, SVsServiceProvider serviceProvider) : base(threadingContext) { _workspace = workspace; _serviceProvider = serviceProvider; } public Task InitializeAsync() { // Immediately bail if the user has asked to never see this bar again. if (_workspace.Options.GetOption(KeybindingResetOptions.NeverShowAgain)) { return Task.CompletedTask; } return InvokeBelowInputPriorityAsync(InitializeCore); } private void InitializeCore() { AssertIsForeground(); // Ensure one of the flights is enabled, otherwise bail if (!_workspace.Options.GetOption(KeybindingResetOptions.EnabledFeatureFlag)) { return; } var vsShell = IServiceProviderExtensions.GetService<SVsShell, IVsShell>(_serviceProvider); var hr = vsShell.IsPackageInstalled(ReSharperPackageGuid, out var extensionEnabled); if (ErrorHandler.Failed(hr)) { FatalError.ReportAndCatch(Marshal.GetExceptionForHR(hr)); return; } _resharperExtensionInstalledAndEnabled = extensionEnabled != 0; if (_resharperExtensionInstalledAndEnabled) { // We need to monitor for suspend/resume commands, so create and install the command target and the modal callback. var priorityCommandTargetRegistrar = IServiceProviderExtensions.GetService<SVsRegisterPriorityCommandTarget, IVsRegisterPriorityCommandTarget>(_serviceProvider); hr = priorityCommandTargetRegistrar.RegisterPriorityCommandTarget( dwReserved: 0 /* from docs must be 0 */, pCmdTrgt: this, pdwCookie: out _priorityCommandTargetCookie); if (ErrorHandler.Failed(hr)) { FatalError.ReportAndCatch(Marshal.GetExceptionForHR(hr)); return; } // Initialize the OleComponent to listen for modal changes (which will tell us when Tools->Options is closed) _oleComponent = OleComponent.CreateHostedComponent("Keybinding Reset Detector"); _oleComponent.ModalStateChanged += OnModalStateChanged; } // run it from background and fire and forget StartUpdateStateMachine(); } private void StartUpdateStateMachine() { // cancel previous state machine update request _cancellationTokenSource.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; // make sure all state machine change work is serialized so that cancellation // doesn't mess the state up. _lastTask = _lastTask.SafeContinueWithFromAsync(_ => { return UpdateStateMachineWorkerAsync(cancellationToken); }, cancellationToken, TaskScheduler.Default); } private async Task UpdateStateMachineWorkerAsync(CancellationToken cancellationToken) { var options = _workspace.Options; var lastStatus = options.GetOption(KeybindingResetOptions.ReSharperStatus); ReSharperStatus currentStatus; try { currentStatus = await IsReSharperRunningAsync(cancellationToken) .ConfigureAwait(false); } catch (OperationCanceledException) { return; } if (currentStatus == lastStatus) { return; } options = options.WithChangedOption(KeybindingResetOptions.ReSharperStatus, currentStatus); switch (lastStatus) { case ReSharperStatus.NotInstalledOrDisabled: case ReSharperStatus.Suspended: if (currentStatus == ReSharperStatus.Enabled) { // N->E or S->E. If ReSharper was just installed and is enabled, reset NeedsReset. options = options.WithChangedOption(KeybindingResetOptions.NeedsReset, false); } // Else is N->N, N->S, S->N, S->S. N->S can occur if the user suspends ReSharper, then disables // the extension, then reenables the extension. We will show the gold bar after the switch // if there is still a pending show. break; case ReSharperStatus.Enabled: if (currentStatus != ReSharperStatus.Enabled) { // E->N or E->S. Set NeedsReset. Pop the gold bar to the user. options = options.WithChangedOption(KeybindingResetOptions.NeedsReset, true); } // Else is E->E. No actions to take break; } // Apply the new options. // We need to switch to UI thread to invoke TryApplyChanges. await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(options)); if (options.GetOption(KeybindingResetOptions.NeedsReset)) { ShowGoldBar(); } } private void ShowGoldBar() { // If the gold bar is already open, do not show if (_infoBarOpen) { return; } _infoBarOpen = true; var message = ServicesVSResources.We_notice_you_suspended_0_Reset_keymappings_to_continue_to_navigate_and_refactor; KeybindingsResetLogger.Log("InfoBarShown"); var infoBarService = _workspace.Services.GetRequiredService<IInfoBarService>(); infoBarService.ShowInfoBar( string.Format(message, ReSharperExtensionName), new InfoBarUI(title: ServicesVSResources.Reset_Visual_Studio_default_keymapping, kind: InfoBarUI.UIKind.Button, action: RestoreVsKeybindings), new InfoBarUI(title: string.Format(ServicesVSResources.Apply_0_keymapping_scheme, ReSharperKeyboardMappingName), kind: InfoBarUI.UIKind.Button, action: OpenExtensionsHyperlink), new InfoBarUI(title: string.Format(ServicesVSResources.Apply_0_keymapping_scheme, VSCodeKeyboardMappingName), kind: InfoBarUI.UIKind.Button, action: OpenExtensionsHyperlink), new InfoBarUI(title: ServicesVSResources.Never_show_this_again, kind: InfoBarUI.UIKind.HyperLink, action: NeverShowAgain), new InfoBarUI(title: "", kind: InfoBarUI.UIKind.Close, action: InfoBarClose)); } /// <summary> /// Returns true if ReSharper is installed, enabled, and not suspended. /// </summary> private async ValueTask<ReSharperStatus> IsReSharperRunningAsync(CancellationToken cancellationToken) { // Quick exit if resharper is either uninstalled or not enabled if (!_resharperExtensionInstalledAndEnabled) { return ReSharperStatus.NotInstalledOrDisabled; } await EnsureOleCommandTargetAsync().ConfigureAwait(false); // poll until either suspend or resume botton is available, or until operation is canceled while (true) { cancellationToken.ThrowIfCancellationRequested(); var suspendFlag = await QueryStatusAsync(SuspendId).ConfigureAwait(false); // In the case of an error when attempting to get the status, pretend that ReSharper isn't enabled. We also // shut down monitoring so we don't keep hitting this. if (suspendFlag == 0) { return ReSharperStatus.NotInstalledOrDisabled; } var resumeFlag = await QueryStatusAsync(ResumeId).ConfigureAwait(false); if (resumeFlag == 0) { return ReSharperStatus.NotInstalledOrDisabled; } // When ReSharper is running, the ReSharper_Suspend command is Enabled and not Invisible if (suspendFlag.HasFlag(OLECMDF.OLECMDF_ENABLED) && !suspendFlag.HasFlag(OLECMDF.OLECMDF_INVISIBLE)) { return ReSharperStatus.Enabled; } // When ReSharper is suspended, the ReSharper_Resume command is Enabled and not Invisible if (resumeFlag.HasFlag(OLECMDF.OLECMDF_ENABLED) && !resumeFlag.HasFlag(OLECMDF.OLECMDF_INVISIBLE)) { return ReSharperStatus.Suspended; } // ReSharper has not finished initializing, so try again later await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken).ConfigureAwait(false); } async Task<OLECMDF> QueryStatusAsync(uint cmdId) { var cmds = new OLECMD[1]; cmds[0].cmdID = cmdId; cmds[0].cmdf = 0; await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var hr = _oleCommandTarget.QueryStatus(ReSharperCommandGroup, (uint)cmds.Length, cmds, IntPtr.Zero); if (ErrorHandler.Failed(hr)) { FatalError.ReportAndCatch(Marshal.GetExceptionForHR(hr)); await ShutdownAsync().ConfigureAwait(false); return 0; } return (OLECMDF)cmds[0].cmdf; } async Task EnsureOleCommandTargetAsync() { if (_oleCommandTarget != null) { return; } await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _oleCommandTarget = IServiceProviderExtensions.GetService<SUIHostCommandDispatcher, IOleCommandTarget>(_serviceProvider); } } private void RestoreVsKeybindings() { AssertIsForeground(); if (_uiShell == null) { _uiShell = IServiceProviderExtensions.GetService<SVsUIShell, IVsUIShell>(_serviceProvider); } ErrorHandler.ThrowOnFailure(_uiShell.PostExecCommand( VSConstants.GUID_VSStandardCommandSet97, (uint)VSConstants.VSStd97CmdID.CustomizeKeyboard, (uint)OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, null)); KeybindingsResetLogger.Log("KeybindingsReset"); _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(KeybindingResetOptions.NeedsReset, false))); } private void OpenExtensionsHyperlink() { ThisCanBeCalledOnAnyThread(); VisualStudioNavigateToLinkService.StartBrowser(KeybindingsFwLink); KeybindingsResetLogger.Log("ExtensionsLink"); _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(KeybindingResetOptions.NeedsReset, false))); } private void NeverShowAgain() { _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(KeybindingResetOptions.NeverShowAgain, true) .WithChangedOption(KeybindingResetOptions.NeedsReset, false))); KeybindingsResetLogger.Log("NeverShowAgain"); // The only external references to this object are as callbacks, which are removed by the Shutdown method. ThreadingContext.JoinableTaskFactory.Run(ShutdownAsync); } private void InfoBarClose() { AssertIsForeground(); _infoBarOpen = false; } public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { // Technically can be called on any thread, though VS will only ever call it on the UI thread. ThisCanBeCalledOnAnyThread(); // We don't care about query status, only when the command is actually executed return (int)OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED; } public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { // Technically can be called on any thread, though VS will only ever call it on the UI thread. ThisCanBeCalledOnAnyThread(); if (pguidCmdGroup == ReSharperCommandGroup && nCmdID >= ResumeId && nCmdID <= ToggleSuspendId) { // Don't delay command processing to update resharper status StartUpdateStateMachine(); } // No matter the command, we never actually want to respond to it, so always return not supported. We're just monitoring. return (int)OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED; } private void OnModalStateChanged(object sender, StateChangedEventArgs args) { ThisCanBeCalledOnAnyThread(); // Only monitor for StateTransitionType.Exit. This will be fired when the shell is leaving a modal state, including // Tools->Options being exited. This will fire more than just on Options close, but there's no harm from running an // extra QueryStatus. if (args.TransitionType == StateTransitionType.Exit) { StartUpdateStateMachine(); } } private async Task ShutdownAsync() { // we are shutting down, cancel any pending work. _cancellationTokenSource.Cancel(); await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); if (_priorityCommandTargetCookie != VSConstants.VSCOOKIE_NIL) { var priorityCommandTargetRegistrar = IServiceProviderExtensions.GetService<SVsRegisterPriorityCommandTarget, IVsRegisterPriorityCommandTarget>(_serviceProvider); var cookie = _priorityCommandTargetCookie; _priorityCommandTargetCookie = VSConstants.VSCOOKIE_NIL; var hr = priorityCommandTargetRegistrar.UnregisterPriorityCommandTarget(cookie); if (ErrorHandler.Failed(hr)) { FatalError.ReportAndCatch(Marshal.GetExceptionForHR(hr)); } } if (_oleComponent != null) { _oleComponent.Dispose(); _oleComponent = null; } } } }
// 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. #nullable disable using System; using System.ComponentModel.Composition; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Experimentation; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Experimentation; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.PlatformUI.OleComponentSupport; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Experimentation { /// <summary> /// Detects if keybindings have been messed up by ReSharper disable, and offers the user the ability /// to reset if so. /// </summary> /// <remarks> /// The only objects to hold permanent references to this object should be callbacks that are registered for in /// <see cref="InitializeCore"/>. No other external objects should hold a reference to this. Unless the user clicks /// 'Never show this again', this will persist for the life of the VS instance, and does not need to be manually disposed /// in that case. /// </remarks> /// <para> /// We've written this in a generic mechanism we can extend to any extension as we know of them, /// but at this time ReSharper is the only one we know of that has this behavior. /// If we find other extensions that do this in the future, we'll re-use this same mechanism /// </para> [Export(typeof(IExperiment))] internal sealed class KeybindingResetDetector : ForegroundThreadAffinitizedObject, IExperiment, IOleCommandTarget { private const string KeybindingsFwLink = "https://go.microsoft.com/fwlink/?linkid=864209"; private const string ReSharperExtensionName = "ReSharper Ultimate"; private const string ReSharperKeyboardMappingName = "ReSharper (Visual Studio)"; private const string VSCodeKeyboardMappingName = "Visual Studio Code"; // Resharper commands and package private const uint ResumeId = 707; private const uint SuspendId = 708; private const uint ToggleSuspendId = 709; private static readonly Guid ReSharperPackageGuid = new("0C6E6407-13FC-4878-869A-C8B4016C57FE"); private static readonly Guid ReSharperCommandGroup = new("{47F03277-5055-4922-899C-0F7F30D26BF1}"); private readonly VisualStudioWorkspace _workspace; private readonly System.IServiceProvider _serviceProvider; // All mutable fields are UI-thread affinitized private IVsUIShell _uiShell; private IOleCommandTarget _oleCommandTarget; private OleComponent _oleComponent; private uint _priorityCommandTargetCookie = VSConstants.VSCOOKIE_NIL; private CancellationTokenSource _cancellationTokenSource = new(); /// <summary> /// If false, ReSharper is either not installed, or has been disabled in the extension manager. /// If true, the ReSharper extension is enabled. ReSharper's internal status could be either suspended or enabled. /// </summary> private bool _resharperExtensionInstalledAndEnabled = false; private bool _infoBarOpen = false; /// <summary> /// Chain all update tasks so that task runs serially /// </summary> private Task _lastTask = Task.CompletedTask; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public KeybindingResetDetector(IThreadingContext threadingContext, VisualStudioWorkspace workspace, SVsServiceProvider serviceProvider) : base(threadingContext) { _workspace = workspace; _serviceProvider = serviceProvider; } public Task InitializeAsync() { // Immediately bail if the user has asked to never see this bar again. if (_workspace.Options.GetOption(KeybindingResetOptions.NeverShowAgain)) { return Task.CompletedTask; } return InvokeBelowInputPriorityAsync(InitializeCore); } private void InitializeCore() { AssertIsForeground(); // Ensure one of the flights is enabled, otherwise bail if (!_workspace.Options.GetOption(KeybindingResetOptions.EnabledFeatureFlag)) { return; } var vsShell = IServiceProviderExtensions.GetService<SVsShell, IVsShell>(_serviceProvider); var hr = vsShell.IsPackageInstalled(ReSharperPackageGuid, out var extensionEnabled); if (ErrorHandler.Failed(hr)) { FatalError.ReportAndCatch(Marshal.GetExceptionForHR(hr)); return; } _resharperExtensionInstalledAndEnabled = extensionEnabled != 0; if (_resharperExtensionInstalledAndEnabled) { // We need to monitor for suspend/resume commands, so create and install the command target and the modal callback. var priorityCommandTargetRegistrar = IServiceProviderExtensions.GetService<SVsRegisterPriorityCommandTarget, IVsRegisterPriorityCommandTarget>(_serviceProvider); hr = priorityCommandTargetRegistrar.RegisterPriorityCommandTarget( dwReserved: 0 /* from docs must be 0 */, pCmdTrgt: this, pdwCookie: out _priorityCommandTargetCookie); if (ErrorHandler.Failed(hr)) { FatalError.ReportAndCatch(Marshal.GetExceptionForHR(hr)); return; } // Initialize the OleComponent to listen for modal changes (which will tell us when Tools->Options is closed) _oleComponent = OleComponent.CreateHostedComponent("Keybinding Reset Detector"); _oleComponent.ModalStateChanged += OnModalStateChanged; } // run it from background and fire and forget StartUpdateStateMachine(); } private void StartUpdateStateMachine() { // cancel previous state machine update request _cancellationTokenSource.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; // make sure all state machine change work is serialized so that cancellation // doesn't mess the state up. _lastTask = _lastTask.SafeContinueWithFromAsync(_ => { return UpdateStateMachineWorkerAsync(cancellationToken); }, cancellationToken, TaskScheduler.Default); } private async Task UpdateStateMachineWorkerAsync(CancellationToken cancellationToken) { var options = _workspace.Options; var lastStatus = options.GetOption(KeybindingResetOptions.ReSharperStatus); ReSharperStatus currentStatus; try { currentStatus = await IsReSharperRunningAsync(cancellationToken) .ConfigureAwait(false); } catch (OperationCanceledException) { return; } if (currentStatus == lastStatus) { return; } options = options.WithChangedOption(KeybindingResetOptions.ReSharperStatus, currentStatus); switch (lastStatus) { case ReSharperStatus.NotInstalledOrDisabled: case ReSharperStatus.Suspended: if (currentStatus == ReSharperStatus.Enabled) { // N->E or S->E. If ReSharper was just installed and is enabled, reset NeedsReset. options = options.WithChangedOption(KeybindingResetOptions.NeedsReset, false); } // Else is N->N, N->S, S->N, S->S. N->S can occur if the user suspends ReSharper, then disables // the extension, then reenables the extension. We will show the gold bar after the switch // if there is still a pending show. break; case ReSharperStatus.Enabled: if (currentStatus != ReSharperStatus.Enabled) { // E->N or E->S. Set NeedsReset. Pop the gold bar to the user. options = options.WithChangedOption(KeybindingResetOptions.NeedsReset, true); } // Else is E->E. No actions to take break; } // Apply the new options. // We need to switch to UI thread to invoke TryApplyChanges. await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(options)); if (options.GetOption(KeybindingResetOptions.NeedsReset)) { ShowGoldBar(); } } private void ShowGoldBar() { // If the gold bar is already open, do not show if (_infoBarOpen) { return; } _infoBarOpen = true; var message = ServicesVSResources.We_notice_you_suspended_0_Reset_keymappings_to_continue_to_navigate_and_refactor; KeybindingsResetLogger.Log("InfoBarShown"); var infoBarService = _workspace.Services.GetRequiredService<IInfoBarService>(); infoBarService.ShowInfoBar( string.Format(message, ReSharperExtensionName), new InfoBarUI(title: ServicesVSResources.Reset_Visual_Studio_default_keymapping, kind: InfoBarUI.UIKind.Button, action: RestoreVsKeybindings), new InfoBarUI(title: string.Format(ServicesVSResources.Apply_0_keymapping_scheme, ReSharperKeyboardMappingName), kind: InfoBarUI.UIKind.Button, action: OpenExtensionsHyperlink), new InfoBarUI(title: string.Format(ServicesVSResources.Apply_0_keymapping_scheme, VSCodeKeyboardMappingName), kind: InfoBarUI.UIKind.Button, action: OpenExtensionsHyperlink), new InfoBarUI(title: ServicesVSResources.Never_show_this_again, kind: InfoBarUI.UIKind.HyperLink, action: NeverShowAgain), new InfoBarUI(title: "", kind: InfoBarUI.UIKind.Close, action: InfoBarClose)); } /// <summary> /// Returns true if ReSharper is installed, enabled, and not suspended. /// </summary> private async ValueTask<ReSharperStatus> IsReSharperRunningAsync(CancellationToken cancellationToken) { // Quick exit if resharper is either uninstalled or not enabled if (!_resharperExtensionInstalledAndEnabled) { return ReSharperStatus.NotInstalledOrDisabled; } await EnsureOleCommandTargetAsync().ConfigureAwait(false); // poll until either suspend or resume botton is available, or until operation is canceled while (true) { cancellationToken.ThrowIfCancellationRequested(); var suspendFlag = await QueryStatusAsync(SuspendId).ConfigureAwait(false); // In the case of an error when attempting to get the status, pretend that ReSharper isn't enabled. We also // shut down monitoring so we don't keep hitting this. if (suspendFlag == 0) { return ReSharperStatus.NotInstalledOrDisabled; } var resumeFlag = await QueryStatusAsync(ResumeId).ConfigureAwait(false); if (resumeFlag == 0) { return ReSharperStatus.NotInstalledOrDisabled; } // When ReSharper is running, the ReSharper_Suspend command is Enabled and not Invisible if (suspendFlag.HasFlag(OLECMDF.OLECMDF_ENABLED) && !suspendFlag.HasFlag(OLECMDF.OLECMDF_INVISIBLE)) { return ReSharperStatus.Enabled; } // When ReSharper is suspended, the ReSharper_Resume command is Enabled and not Invisible if (resumeFlag.HasFlag(OLECMDF.OLECMDF_ENABLED) && !resumeFlag.HasFlag(OLECMDF.OLECMDF_INVISIBLE)) { return ReSharperStatus.Suspended; } // ReSharper has not finished initializing, so try again later await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken).ConfigureAwait(false); } async Task<OLECMDF> QueryStatusAsync(uint cmdId) { var cmds = new OLECMD[1]; cmds[0].cmdID = cmdId; cmds[0].cmdf = 0; await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var hr = _oleCommandTarget.QueryStatus(ReSharperCommandGroup, (uint)cmds.Length, cmds, IntPtr.Zero); if (ErrorHandler.Failed(hr)) { FatalError.ReportAndCatch(Marshal.GetExceptionForHR(hr)); await ShutdownAsync().ConfigureAwait(false); return 0; } return (OLECMDF)cmds[0].cmdf; } async Task EnsureOleCommandTargetAsync() { if (_oleCommandTarget != null) { return; } await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _oleCommandTarget = IServiceProviderExtensions.GetService<SUIHostCommandDispatcher, IOleCommandTarget>(_serviceProvider); } } private void RestoreVsKeybindings() { AssertIsForeground(); if (_uiShell == null) { _uiShell = IServiceProviderExtensions.GetService<SVsUIShell, IVsUIShell>(_serviceProvider); } ErrorHandler.ThrowOnFailure(_uiShell.PostExecCommand( VSConstants.GUID_VSStandardCommandSet97, (uint)VSConstants.VSStd97CmdID.CustomizeKeyboard, (uint)OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, null)); KeybindingsResetLogger.Log("KeybindingsReset"); _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(KeybindingResetOptions.NeedsReset, false))); } private void OpenExtensionsHyperlink() { ThisCanBeCalledOnAnyThread(); VisualStudioNavigateToLinkService.StartBrowser(KeybindingsFwLink); KeybindingsResetLogger.Log("ExtensionsLink"); _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(KeybindingResetOptions.NeedsReset, false))); } private void NeverShowAgain() { _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(KeybindingResetOptions.NeverShowAgain, true) .WithChangedOption(KeybindingResetOptions.NeedsReset, false))); KeybindingsResetLogger.Log("NeverShowAgain"); // The only external references to this object are as callbacks, which are removed by the Shutdown method. ThreadingContext.JoinableTaskFactory.Run(ShutdownAsync); } private void InfoBarClose() { AssertIsForeground(); _infoBarOpen = false; } public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { // Technically can be called on any thread, though VS will only ever call it on the UI thread. ThisCanBeCalledOnAnyThread(); // We don't care about query status, only when the command is actually executed return (int)OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED; } public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { // Technically can be called on any thread, though VS will only ever call it on the UI thread. ThisCanBeCalledOnAnyThread(); if (pguidCmdGroup == ReSharperCommandGroup && nCmdID >= ResumeId && nCmdID <= ToggleSuspendId) { // Don't delay command processing to update resharper status StartUpdateStateMachine(); } // No matter the command, we never actually want to respond to it, so always return not supported. We're just monitoring. return (int)OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED; } private void OnModalStateChanged(object sender, StateChangedEventArgs args) { ThisCanBeCalledOnAnyThread(); // Only monitor for StateTransitionType.Exit. This will be fired when the shell is leaving a modal state, including // Tools->Options being exited. This will fire more than just on Options close, but there's no harm from running an // extra QueryStatus. if (args.TransitionType == StateTransitionType.Exit) { StartUpdateStateMachine(); } } private async Task ShutdownAsync() { // we are shutting down, cancel any pending work. _cancellationTokenSource.Cancel(); await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); if (_priorityCommandTargetCookie != VSConstants.VSCOOKIE_NIL) { var priorityCommandTargetRegistrar = IServiceProviderExtensions.GetService<SVsRegisterPriorityCommandTarget, IVsRegisterPriorityCommandTarget>(_serviceProvider); var cookie = _priorityCommandTargetCookie; _priorityCommandTargetCookie = VSConstants.VSCOOKIE_NIL; var hr = priorityCommandTargetRegistrar.UnregisterPriorityCommandTarget(cookie); if (ErrorHandler.Failed(hr)) { FatalError.ReportAndCatch(Marshal.GetExceptionForHR(hr)); } } if (_oleComponent != null) { _oleComponent.Dispose(); _oleComponent = null; } } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Symbols/SymbolDistinguisher.cs
// 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. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Some error messages are particularly confusing if multiple placeholders are substituted /// with the same string. For example, "cannot convert from 'Goo' to 'Goo'". Usually, this /// occurs because there are two types in different contexts with the same qualified name. /// The solution is to provide additional qualification on each symbol - either a source /// location, an assembly path, or an assembly identity. /// </summary> /// <remarks> /// Performs the same function as ErrArgFlags::Unique in the native compiler. /// </remarks> internal sealed class SymbolDistinguisher { private readonly CSharpCompilation _compilation; private readonly Symbol _symbol0; private readonly Symbol _symbol1; private ImmutableArray<string> _lazyDescriptions; public SymbolDistinguisher(CSharpCompilation compilation, Symbol symbol0, Symbol symbol1) { Debug.Assert(symbol0 != symbol1); CheckSymbolKind(symbol0); CheckSymbolKind(symbol1); _compilation = compilation; _symbol0 = symbol0; _symbol1 = symbol1; } public IFormattable First { get { return new Description(this, 0); } } public IFormattable Second { get { return new Description(this, 1); } } [Conditional("DEBUG")] private static void CheckSymbolKind(Symbol symbol) { switch (symbol.Kind) { case SymbolKind.ErrorType: case SymbolKind.NamedType: case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.TypeParameter: break; // Can sensibly append location. case SymbolKind.ArrayType: case SymbolKind.PointerType: case SymbolKind.Parameter: break; // Can sensibly append location, after unwrapping. case SymbolKind.DynamicType: // Can't sensibly append location, but it should never be ambiguous. case SymbolKind.FunctionPointerType: // Can't sensibly append location break; case SymbolKind.Namespace: case SymbolKind.Alias: case SymbolKind.Assembly: case SymbolKind.NetModule: case SymbolKind.Label: case SymbolKind.Local: case SymbolKind.RangeVariable: case SymbolKind.Preprocessing: default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } private void MakeDescriptions() { if (!_lazyDescriptions.IsDefault) return; string description0 = _symbol0.ToDisplayString(); string description1 = _symbol1.ToDisplayString(); if (description0 == description1) { Symbol unwrappedSymbol0 = UnwrapSymbol(_symbol0); Symbol unwrappedSymbol1 = UnwrapSymbol(_symbol1); string location0 = GetLocationString(_compilation, unwrappedSymbol0); string location1 = GetLocationString(_compilation, unwrappedSymbol1); // The locations should not be equal, but they might be if the same // SyntaxTree is referenced by two different compilations. if (location0 == location1) { var containingAssembly0 = unwrappedSymbol0.ContainingAssembly; var containingAssembly1 = unwrappedSymbol1.ContainingAssembly; // May not be the case if there are error types. if ((object)containingAssembly0 != null && (object)containingAssembly1 != null) { // Use the assembly identities rather than locations. Note that the // assembly identities may be identical as well. (For instance, the // symbols are type arguments to the same generic type, and the type // arguments have the same string representation. The assembly // identities will refer to the generic types, not the type arguments.) location0 = containingAssembly0.Identity.ToString(); location1 = containingAssembly1.Identity.ToString(); } } if (location0 != location1) { if (location0 != null) { description0 = $"{description0} [{location0}]"; } if (location1 != null) { description1 = $"{description1} [{location1}]"; } } } if (!_lazyDescriptions.IsDefault) return; ImmutableInterlocked.InterlockedInitialize(ref _lazyDescriptions, ImmutableArray.Create(description0, description1)); } private static Symbol UnwrapSymbol(Symbol symbol) { while (true) { switch (symbol.Kind) { case SymbolKind.Parameter: symbol = ((ParameterSymbol)symbol).Type; continue; case SymbolKind.PointerType: symbol = ((PointerTypeSymbol)symbol).PointedAtType; continue; case SymbolKind.ArrayType: symbol = ((ArrayTypeSymbol)symbol).ElementType; continue; default: return symbol; } } } private static string GetLocationString(CSharpCompilation compilation, Symbol unwrappedSymbol) { Debug.Assert((object)unwrappedSymbol == UnwrapSymbol(unwrappedSymbol)); ImmutableArray<SyntaxReference> syntaxReferences = unwrappedSymbol.DeclaringSyntaxReferences; if (syntaxReferences.Length > 0) { var tree = syntaxReferences[0].SyntaxTree; var span = syntaxReferences[0].Span; string path = tree.GetDisplayPath(span, (compilation != null) ? compilation.Options.SourceReferenceResolver : null); if (!string.IsNullOrEmpty(path)) { return $"{path}({tree.GetDisplayLineNumber(span)})"; } } AssemblySymbol containingAssembly = unwrappedSymbol.ContainingAssembly; if ((object)containingAssembly != null) { if (compilation != null) { PortableExecutableReference metadataReference = compilation.GetMetadataReference(containingAssembly) as PortableExecutableReference; if (metadataReference != null) { string path = metadataReference.FilePath; if (!string.IsNullOrEmpty(path)) { return path; } } } return containingAssembly.Identity.ToString(); } Debug.Assert(unwrappedSymbol.Kind == SymbolKind.DynamicType || unwrappedSymbol.Kind == SymbolKind.ErrorType || unwrappedSymbol.Kind == SymbolKind.FunctionPointerType); return null; } private string GetDescription(int index) { MakeDescriptions(); return _lazyDescriptions[index]; } private sealed class Description : IFormattable { private readonly SymbolDistinguisher _distinguisher; private readonly int _index; public Description(SymbolDistinguisher distinguisher, int index) { _distinguisher = distinguisher; _index = index; } private Symbol GetSymbol() { return (_index == 0) ? _distinguisher._symbol0 : _distinguisher._symbol1; } public override bool Equals(object obj) { var other = obj as Description; return other != null && _distinguisher._compilation == other._distinguisher._compilation && GetSymbol() == other.GetSymbol(); } public override int GetHashCode() { int result = GetSymbol().GetHashCode(); var compilation = _distinguisher._compilation; if (compilation != null) { result = Hash.Combine(result, compilation.GetHashCode()); } return result; } public override string ToString() { return _distinguisher.GetDescription(_index); } string IFormattable.ToString(string format, IFormatProvider formatProvider) { return ToString(); } } } }
// 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. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Some error messages are particularly confusing if multiple placeholders are substituted /// with the same string. For example, "cannot convert from 'Goo' to 'Goo'". Usually, this /// occurs because there are two types in different contexts with the same qualified name. /// The solution is to provide additional qualification on each symbol - either a source /// location, an assembly path, or an assembly identity. /// </summary> /// <remarks> /// Performs the same function as ErrArgFlags::Unique in the native compiler. /// </remarks> internal sealed class SymbolDistinguisher { private readonly CSharpCompilation _compilation; private readonly Symbol _symbol0; private readonly Symbol _symbol1; private ImmutableArray<string> _lazyDescriptions; public SymbolDistinguisher(CSharpCompilation compilation, Symbol symbol0, Symbol symbol1) { Debug.Assert(symbol0 != symbol1); CheckSymbolKind(symbol0); CheckSymbolKind(symbol1); _compilation = compilation; _symbol0 = symbol0; _symbol1 = symbol1; } public IFormattable First { get { return new Description(this, 0); } } public IFormattable Second { get { return new Description(this, 1); } } [Conditional("DEBUG")] private static void CheckSymbolKind(Symbol symbol) { switch (symbol.Kind) { case SymbolKind.ErrorType: case SymbolKind.NamedType: case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.TypeParameter: break; // Can sensibly append location. case SymbolKind.ArrayType: case SymbolKind.PointerType: case SymbolKind.Parameter: break; // Can sensibly append location, after unwrapping. case SymbolKind.DynamicType: // Can't sensibly append location, but it should never be ambiguous. case SymbolKind.FunctionPointerType: // Can't sensibly append location break; case SymbolKind.Namespace: case SymbolKind.Alias: case SymbolKind.Assembly: case SymbolKind.NetModule: case SymbolKind.Label: case SymbolKind.Local: case SymbolKind.RangeVariable: case SymbolKind.Preprocessing: default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } private void MakeDescriptions() { if (!_lazyDescriptions.IsDefault) return; string description0 = _symbol0.ToDisplayString(); string description1 = _symbol1.ToDisplayString(); if (description0 == description1) { Symbol unwrappedSymbol0 = UnwrapSymbol(_symbol0); Symbol unwrappedSymbol1 = UnwrapSymbol(_symbol1); string location0 = GetLocationString(_compilation, unwrappedSymbol0); string location1 = GetLocationString(_compilation, unwrappedSymbol1); // The locations should not be equal, but they might be if the same // SyntaxTree is referenced by two different compilations. if (location0 == location1) { var containingAssembly0 = unwrappedSymbol0.ContainingAssembly; var containingAssembly1 = unwrappedSymbol1.ContainingAssembly; // May not be the case if there are error types. if ((object)containingAssembly0 != null && (object)containingAssembly1 != null) { // Use the assembly identities rather than locations. Note that the // assembly identities may be identical as well. (For instance, the // symbols are type arguments to the same generic type, and the type // arguments have the same string representation. The assembly // identities will refer to the generic types, not the type arguments.) location0 = containingAssembly0.Identity.ToString(); location1 = containingAssembly1.Identity.ToString(); } } if (location0 != location1) { if (location0 != null) { description0 = $"{description0} [{location0}]"; } if (location1 != null) { description1 = $"{description1} [{location1}]"; } } } if (!_lazyDescriptions.IsDefault) return; ImmutableInterlocked.InterlockedInitialize(ref _lazyDescriptions, ImmutableArray.Create(description0, description1)); } private static Symbol UnwrapSymbol(Symbol symbol) { while (true) { switch (symbol.Kind) { case SymbolKind.Parameter: symbol = ((ParameterSymbol)symbol).Type; continue; case SymbolKind.PointerType: symbol = ((PointerTypeSymbol)symbol).PointedAtType; continue; case SymbolKind.ArrayType: symbol = ((ArrayTypeSymbol)symbol).ElementType; continue; default: return symbol; } } } private static string GetLocationString(CSharpCompilation compilation, Symbol unwrappedSymbol) { Debug.Assert((object)unwrappedSymbol == UnwrapSymbol(unwrappedSymbol)); ImmutableArray<SyntaxReference> syntaxReferences = unwrappedSymbol.DeclaringSyntaxReferences; if (syntaxReferences.Length > 0) { var tree = syntaxReferences[0].SyntaxTree; var span = syntaxReferences[0].Span; string path = tree.GetDisplayPath(span, (compilation != null) ? compilation.Options.SourceReferenceResolver : null); if (!string.IsNullOrEmpty(path)) { return $"{path}({tree.GetDisplayLineNumber(span)})"; } } AssemblySymbol containingAssembly = unwrappedSymbol.ContainingAssembly; if ((object)containingAssembly != null) { if (compilation != null) { PortableExecutableReference metadataReference = compilation.GetMetadataReference(containingAssembly) as PortableExecutableReference; if (metadataReference != null) { string path = metadataReference.FilePath; if (!string.IsNullOrEmpty(path)) { return path; } } } return containingAssembly.Identity.ToString(); } Debug.Assert(unwrappedSymbol.Kind == SymbolKind.DynamicType || unwrappedSymbol.Kind == SymbolKind.ErrorType || unwrappedSymbol.Kind == SymbolKind.FunctionPointerType); return null; } private string GetDescription(int index) { MakeDescriptions(); return _lazyDescriptions[index]; } private sealed class Description : IFormattable { private readonly SymbolDistinguisher _distinguisher; private readonly int _index; public Description(SymbolDistinguisher distinguisher, int index) { _distinguisher = distinguisher; _index = index; } private Symbol GetSymbol() { return (_index == 0) ? _distinguisher._symbol0 : _distinguisher._symbol1; } public override bool Equals(object obj) { var other = obj as Description; return other != null && _distinguisher._compilation == other._distinguisher._compilation && GetSymbol() == other.GetSymbol(); } public override int GetHashCode() { int result = GetSymbol().GetHashCode(); var compilation = _distinguisher._compilation; if (compilation != null) { result = Hash.Combine(result, compilation.GetHashCode()); } return result; } public override string ToString() { return _distinguisher.GetDescription(_index); } string IFormattable.ToString(string format, IFormatProvider formatProvider) { return ToString(); } } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Declarations/DeclarationModifiers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.CSharp { [Flags] internal enum DeclarationModifiers : uint { None = 0, Abstract = 1 << 0, Sealed = 1 << 1, Static = 1 << 2, New = 1 << 3, Public = 1 << 4, Protected = 1 << 5, Internal = 1 << 6, ProtectedInternal = 1 << 7, // the two keywords together are treated as one modifier Private = 1 << 8, PrivateProtected = 1 << 9, // the two keywords together are treated as one modifier ReadOnly = 1 << 10, Const = 1 << 11, Volatile = 1 << 12, Extern = 1 << 13, Partial = 1 << 14, Unsafe = 1 << 15, Fixed = 1 << 16, Virtual = 1 << 17, // used for method binding Override = 1 << 18, // used for method binding Indexer = 1 << 19, // not a real modifier, but used to record that indexer syntax was used. Async = 1 << 20, Ref = 1 << 21, // used only for structs All = (1 << 23) - 1, // all modifiers Unset = 1 << 23, // used when a modifiers value hasn't yet been computed AccessibilityMask = PrivateProtected | Private | Protected | Internal | ProtectedInternal | Public, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.CSharp { [Flags] internal enum DeclarationModifiers : uint { None = 0, Abstract = 1 << 0, Sealed = 1 << 1, Static = 1 << 2, New = 1 << 3, Public = 1 << 4, Protected = 1 << 5, Internal = 1 << 6, ProtectedInternal = 1 << 7, // the two keywords together are treated as one modifier Private = 1 << 8, PrivateProtected = 1 << 9, // the two keywords together are treated as one modifier ReadOnly = 1 << 10, Const = 1 << 11, Volatile = 1 << 12, Extern = 1 << 13, Partial = 1 << 14, Unsafe = 1 << 15, Fixed = 1 << 16, Virtual = 1 << 17, // used for method binding Override = 1 << 18, // used for method binding Indexer = 1 << 19, // not a real modifier, but used to record that indexer syntax was used. Async = 1 << 20, Ref = 1 << 21, // used only for structs All = (1 << 23) - 1, // all modifiers Unset = 1 << 23, // used when a modifiers value hasn't yet been computed AccessibilityMask = PrivateProtected | Private | Protected | Internal | ProtectedInternal | Public, } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/CSharp/Portable/CodeFixes/HideBase/HideBaseCodeFixProvider.AddNewKeywordAction.cs
// 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. #nullable disable using System.Linq; using System.Threading.Tasks; using System.Threading; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.OrderModifiers; using Microsoft.CodeAnalysis.OrderModifiers; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CSharp.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.HideBase { internal partial class HideBaseCodeFixProvider { private class AddNewKeywordAction : CodeActions.CodeAction { private readonly Document _document; private readonly SyntaxNode _node; public override string Title => CSharpFeaturesResources.Hide_base_member; public AddNewKeywordAction(Document document, SyntaxNode node) { _document = document; _node = node; } protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) { var root = await _document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newNode = await GetNewNodeAsync(_node, cancellationToken).ConfigureAwait(false); var newRoot = root.ReplaceNode(_node, newNode); return _document.WithSyntaxRoot(newRoot); } private async Task<SyntaxNode> GetNewNodeAsync(SyntaxNode node, CancellationToken cancellationToken) { var syntaxFacts = CSharpSyntaxFacts.Instance; var modifiers = syntaxFacts.GetModifiers(node); var newModifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); var options = await _document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var option = options.GetOption(CSharpCodeStyleOptions.PreferredModifierOrder); if (!CSharpOrderModifiersHelper.Instance.TryGetOrComputePreferredOrder(option.Value, out var preferredOrder) || !AbstractOrderModifiersHelpers.IsOrdered(preferredOrder, modifiers)) { return syntaxFacts.WithModifiers(node, newModifiers); } var orderedModifiers = new SyntaxTokenList( newModifiers.OrderBy(CompareModifiers)); return syntaxFacts.WithModifiers(node, orderedModifiers); int CompareModifiers(SyntaxToken left, SyntaxToken right) => GetOrder(left) - GetOrder(right); int GetOrder(SyntaxToken token) => preferredOrder.TryGetValue(token.RawKind, out var value) ? value : int.MaxValue; } } } }
// 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. #nullable disable using System.Linq; using System.Threading.Tasks; using System.Threading; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.OrderModifiers; using Microsoft.CodeAnalysis.OrderModifiers; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CSharp.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.HideBase { internal partial class HideBaseCodeFixProvider { private class AddNewKeywordAction : CodeActions.CodeAction { private readonly Document _document; private readonly SyntaxNode _node; public override string Title => CSharpFeaturesResources.Hide_base_member; public AddNewKeywordAction(Document document, SyntaxNode node) { _document = document; _node = node; } protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) { var root = await _document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newNode = await GetNewNodeAsync(_node, cancellationToken).ConfigureAwait(false); var newRoot = root.ReplaceNode(_node, newNode); return _document.WithSyntaxRoot(newRoot); } private async Task<SyntaxNode> GetNewNodeAsync(SyntaxNode node, CancellationToken cancellationToken) { var syntaxFacts = CSharpSyntaxFacts.Instance; var modifiers = syntaxFacts.GetModifiers(node); var newModifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); var options = await _document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var option = options.GetOption(CSharpCodeStyleOptions.PreferredModifierOrder); if (!CSharpOrderModifiersHelper.Instance.TryGetOrComputePreferredOrder(option.Value, out var preferredOrder) || !AbstractOrderModifiersHelpers.IsOrdered(preferredOrder, modifiers)) { return syntaxFacts.WithModifiers(node, newModifiers); } var orderedModifiers = new SyntaxTokenList( newModifiers.OrderBy(CompareModifiers)); return syntaxFacts.WithModifiers(node, orderedModifiers); int CompareModifiers(SyntaxToken left, SyntaxToken right) => GetOrder(left) - GetOrder(right); int GetOrder(SyntaxToken token) => preferredOrder.TryGetValue(token.RawKind, out var value) ? value : int.MaxValue; } } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Tools/BuildBoss/SolutionCheckerUtil.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace BuildBoss { internal sealed class SolutionCheckerUtil : ICheckerUtil { private struct SolutionProjectData { internal ProjectEntry ProjectEntry; internal ProjectData ProjectData; internal SolutionProjectData(ProjectEntry entry, ProjectData data) { ProjectEntry = entry; ProjectData = data; } } internal string SolutionFilePath { get; } internal string SolutionPath { get; } internal bool IsPrimarySolution { get; } internal SolutionCheckerUtil(string solutionFilePath, bool isPrimarySolution) { SolutionFilePath = solutionFilePath; IsPrimarySolution = isPrimarySolution; SolutionPath = Path.GetDirectoryName(SolutionFilePath); } public bool Check(TextWriter textWriter) { var allGood = true; allGood &= CheckDuplicate(textWriter, out var map); allGood &= CheckProjects(textWriter, map); allGood &= CheckProjectSystemGuid(textWriter, map.Values); return allGood; } private bool CheckProjects(TextWriter textWriter, Dictionary<ProjectKey, SolutionProjectData> map) { var solutionMap = new Dictionary<ProjectKey, ProjectData>(); foreach (var pair in map) { solutionMap.Add(pair.Key, pair.Value.ProjectData); } var allGood = true; var count = 0; foreach (var data in map.Values.OrderBy(x => x.ProjectEntry.Name)) { var projectWriter = new StringWriter(); var projectData = data.ProjectData; projectWriter.WriteLine($"Processing {projectData.Key.FileName}"); var util = new ProjectCheckerUtil(projectData, solutionMap, IsPrimarySolution); if (!util.Check(projectWriter)) { allGood = false; textWriter.WriteLine(projectWriter.ToString()); } count++; } textWriter.WriteLine($"Processed {count} projects"); return allGood; } private bool CheckDuplicate(TextWriter textWriter, out Dictionary<ProjectKey, SolutionProjectData> map) { map = new Dictionary<ProjectKey, SolutionProjectData>(); var allGood = true; foreach (var projectEntry in SolutionUtil.ParseProjects(SolutionFilePath)) { if (projectEntry.IsFolder) { continue; } var projectFilePath = Path.Combine(SolutionPath, projectEntry.RelativeFilePath); var projectData = new ProjectData(projectFilePath); if (map.ContainsKey(projectData.Key)) { textWriter.WriteLine($"Duplicate project detected {projectData.FileName}"); allGood = false; } else { map.Add(projectData.Key, new SolutionProjectData(projectEntry, projectData)); } } return allGood; } /// <summary> /// Ensure solution files have the proper project system GUID. /// </summary> private bool CheckProjectSystemGuid(TextWriter textWriter, IEnumerable<SolutionProjectData> dataList) { Guid getExpectedGuid(ProjectData data) { var util = data.ProjectUtil; switch (ProjectEntryUtil.GetProjectFileType(data.FilePath)) { case ProjectFileType.CSharp: return ProjectEntryUtil.ManagedProjectSystemCSharp; case ProjectFileType.Basic: return ProjectEntryUtil.ManagedProjectSystemVisualBasic; case ProjectFileType.Shared: return ProjectEntryUtil.SharedProject; default: throw new Exception($"Invalid file path {data.FilePath}"); } } var allGood = true; foreach (var data in dataList.Where(x => x.ProjectEntry.ProjectType != ProjectFileType.Tool)) { var guid = getExpectedGuid(data.ProjectData); if (guid != data.ProjectEntry.TypeGuid) { var name = data.ProjectData.FileName; textWriter.WriteLine($"Project {name} should have GUID {guid} but has {data.ProjectEntry.TypeGuid}"); allGood = false; } } return allGood; } } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace BuildBoss { internal sealed class SolutionCheckerUtil : ICheckerUtil { private struct SolutionProjectData { internal ProjectEntry ProjectEntry; internal ProjectData ProjectData; internal SolutionProjectData(ProjectEntry entry, ProjectData data) { ProjectEntry = entry; ProjectData = data; } } internal string SolutionFilePath { get; } internal string SolutionPath { get; } internal bool IsPrimarySolution { get; } internal SolutionCheckerUtil(string solutionFilePath, bool isPrimarySolution) { SolutionFilePath = solutionFilePath; IsPrimarySolution = isPrimarySolution; SolutionPath = Path.GetDirectoryName(SolutionFilePath); } public bool Check(TextWriter textWriter) { var allGood = true; allGood &= CheckDuplicate(textWriter, out var map); allGood &= CheckProjects(textWriter, map); allGood &= CheckProjectSystemGuid(textWriter, map.Values); return allGood; } private bool CheckProjects(TextWriter textWriter, Dictionary<ProjectKey, SolutionProjectData> map) { var solutionMap = new Dictionary<ProjectKey, ProjectData>(); foreach (var pair in map) { solutionMap.Add(pair.Key, pair.Value.ProjectData); } var allGood = true; var count = 0; foreach (var data in map.Values.OrderBy(x => x.ProjectEntry.Name)) { var projectWriter = new StringWriter(); var projectData = data.ProjectData; projectWriter.WriteLine($"Processing {projectData.Key.FileName}"); var util = new ProjectCheckerUtil(projectData, solutionMap, IsPrimarySolution); if (!util.Check(projectWriter)) { allGood = false; textWriter.WriteLine(projectWriter.ToString()); } count++; } textWriter.WriteLine($"Processed {count} projects"); return allGood; } private bool CheckDuplicate(TextWriter textWriter, out Dictionary<ProjectKey, SolutionProjectData> map) { map = new Dictionary<ProjectKey, SolutionProjectData>(); var allGood = true; foreach (var projectEntry in SolutionUtil.ParseProjects(SolutionFilePath)) { if (projectEntry.IsFolder) { continue; } var projectFilePath = Path.Combine(SolutionPath, projectEntry.RelativeFilePath); var projectData = new ProjectData(projectFilePath); if (map.ContainsKey(projectData.Key)) { textWriter.WriteLine($"Duplicate project detected {projectData.FileName}"); allGood = false; } else { map.Add(projectData.Key, new SolutionProjectData(projectEntry, projectData)); } } return allGood; } /// <summary> /// Ensure solution files have the proper project system GUID. /// </summary> private bool CheckProjectSystemGuid(TextWriter textWriter, IEnumerable<SolutionProjectData> dataList) { Guid getExpectedGuid(ProjectData data) { var util = data.ProjectUtil; switch (ProjectEntryUtil.GetProjectFileType(data.FilePath)) { case ProjectFileType.CSharp: return ProjectEntryUtil.ManagedProjectSystemCSharp; case ProjectFileType.Basic: return ProjectEntryUtil.ManagedProjectSystemVisualBasic; case ProjectFileType.Shared: return ProjectEntryUtil.SharedProject; default: throw new Exception($"Invalid file path {data.FilePath}"); } } var allGood = true; foreach (var data in dataList.Where(x => x.ProjectEntry.ProjectType != ProjectFileType.Tool)) { var guid = getExpectedGuid(data.ProjectData); if (guid != data.ProjectEntry.TypeGuid) { var name = data.ProjectData.FileName; textWriter.WriteLine($"Project {name} should have GUID {guid} but has {data.ProjectEntry.TypeGuid}"); allGood = false; } } return allGood; } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/Conversions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.MSBuild { /// <summary> /// Handles conversions from MSBuild values. /// </summary> internal static class Conversions { public static bool ToBool(string? value) => value != null && (string.Equals(bool.TrueString, value, StringComparison.OrdinalIgnoreCase) || string.Equals("On", value, StringComparison.OrdinalIgnoreCase)); public static int ToInt(string? value) { if (value == null) { return 0; } else { if (int.TryParse(value, out var result)) { return result; } return 0; } } public static ulong ToULong(string? value) { if (value == null) { return 0; } else { if (ulong.TryParse(value, out var result)) { return result; } return 0; } } public static TEnum? ToEnum<TEnum>(string? value, bool ignoreCase) where TEnum : struct { if (value == null) { return null; } else { return Enum.TryParse<TEnum>(value, ignoreCase, out var result) ? result : (TEnum?)null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.MSBuild { /// <summary> /// Handles conversions from MSBuild values. /// </summary> internal static class Conversions { public static bool ToBool(string? value) => value != null && (string.Equals(bool.TrueString, value, StringComparison.OrdinalIgnoreCase) || string.Equals("On", value, StringComparison.OrdinalIgnoreCase)); public static int ToInt(string? value) { if (value == null) { return 0; } else { if (int.TryParse(value, out var result)) { return result; } return 0; } } public static ulong ToULong(string? value) { if (value == null) { return 0; } else { if (ulong.TryParse(value, out var result)) { return result; } return 0; } } public static TEnum? ToEnum<TEnum>(string? value, bool ignoreCase) where TEnum : struct { if (value == null) { return null; } else { return Enum.TryParse<TEnum>(value, ignoreCase, out var result) ? result : (TEnum?)null; } } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldTestState.vb
' 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.Editor.Shared Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EncapsulateField Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.VisualBasic.EncapsulateField Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EncapsulateField Friend Class EncapsulateFieldTestState Implements IDisposable Private ReadOnly _testDocument As TestHostDocument Public Workspace As TestWorkspace Public TargetDocument As Document Private Sub New(workspace As TestWorkspace) Me.Workspace = workspace _testDocument = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue OrElse d.SelectedSpans.Any()) TargetDocument = workspace.CurrentSolution.GetDocument(_testDocument.Id) End Sub Public Shared Function Create(markup As String) As EncapsulateFieldTestState Dim workspace = TestWorkspace.CreateVisualBasic(markup, composition:=EditorTestCompositions.EditorFeatures) Return New EncapsulateFieldTestState(workspace) End Function Public Sub Encapsulate() Dim args = New EncapsulateFieldCommandArgs(_testDocument.GetTextView(), _testDocument.GetTextBuffer()) Dim commandHandler = New EncapsulateFieldCommandHandler( Workspace.ExportProvider.GetExportedValue(Of IThreadingContext)(), Workspace.GetService(Of ITextBufferUndoManagerProvider)(), Workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)) commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create()) End Sub Public Sub AssertEncapsulateAs(expected As String) Encapsulate() Assert.Equal(expected, _testDocument.GetTextBuffer().CurrentSnapshot.GetText().ToString()) End Sub Public Sub Dispose() Implements IDisposable.Dispose If Workspace IsNot Nothing Then Workspace.Dispose() End If End Sub End Class End Namespace
' 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.Editor.Shared Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EncapsulateField Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.VisualBasic.EncapsulateField Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EncapsulateField Friend Class EncapsulateFieldTestState Implements IDisposable Private ReadOnly _testDocument As TestHostDocument Public Workspace As TestWorkspace Public TargetDocument As Document Private Sub New(workspace As TestWorkspace) Me.Workspace = workspace _testDocument = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue OrElse d.SelectedSpans.Any()) TargetDocument = workspace.CurrentSolution.GetDocument(_testDocument.Id) End Sub Public Shared Function Create(markup As String) As EncapsulateFieldTestState Dim workspace = TestWorkspace.CreateVisualBasic(markup, composition:=EditorTestCompositions.EditorFeatures) Return New EncapsulateFieldTestState(workspace) End Function Public Sub Encapsulate() Dim args = New EncapsulateFieldCommandArgs(_testDocument.GetTextView(), _testDocument.GetTextBuffer()) Dim commandHandler = New EncapsulateFieldCommandHandler( Workspace.ExportProvider.GetExportedValue(Of IThreadingContext)(), Workspace.GetService(Of ITextBufferUndoManagerProvider)(), Workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)) commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create()) End Sub Public Sub AssertEncapsulateAs(expected As String) Encapsulate() Assert.Equal(expected, _testDocument.GetTextBuffer().CurrentSnapshot.GetText().ToString()) End Sub Public Sub Dispose() Implements IDisposable.Dispose If Workspace IsNot Nothing Then Workspace.Dispose() End If End Sub End Class End Namespace
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/MSBuildTest/Resources/SolutionFiles/CSharp_UnknownProjectTypeGuid.sln
 Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-000000000000}") = "CSharpProject", "CSharpProject\CSharpProject.csproj", "{686DD036-86AA-443E-8A10-DDB43266A8C4}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {686DD036-86AA-443E-8A10-DDB43266A8C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {686DD036-86AA-443E-8A10-DDB43266A8C4}.Debug|Any CPU.Build.0 = Debug|Any CPU {686DD036-86AA-443E-8A10-DDB43266A8C4}.Release|Any CPU.ActiveCfg = Release|Any CPU {686DD036-86AA-443E-8A10-DDB43266A8C4}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
 Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-000000000000}") = "CSharpProject", "CSharpProject\CSharpProject.csproj", "{686DD036-86AA-443E-8A10-DDB43266A8C4}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {686DD036-86AA-443E-8A10-DDB43266A8C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {686DD036-86AA-443E-8A10-DDB43266A8C4}.Debug|Any CPU.Build.0 = Debug|Any CPU {686DD036-86AA-443E-8A10-DDB43266A8C4}.Release|Any CPU.ActiveCfg = Release|Any CPU {686DD036-86AA-443E-8A10-DDB43266A8C4}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/CoreTestUtilities/Fakes/SimpleAssetSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote.Testing { /// <summary> /// provide asset from given map at the creation /// </summary> internal sealed class SimpleAssetSource : IAssetSource { private readonly ISerializerService _serializerService; private readonly IReadOnlyDictionary<Checksum, object> _map; public SimpleAssetSource(ISerializerService serializerService, IReadOnlyDictionary<Checksum, object> map) { _serializerService = serializerService; _map = map; } public ValueTask<ImmutableArray<(Checksum, object)>> GetAssetsAsync( int serviceId, ISet<Checksum> checksums, ISerializerService deserializerService, CancellationToken cancellationToken) { var results = new List<(Checksum, object)>(); foreach (var checksum in checksums) { if (_map.TryGetValue(checksum, out var data)) { using var stream = new MemoryStream(); using var context = SolutionReplicationContext.Create(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { _serializerService.Serialize(data, writer, context, cancellationToken); } stream.Position = 0; using var reader = ObjectReader.GetReader(stream, leaveOpen: true, cancellationToken); var asset = deserializerService.Deserialize<object>(data.GetWellKnownSynchronizationKind(), reader, cancellationToken); Contract.ThrowIfTrue(asset is null); results.Add((checksum, asset)); } else { throw ExceptionUtilities.UnexpectedValue(checksum); } } return ValueTaskFactory.FromResult(results.ToImmutableArray()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote.Testing { /// <summary> /// provide asset from given map at the creation /// </summary> internal sealed class SimpleAssetSource : IAssetSource { private readonly ISerializerService _serializerService; private readonly IReadOnlyDictionary<Checksum, object> _map; public SimpleAssetSource(ISerializerService serializerService, IReadOnlyDictionary<Checksum, object> map) { _serializerService = serializerService; _map = map; } public ValueTask<ImmutableArray<(Checksum, object)>> GetAssetsAsync( int serviceId, ISet<Checksum> checksums, ISerializerService deserializerService, CancellationToken cancellationToken) { var results = new List<(Checksum, object)>(); foreach (var checksum in checksums) { if (_map.TryGetValue(checksum, out var data)) { using var stream = new MemoryStream(); using var context = SolutionReplicationContext.Create(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { _serializerService.Serialize(data, writer, context, cancellationToken); } stream.Position = 0; using var reader = ObjectReader.GetReader(stream, leaveOpen: true, cancellationToken); var asset = deserializerService.Deserialize<object>(data.GetWellKnownSynchronizationKind(), reader, cancellationToken); Contract.ThrowIfTrue(asset is null); results.Add((checksum, asset)); } else { throw ExceptionUtilities.UnexpectedValue(checksum); } } return ValueTaskFactory.FromResult(results.ToImmutableArray()); } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Impl/CodeModel/Collections/ExternalParameterCollection.cs
// 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. #nullable disable using System.Collections.Immutable; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class ExternalParameterCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, AbstractExternalCodeMember parent, ProjectId projectId) { var collection = new ExternalParameterCollection(state, parent, projectId); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ProjectId _projectId; private ExternalParameterCollection( CodeModelState state, AbstractExternalCodeMember parent, ProjectId projectId) : base(state, parent) { _projectId = projectId; } private AbstractExternalCodeMember ParentElement { get { return (AbstractExternalCodeMember)this.Parent; } } private ImmutableArray<IParameterSymbol> GetParameters() { var symbol = this.ParentElement.LookupSymbol(); return symbol.GetParameters(); } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var parameters = GetParameters(); if (index < parameters.Length) { element = (EnvDTE.CodeElement)ExternalCodeParameter.Create(this.State, _projectId, parameters[index], this.ParentElement); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var parameters = GetParameters(); var index = parameters.IndexOf(p => p.Name == name); if (index >= 0 && index < parameters.Length) { element = (EnvDTE.CodeElement)ExternalCodeParameter.Create(this.State, _projectId, parameters[index], this.ParentElement); return true; } element = null; return false; } public override int Count { get { var parameters = GetParameters(); return parameters.Length; } } } }
// 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. #nullable disable using System.Collections.Immutable; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class ExternalParameterCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, AbstractExternalCodeMember parent, ProjectId projectId) { var collection = new ExternalParameterCollection(state, parent, projectId); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ProjectId _projectId; private ExternalParameterCollection( CodeModelState state, AbstractExternalCodeMember parent, ProjectId projectId) : base(state, parent) { _projectId = projectId; } private AbstractExternalCodeMember ParentElement { get { return (AbstractExternalCodeMember)this.Parent; } } private ImmutableArray<IParameterSymbol> GetParameters() { var symbol = this.ParentElement.LookupSymbol(); return symbol.GetParameters(); } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var parameters = GetParameters(); if (index < parameters.Length) { element = (EnvDTE.CodeElement)ExternalCodeParameter.Create(this.State, _projectId, parameters[index], this.ParentElement); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var parameters = GetParameters(); var index = parameters.IndexOf(p => p.Name == name); if (index >= 0 && index < parameters.Length) { element = (EnvDTE.CodeElement)ExternalCodeParameter.Create(this.State, _projectId, parameters[index], this.ParentElement); return true; } element = null; return false; } public override int Count { get { var parameters = GetParameters(); return parameters.Length; } } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.de.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="de" original="../WorkspaceExtensionsResources.resx"> <body> <trans-unit id="Compilation_is_required_to_accomplish_the_task_but_is_not_supported_by_project_0"> <source>Compilation is required to accomplish the task but is not supported by project {0}.</source> <target state="translated">Die Kompilierung ist zum Ausführen der Aufgabe erforderlich, wird aber vom Projekt "{0}" nicht unterstützt.</target> <note /> </trans-unit> <trans-unit id="Fix_all_0"> <source>Fix all '{0}'</source> <target state="translated">Alle '{0}' reparieren</target> <note /> </trans-unit> <trans-unit id="Fix_all_0_in_1"> <source>Fix all '{0}' in '{1}'</source> <target state="translated">Alle '{0}' in '{1}' reparieren</target> <note /> </trans-unit> <trans-unit id="Fix_all_0_in_Solution"> <source>Fix all '{0}' in Solution</source> <target state="translated">Alle '{0}' in Lösung reparieren</target> <note /> </trans-unit> <trans-unit id="Project_of_ID_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_solution"> <source>Project of ID {0} is required to accomplish the task but is not available from the solution</source> <target state="translated">Ein Projekt mit der ID "{0}" ist zum Ausführen der Aufgabe erforderlich, steht aber in der Projektmappe nicht zur Verfügung.</target> <note /> </trans-unit> <trans-unit id="Supplied_diagnostic_cannot_be_null"> <source>Supplied diagnostic cannot be null.</source> <target state="translated">Bereitgestellte Diagnose darf nicht null sein.</target> <note /> </trans-unit> <trans-unit id="SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0"> <source>Syntax tree is required to accomplish the task but is not supported by document {0}.</source> <target state="translated">Die Syntaxstruktur ist zum Ausführen der Aufgabe erforderlich, wird aber vom Dokument "{0}" nicht unterstützt.</target> <note /> </trans-unit> <trans-unit id="The_solution_does_not_contain_the_specified_document"> <source>The solution does not contain the specified document.</source> <target state="translated">Die Lösung enthält nicht das angegebene Dokument.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Declaration_changes_scope_and_may_change_meaning"> <source>Warning: Declaration changes scope and may change meaning.</source> <target state="translated">Warnung: Die Deklaration ändert den Bereich und möglicherweise die Bedeutung.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="de" original="../WorkspaceExtensionsResources.resx"> <body> <trans-unit id="Compilation_is_required_to_accomplish_the_task_but_is_not_supported_by_project_0"> <source>Compilation is required to accomplish the task but is not supported by project {0}.</source> <target state="translated">Die Kompilierung ist zum Ausführen der Aufgabe erforderlich, wird aber vom Projekt "{0}" nicht unterstützt.</target> <note /> </trans-unit> <trans-unit id="Fix_all_0"> <source>Fix all '{0}'</source> <target state="translated">Alle '{0}' reparieren</target> <note /> </trans-unit> <trans-unit id="Fix_all_0_in_1"> <source>Fix all '{0}' in '{1}'</source> <target state="translated">Alle '{0}' in '{1}' reparieren</target> <note /> </trans-unit> <trans-unit id="Fix_all_0_in_Solution"> <source>Fix all '{0}' in Solution</source> <target state="translated">Alle '{0}' in Lösung reparieren</target> <note /> </trans-unit> <trans-unit id="Project_of_ID_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_solution"> <source>Project of ID {0} is required to accomplish the task but is not available from the solution</source> <target state="translated">Ein Projekt mit der ID "{0}" ist zum Ausführen der Aufgabe erforderlich, steht aber in der Projektmappe nicht zur Verfügung.</target> <note /> </trans-unit> <trans-unit id="Supplied_diagnostic_cannot_be_null"> <source>Supplied diagnostic cannot be null.</source> <target state="translated">Bereitgestellte Diagnose darf nicht null sein.</target> <note /> </trans-unit> <trans-unit id="SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0"> <source>Syntax tree is required to accomplish the task but is not supported by document {0}.</source> <target state="translated">Die Syntaxstruktur ist zum Ausführen der Aufgabe erforderlich, wird aber vom Dokument "{0}" nicht unterstützt.</target> <note /> </trans-unit> <trans-unit id="The_solution_does_not_contain_the_specified_document"> <source>The solution does not contain the specified document.</source> <target state="translated">Die Lösung enthält nicht das angegebene Dokument.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Declaration_changes_scope_and_may_change_meaning"> <source>Warning: Declaration changes scope and may change meaning.</source> <target state="translated">Warnung: Die Deklaration ändert den Bereich und möglicherweise die Bedeutung.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/EditAndContinue/BidirectionalMap.cs
// 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. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.Differencing; namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct BidirectionalMap<T> { public readonly IReadOnlyDictionary<T, T> Forward; public readonly IReadOnlyDictionary<T, T> Reverse; public BidirectionalMap(IReadOnlyDictionary<T, T> forward, IReadOnlyDictionary<T, T> reverse) { Forward = forward; Reverse = reverse; } public BidirectionalMap(IEnumerable<KeyValuePair<T, T>> entries) { var map = new Dictionary<T, T>(); var reverseMap = new Dictionary<T, T>(); foreach (var entry in entries) { map.Add(entry.Key, entry.Value); reverseMap.Add(entry.Value, entry.Key); } Forward = map; Reverse = reverseMap; } public static BidirectionalMap<T> FromMatch(Match<T> match) => new(match.Matches, match.ReverseMatches); public bool IsDefaultOrEmpty => Forward == null || Forward.Count == 0; } }
// 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. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.Differencing; namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct BidirectionalMap<T> { public readonly IReadOnlyDictionary<T, T> Forward; public readonly IReadOnlyDictionary<T, T> Reverse; public BidirectionalMap(IReadOnlyDictionary<T, T> forward, IReadOnlyDictionary<T, T> reverse) { Forward = forward; Reverse = reverse; } public BidirectionalMap(IEnumerable<KeyValuePair<T, T>> entries) { var map = new Dictionary<T, T>(); var reverseMap = new Dictionary<T, T>(); foreach (var entry in entries) { map.Add(entry.Key, entry.Value); reverseMap.Add(entry.Value, entry.Key); } Forward = map; Reverse = reverseMap; } public static BidirectionalMap<T> FromMatch(Match<T> match) => new(match.Matches, match.ReverseMatches); public bool IsDefaultOrEmpty => Forward == null || Forward.Count == 0; } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/VisualBasicTest/BraceMatching/VisualBasicBraceMatcherTests.vb
' 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.Editor.UnitTests.BraceMatching Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.BraceMatching Public Class VisualBasicBraceMatcherTests Inherits AbstractBraceMatcherTests Protected Overrides Function CreateWorkspaceFromCode(code As String, options As ParseOptions) As TestWorkspace Return TestWorkspace.CreateVisualBasic(code) End Function Private Async Function TestInClassAsync(code As String, expectedCode As String) As Task Await TestAsync( "Class C" & vbCrLf & code & vbCrLf & "End Class", "Class C" & vbCrLf & expectedCode & vbCrLf & "End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestEmptyFile() As Task Dim code = "$$" Dim expected = "" Await TestAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAtFirstPositionInFile() As Task Dim code = "$$Class C" & vbCrLf & vbCrLf & "End Class" Dim expected = "Class C" & vbCrLf & vbCrLf & "End Class" Await TestAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAtLastPositionInFile() As Task Dim code = "Class C" & vbCrLf & vbCrLf & "End Class$$" Dim expected = "Class C" & vbCrLf & vbCrLf & "End Class" Await TestAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestCurlyBrace1() As Task Dim code = "Dim l As New List(Of Integer) From $${}" Dim expected = "Dim l As New List(Of Integer) From {[|}|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestCurlyBrace2() As Task Dim code = "Dim l As New List(Of Integer) From {$$}" Dim expected = "Dim l As New List(Of Integer) From {[|}|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestCurlyBrace3() As Task Dim code = "Dim l As New List(Of Integer) From {$$ }" Dim expected = "Dim l As New List(Of Integer) From { [|}|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestCurlyBrace4() As Task Dim code = "Dim l As New List(Of Integer) From { $$}" Dim expected = "Dim l As New List(Of Integer) From [|{|] }" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestCurlyBrace5() As Task Dim code = "Dim l As New List(Of Integer) From { }$$" Dim expected = "Dim l As New List(Of Integer) From [|{|] }" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestCurlyBrace6() As Task Dim code = "Dim l As New List(Of Integer) From {}$$" Dim expected = "Dim l As New List(Of Integer) From [|{|]}" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen1() As Task Dim code = "Dim l As New List$$(Of Func(Of Integer))" Dim expected = "Dim l As New List(Of Func(Of Integer)[|)|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen2() As Task Dim code = "Dim l As New List($$Of Func(Of Integer))" Dim expected = "Dim l As New List(Of Func(Of Integer)[|)|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen3() As Task Dim code = "Dim l As New List(Of Func$$(Of Integer))" Dim expected = "Dim l As New List(Of Func(Of Integer[|)|])" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen4() As Task Dim code = "Dim l As New List(Of Func($$Of Integer))" Dim expected = "Dim l As New List(Of Func(Of Integer[|)|])" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen5() As Task Dim code = "Dim l As New List(Of Func(Of Integer$$))" Dim expected = "Dim l As New List(Of Func[|(|]Of Integer))" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen6() As Task Dim code = "Dim l As New List(Of Func(Of Integer)$$)" Dim expected = "Dim l As New List(Of Func[|(|]Of Integer))" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen7() As Task Dim code = "Dim l As New List(Of Func(Of Integer)$$ )" Dim expected = "Dim l As New List(Of Func[|(|]Of Integer) )" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen8() As Task Dim code = "Dim l As New List(Of Func(Of Integer) $$)" Dim expected = "Dim l As New List[|(|]Of Func(Of Integer) )" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen9() As Task Dim code = "Dim l As New List(Of Func(Of Integer) )$$" Dim expected = "Dim l As New List[|(|]Of Func(Of Integer) )" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen10() As Task Dim code = "Dim l As New List(Of Func(Of Integer))$$" Dim expected = "Dim l As New List[|(|]Of Func(Of Integer))" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket1() As Task Dim code = "$$<Goo()> Dim i As Integer" Dim expected = "<Goo()[|>|] Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket2() As Task Dim code = "<$$Goo()> Dim i As Integer" Dim expected = "<Goo()[|>|] Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket3() As Task Dim code = "<Goo$$()> Dim i As Integer" Dim expected = "<Goo([|)|]> Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket4() As Task Dim code = "<Goo($$)> Dim i As Integer" Dim expected = "<Goo([|)|]> Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket5() As Task Dim code = "<Goo($$ )> Dim i As Integer" Dim expected = "<Goo( [|)|]> Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket6() As Task Dim code = "<Goo( $$)> Dim i As Integer" Dim expected = "<Goo[|(|] )> Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket7() As Task Dim code = "<Goo( )$$> Dim i As Integer" Dim expected = "<Goo[|(|] )> Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket8() As Task Dim code = "<Goo()$$> Dim i As Integer" Dim expected = "<Goo[|(|])> Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket9() As Task Dim code = "<Goo()$$ > Dim i As Integer" Dim expected = "<Goo[|(|]) > Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket10() As Task Dim code = "<Goo() $$> Dim i As Integer" Dim expected = "[|<|]Goo() > Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket11() As Task Dim code = "<Goo() >$$ Dim i As Integer" Dim expected = "[|<|]Goo() > Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket12() As Task Dim code = "<Goo()>$$ Dim i As Integer" Dim expected = "[|<|]Goo()> Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestString1() As Task Dim code = "Dim s As String = $$""Goo""" Dim expected = "Dim s As String = ""Goo[|""|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestString2() As Task Dim code = "Dim s As String = ""$$Goo""" Dim expected = "Dim s As String = ""Goo[|""|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestString3() As Task Dim code = "Dim s As String = ""Goo$$""" Dim expected = "Dim s As String = [|""|]Goo""" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestString4() As Task Dim code = "Dim s As String = ""Goo""$$" Dim expected = "Dim s As String = [|""|]Goo""" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestString5() As Task Dim code = "Dim s As String = ""Goo$$" Dim expected = "Dim s As String = ""Goo" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString1() As Task Dim code = "Dim s = $$[||]$""Goo""" Dim expected = "Dim s = $""Goo[|""|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString2() As Task Dim code = "Dim s = $""$$Goo""" Dim expected = "Dim s = $""Goo[|""|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString3() As Task Dim code = "Dim s = $""Goo$$""" Dim expected = "Dim s = [|$""|]Goo""" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString4() As Task Dim code = "Dim s = $""Goo""$$" Dim expected = "Dim s = [|$""|]Goo""" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString5() As Task Dim code = "Dim s = $"" $${x} """ Dim expected = "Dim s = $"" {x[|}|] """ Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString6() As Task Dim code = "Dim s = $"" {$$x} """ Dim expected = "Dim s = $"" {x[|}|] """ Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString7() As Task Dim code = "Dim s = $"" {x$$} """ Dim expected = "Dim s = $"" [|{|]x} """ Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString8() As Task Dim code = "Dim s = $"" {x}$$ """ Dim expected = "Dim s = $"" [|{|]x} """ Await TestInClassAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestConditionalDirectiveWithSingleMatchingDirective() As Task Dim code = <Text>Class C Sub Test() #If$$ CHK Then #End If End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>Class C Sub Test() #If CHK Then [|#End If|] End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestConditionalDirectiveWithTwoMatchingDirectives() As Task Dim code = <Text>Class C Sub Test() #If$$ CHK Then #Else #End If End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>Class C Sub Test() #If CHK Then [|#Else|] #End If End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestConditionalDirectiveWithAllMatchingDirectives() As Task Dim code = <Text>Class C Sub Test() #If CHK Then #ElseIf RET Then #Else #End If$$ End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>Class C Sub Test() [|#If|] CHK Then #ElseIf RET Then #Else #End If End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestRegionDirective() As Task Dim code = <Text>Class C $$#Region "Public Methods" Sub Test() End Sub #End Region End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>Class C #Region "Public Methods" Sub Test() End Sub [|#End Region|] End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterleavedDirectivesInner() As Task Dim code = <Text>#Const CHK = True Module Program Sub Main(args As String()) #If CHK Then #Region$$ "Public Methods" Console.Write(5) #ElseIf RET Then Console.Write(5) #Else #End If End Sub #End Region End Module </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>#Const CHK = True Module Program Sub Main(args As String()) #If CHK Then #Region "Public Methods" Console.Write(5) #ElseIf RET Then Console.Write(5) #Else #End If End Sub [|#End Region|] End Module </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterleavedDirectivesOuter() As Task Dim code = <Text>#Const CHK = True Module Program Sub Main(args As String()) #If$$ CHK Then #Region "Public Methods" Console.Write(5) #ElseIf RET Then Console.Write(5) #Else #End If End Sub #End Region End Module </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>#Const CHK = True Module Program Sub Main(args As String()) #If CHK Then #Region "Public Methods" Console.Write(5) [|#ElseIf|] RET Then Console.Write(5) #Else #End If End Sub #End Region End Module </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestUnmatchedDirective1() As Task Dim code = <Text>Class C $$#Region "Public Methods" Sub Test() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>Class C #Region "Public Methods" Sub Test() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestUnmatchedDirective2() As Task Dim code = <Text> #Enable Warning$$ Class C Sub Test() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text> #Enable Warning Class C Sub Test() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestUnmatchedIncompleteConditionalDirective() As Task Dim code = <Text> Class C Sub Test() #If$$ End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text> Class C Sub Test() [|#If|] End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestUnmatchedCompleteConditionalDirective() As Task Dim code = <Text> Class C Sub Test() #If$$ CHK Then End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text> Class C Sub Test() [|#If|] CHK Then End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestUnmatchedConditionalDirective() As Task Dim code = <Text> Class C Sub Test() #Else$$ End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text> Class C Sub Test() [|#Else|] End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function End Class End Namespace
' 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.Editor.UnitTests.BraceMatching Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.BraceMatching Public Class VisualBasicBraceMatcherTests Inherits AbstractBraceMatcherTests Protected Overrides Function CreateWorkspaceFromCode(code As String, options As ParseOptions) As TestWorkspace Return TestWorkspace.CreateVisualBasic(code) End Function Private Async Function TestInClassAsync(code As String, expectedCode As String) As Task Await TestAsync( "Class C" & vbCrLf & code & vbCrLf & "End Class", "Class C" & vbCrLf & expectedCode & vbCrLf & "End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestEmptyFile() As Task Dim code = "$$" Dim expected = "" Await TestAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAtFirstPositionInFile() As Task Dim code = "$$Class C" & vbCrLf & vbCrLf & "End Class" Dim expected = "Class C" & vbCrLf & vbCrLf & "End Class" Await TestAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAtLastPositionInFile() As Task Dim code = "Class C" & vbCrLf & vbCrLf & "End Class$$" Dim expected = "Class C" & vbCrLf & vbCrLf & "End Class" Await TestAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestCurlyBrace1() As Task Dim code = "Dim l As New List(Of Integer) From $${}" Dim expected = "Dim l As New List(Of Integer) From {[|}|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestCurlyBrace2() As Task Dim code = "Dim l As New List(Of Integer) From {$$}" Dim expected = "Dim l As New List(Of Integer) From {[|}|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestCurlyBrace3() As Task Dim code = "Dim l As New List(Of Integer) From {$$ }" Dim expected = "Dim l As New List(Of Integer) From { [|}|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestCurlyBrace4() As Task Dim code = "Dim l As New List(Of Integer) From { $$}" Dim expected = "Dim l As New List(Of Integer) From [|{|] }" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestCurlyBrace5() As Task Dim code = "Dim l As New List(Of Integer) From { }$$" Dim expected = "Dim l As New List(Of Integer) From [|{|] }" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestCurlyBrace6() As Task Dim code = "Dim l As New List(Of Integer) From {}$$" Dim expected = "Dim l As New List(Of Integer) From [|{|]}" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen1() As Task Dim code = "Dim l As New List$$(Of Func(Of Integer))" Dim expected = "Dim l As New List(Of Func(Of Integer)[|)|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen2() As Task Dim code = "Dim l As New List($$Of Func(Of Integer))" Dim expected = "Dim l As New List(Of Func(Of Integer)[|)|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen3() As Task Dim code = "Dim l As New List(Of Func$$(Of Integer))" Dim expected = "Dim l As New List(Of Func(Of Integer[|)|])" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen4() As Task Dim code = "Dim l As New List(Of Func($$Of Integer))" Dim expected = "Dim l As New List(Of Func(Of Integer[|)|])" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen5() As Task Dim code = "Dim l As New List(Of Func(Of Integer$$))" Dim expected = "Dim l As New List(Of Func[|(|]Of Integer))" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen6() As Task Dim code = "Dim l As New List(Of Func(Of Integer)$$)" Dim expected = "Dim l As New List(Of Func[|(|]Of Integer))" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen7() As Task Dim code = "Dim l As New List(Of Func(Of Integer)$$ )" Dim expected = "Dim l As New List(Of Func[|(|]Of Integer) )" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen8() As Task Dim code = "Dim l As New List(Of Func(Of Integer) $$)" Dim expected = "Dim l As New List[|(|]Of Func(Of Integer) )" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen9() As Task Dim code = "Dim l As New List(Of Func(Of Integer) )$$" Dim expected = "Dim l As New List[|(|]Of Func(Of Integer) )" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestNestedParen10() As Task Dim code = "Dim l As New List(Of Func(Of Integer))$$" Dim expected = "Dim l As New List[|(|]Of Func(Of Integer))" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket1() As Task Dim code = "$$<Goo()> Dim i As Integer" Dim expected = "<Goo()[|>|] Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket2() As Task Dim code = "<$$Goo()> Dim i As Integer" Dim expected = "<Goo()[|>|] Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket3() As Task Dim code = "<Goo$$()> Dim i As Integer" Dim expected = "<Goo([|)|]> Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket4() As Task Dim code = "<Goo($$)> Dim i As Integer" Dim expected = "<Goo([|)|]> Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket5() As Task Dim code = "<Goo($$ )> Dim i As Integer" Dim expected = "<Goo( [|)|]> Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket6() As Task Dim code = "<Goo( $$)> Dim i As Integer" Dim expected = "<Goo[|(|] )> Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket7() As Task Dim code = "<Goo( )$$> Dim i As Integer" Dim expected = "<Goo[|(|] )> Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket8() As Task Dim code = "<Goo()$$> Dim i As Integer" Dim expected = "<Goo[|(|])> Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket9() As Task Dim code = "<Goo()$$ > Dim i As Integer" Dim expected = "<Goo[|(|]) > Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket10() As Task Dim code = "<Goo() $$> Dim i As Integer" Dim expected = "[|<|]Goo() > Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket11() As Task Dim code = "<Goo() >$$ Dim i As Integer" Dim expected = "[|<|]Goo() > Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestAngleBracket12() As Task Dim code = "<Goo()>$$ Dim i As Integer" Dim expected = "[|<|]Goo()> Dim i As Integer" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestString1() As Task Dim code = "Dim s As String = $$""Goo""" Dim expected = "Dim s As String = ""Goo[|""|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestString2() As Task Dim code = "Dim s As String = ""$$Goo""" Dim expected = "Dim s As String = ""Goo[|""|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestString3() As Task Dim code = "Dim s As String = ""Goo$$""" Dim expected = "Dim s As String = [|""|]Goo""" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestString4() As Task Dim code = "Dim s As String = ""Goo""$$" Dim expected = "Dim s As String = [|""|]Goo""" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestString5() As Task Dim code = "Dim s As String = ""Goo$$" Dim expected = "Dim s As String = ""Goo" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString1() As Task Dim code = "Dim s = $$[||]$""Goo""" Dim expected = "Dim s = $""Goo[|""|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString2() As Task Dim code = "Dim s = $""$$Goo""" Dim expected = "Dim s = $""Goo[|""|]" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString3() As Task Dim code = "Dim s = $""Goo$$""" Dim expected = "Dim s = [|$""|]Goo""" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString4() As Task Dim code = "Dim s = $""Goo""$$" Dim expected = "Dim s = [|$""|]Goo""" Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString5() As Task Dim code = "Dim s = $"" $${x} """ Dim expected = "Dim s = $"" {x[|}|] """ Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString6() As Task Dim code = "Dim s = $"" {$$x} """ Dim expected = "Dim s = $"" {x[|}|] """ Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString7() As Task Dim code = "Dim s = $"" {x$$} """ Dim expected = "Dim s = $"" [|{|]x} """ Await TestInClassAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterpolatedString8() As Task Dim code = "Dim s = $"" {x}$$ """ Dim expected = "Dim s = $"" [|{|]x} """ Await TestInClassAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestConditionalDirectiveWithSingleMatchingDirective() As Task Dim code = <Text>Class C Sub Test() #If$$ CHK Then #End If End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>Class C Sub Test() #If CHK Then [|#End If|] End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestConditionalDirectiveWithTwoMatchingDirectives() As Task Dim code = <Text>Class C Sub Test() #If$$ CHK Then #Else #End If End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>Class C Sub Test() #If CHK Then [|#Else|] #End If End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestConditionalDirectiveWithAllMatchingDirectives() As Task Dim code = <Text>Class C Sub Test() #If CHK Then #ElseIf RET Then #Else #End If$$ End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>Class C Sub Test() [|#If|] CHK Then #ElseIf RET Then #Else #End If End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestRegionDirective() As Task Dim code = <Text>Class C $$#Region "Public Methods" Sub Test() End Sub #End Region End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>Class C #Region "Public Methods" Sub Test() End Sub [|#End Region|] End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterleavedDirectivesInner() As Task Dim code = <Text>#Const CHK = True Module Program Sub Main(args As String()) #If CHK Then #Region$$ "Public Methods" Console.Write(5) #ElseIf RET Then Console.Write(5) #Else #End If End Sub #End Region End Module </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>#Const CHK = True Module Program Sub Main(args As String()) #If CHK Then #Region "Public Methods" Console.Write(5) #ElseIf RET Then Console.Write(5) #Else #End If End Sub [|#End Region|] End Module </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestInterleavedDirectivesOuter() As Task Dim code = <Text>#Const CHK = True Module Program Sub Main(args As String()) #If$$ CHK Then #Region "Public Methods" Console.Write(5) #ElseIf RET Then Console.Write(5) #Else #End If End Sub #End Region End Module </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>#Const CHK = True Module Program Sub Main(args As String()) #If CHK Then #Region "Public Methods" Console.Write(5) [|#ElseIf|] RET Then Console.Write(5) #Else #End If End Sub #End Region End Module </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestUnmatchedDirective1() As Task Dim code = <Text>Class C $$#Region "Public Methods" Sub Test() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>Class C #Region "Public Methods" Sub Test() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestUnmatchedDirective2() As Task Dim code = <Text> #Enable Warning$$ Class C Sub Test() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text> #Enable Warning Class C Sub Test() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestUnmatchedIncompleteConditionalDirective() As Task Dim code = <Text> Class C Sub Test() #If$$ End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text> Class C Sub Test() [|#If|] End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestUnmatchedCompleteConditionalDirective() As Task Dim code = <Text> Class C Sub Test() #If$$ CHK Then End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text> Class C Sub Test() [|#If|] CHK Then End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function <WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")> <WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)> Public Async Function TestUnmatchedConditionalDirective() As Task Dim code = <Text> Class C Sub Test() #Else$$ End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text> Class C Sub Test() [|#Else|] End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf) Await TestAsync(code, expected) End Function End Class End Namespace
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Test2/InlineHints/CSharpInlineParameterNameHintsTests.vb
' 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. Namespace Microsoft.CodeAnalysis.Editor.UnitTests.InlineHints Public Class CSharpInlineParameterNameHintsTests Inherits AbstractInlineHintsTests <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNoParameterSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod() { return 5; } void Main() { testMethod(); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOneParameterSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x) { return x; } void Main() { testMethod({|x:|}5); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestTwoParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod({|x:|}5, {|y:|}2); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNegativeNumberParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod({|x:|}-5, {|y:|}2); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestLiteralNestedCastParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod({|x:|}(int)(double)(int)5.5, {|y:|}2); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestObjectCreationParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}(int)5.5, {|y:|}new object()); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestCastingANegativeSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}(int)-5.5, {|y:|}new object()); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNegatingACastSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}-(int)5.5, {|y:|}new object()); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMissingParameterNameSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int) { return 5; } void Main() { testMethod(); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestDelegateParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> delegate void D(int x); class C { public static void M1(int i) { } } class Test { static void Main() { D cd1 = new D(C.M1); cd1({|x:|}-1); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestFunctionPointerNoParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" AllowUnsafe="true"> <Document> unsafe class Example { void Example(delegate*&lt;int, void&gt; f) { f(42); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestParamsArgument() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { public void UseParams(params int[] list) { } public void Main(string[] args) { UseParams({|list:|}1, 2, 3, 4, 5, 6); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestAttributesArgument() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; [Obsolete({|message:|}"test")] class Foo { } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestIncompleteFunctionCall() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}-(int)5.5,); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestInterpolatedString() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { string testMethod(string x) { return x; } void Main() { testMethod({|x:|}$""); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(47696, "https://github.com/dotnet/roslyn/issues/47696")> Public Async Function TestRecordBaseType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> record Base(int Alice, int Bob); record Derived(int Other) : Base({|Alice:|}2, {|Bob:|}2); </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(47696, "https://github.com/dotnet/roslyn/issues/47696")> Public Async Function TestClassBaseType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Base { public Base(int paramName) {} } class Derived : Base { public Derived() : base({|paramName:|}20) {} } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotOnEnableDisableBoolean1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void EnableLogging(bool value) { } void Main() { EnableLogging(true); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotOnEnableDisableBoolean2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void DisableLogging(bool value) { } void Main() { DisableLogging(true); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnEnableDisableNonBoolean1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void EnableLogging(string value) { } void Main() { EnableLogging({|value:|}"IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnEnableDisableNonBoolean2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void DisableLogging(string value) { } void Main() { DisableLogging({|value:|}"IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnSetMethodWithClearContext() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void SetClassification(string classification) { } void Main() { SetClassification("IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnSetMethodWithUnclearContext() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void SetClassification(string values) { } void Main() { SetClassification({|values:|}"IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithAlphaSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int objA, int objB, int objC) { } void Main() { Goo(1, 2, 3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNonAlphaSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int objA, int objB, int nonobjC) { } void Main() { Goo({|objA:|}1, {|objB:|}2, {|nonobjC:|}3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNumericSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int obj1, int obj2, int obj3) { } void Main() { Goo(1, 2, 3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNonNumericSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int obj1, int obj2, int nonobj3) { } void Main() { Goo({|obj1:|}1, {|obj2:|}2, {|nonobj3:|}3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(48910, "https://github.com/dotnet/roslyn/issues/48910")> Public Async Function TestNullableSuppression() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> #nullable enable class A { void M(string x) { } void Main() { M({|x:|}null!); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(46614, "https://github.com/dotnet/roslyn/issues/46614")> Public Async Function TestIndexerParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class TempRecord { // Array of temperature values float[] temps = new float[10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F, 61.3F, 65.9F, 62.1F, 59.2F, 57.5F }; // To enable client code to validate input // when accessing your indexer. public int Length => temps.Length; // Indexer declaration. // If index is out of range, the temps array will throw the exception. public float this[int index] { get => temps[index]; set => temps[index] = value; } } class Program { static void Main() { var tempRecord = new TempRecord(); // Use the indexer's set accessor var temp = tempRecord[{|index:|}3]; } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function End Class End Namespace
' 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. Namespace Microsoft.CodeAnalysis.Editor.UnitTests.InlineHints Public Class CSharpInlineParameterNameHintsTests Inherits AbstractInlineHintsTests <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNoParameterSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod() { return 5; } void Main() { testMethod(); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOneParameterSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x) { return x; } void Main() { testMethod({|x:|}5); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestTwoParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod({|x:|}5, {|y:|}2); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNegativeNumberParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod({|x:|}-5, {|y:|}2); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestLiteralNestedCastParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod({|x:|}(int)(double)(int)5.5, {|y:|}2); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestObjectCreationParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}(int)5.5, {|y:|}new object()); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestCastingANegativeSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}(int)-5.5, {|y:|}new object()); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNegatingACastSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}-(int)5.5, {|y:|}new object()); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMissingParameterNameSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int) { return 5; } void Main() { testMethod(); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestDelegateParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> delegate void D(int x); class C { public static void M1(int i) { } } class Test { static void Main() { D cd1 = new D(C.M1); cd1({|x:|}-1); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestFunctionPointerNoParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" AllowUnsafe="true"> <Document> unsafe class Example { void Example(delegate*&lt;int, void&gt; f) { f(42); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestParamsArgument() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { public void UseParams(params int[] list) { } public void Main(string[] args) { UseParams({|list:|}1, 2, 3, 4, 5, 6); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestAttributesArgument() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; [Obsolete({|message:|}"test")] class Foo { } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestIncompleteFunctionCall() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}-(int)5.5,); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestInterpolatedString() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { string testMethod(string x) { return x; } void Main() { testMethod({|x:|}$""); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(47696, "https://github.com/dotnet/roslyn/issues/47696")> Public Async Function TestRecordBaseType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> record Base(int Alice, int Bob); record Derived(int Other) : Base({|Alice:|}2, {|Bob:|}2); </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(47696, "https://github.com/dotnet/roslyn/issues/47696")> Public Async Function TestClassBaseType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Base { public Base(int paramName) {} } class Derived : Base { public Derived() : base({|paramName:|}20) {} } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotOnEnableDisableBoolean1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void EnableLogging(bool value) { } void Main() { EnableLogging(true); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotOnEnableDisableBoolean2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void DisableLogging(bool value) { } void Main() { DisableLogging(true); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnEnableDisableNonBoolean1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void EnableLogging(string value) { } void Main() { EnableLogging({|value:|}"IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnEnableDisableNonBoolean2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void DisableLogging(string value) { } void Main() { DisableLogging({|value:|}"IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnSetMethodWithClearContext() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void SetClassification(string classification) { } void Main() { SetClassification("IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnSetMethodWithUnclearContext() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void SetClassification(string values) { } void Main() { SetClassification({|values:|}"IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithAlphaSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int objA, int objB, int objC) { } void Main() { Goo(1, 2, 3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNonAlphaSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int objA, int objB, int nonobjC) { } void Main() { Goo({|objA:|}1, {|objB:|}2, {|nonobjC:|}3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNumericSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int obj1, int obj2, int obj3) { } void Main() { Goo(1, 2, 3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNonNumericSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int obj1, int obj2, int nonobj3) { } void Main() { Goo({|obj1:|}1, {|obj2:|}2, {|nonobj3:|}3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(48910, "https://github.com/dotnet/roslyn/issues/48910")> Public Async Function TestNullableSuppression() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> #nullable enable class A { void M(string x) { } void Main() { M({|x:|}null!); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(46614, "https://github.com/dotnet/roslyn/issues/46614")> Public Async Function TestIndexerParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class TempRecord { // Array of temperature values float[] temps = new float[10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F, 61.3F, 65.9F, 62.1F, 59.2F, 57.5F }; // To enable client code to validate input // when accessing your indexer. public int Length => temps.Length; // Indexer declaration. // If index is out of range, the temps array will throw the exception. public float this[int index] { get => temps[index]; set => temps[index] = value; } } class Program { static void Main() { var tempRecord = new TempRecord(); // Use the indexer's set accessor var temp = tempRecord[{|index:|}3]; } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function End Class End Namespace
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/DiaSymReader/Writer/ISymUnmanagedWriter.cs
// 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. #nullable disable #pragma warning disable 436 // SuppressUnmanagedCodeSecurityAttribute defined in source and mscorlib using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.DiaSymReader { [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("98ECEE1E-752D-11d3-8D56-00C04F680B2B"), SuppressUnmanagedCodeSecurity] internal interface IPdbWriter { int __SetPath(/*[in] const WCHAR* szFullPathName, [in] IStream* pIStream, [in] BOOL fFullBuild*/); int __OpenMod(/*[in] const WCHAR* szModuleName, [in] const WCHAR* szFileName*/); int __CloseMod(); int __GetPath(/*[in] DWORD ccData,[out] DWORD* pccData,[out, size_is(ccData),length_is(*pccData)] WCHAR szPath[]*/); void GetSignatureAge(out uint sig, out int age); } /// <summary> /// The highest version of the interface available on Desktop FX 4.0+. /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("DCF7780D-BDE9-45DF-ACFE-21731A32000C"), SuppressUnmanagedCodeSecurity] internal unsafe interface ISymUnmanagedWriter5 { #region ISymUnmanagedWriter ISymUnmanagedDocumentWriter DefineDocument(string url, ref Guid language, ref Guid languageVendor, ref Guid documentType); void SetUserEntryPoint(int entryMethodToken); void OpenMethod(uint methodToken); void CloseMethod(); uint OpenScope(int startOffset); void CloseScope(int endOffset); void SetScopeRange(uint scopeID, uint startOffset, uint endOffset); void DefineLocalVariable(string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint startOffset, uint endOffset); void DefineParameter(string name, uint attributes, uint sequence, uint addrKind, uint addr1, uint addr2, uint addr3); void DefineField(uint parent, string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint addr3); void DefineGlobalVariable(string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint addr3); void Close(); void SetSymAttribute(uint parent, string name, int length, byte* data); void OpenNamespace(string name); void CloseNamespace(); void UsingNamespace(string fullName); void SetMethodSourceRange(ISymUnmanagedDocumentWriter startDoc, uint startLine, uint startColumn, object endDoc, uint endLine, uint endColumn); void Initialize([MarshalAs(UnmanagedType.IUnknown)] object emitter, string filename, [MarshalAs(UnmanagedType.IUnknown)] object ptrIStream, bool fullBuild); void GetDebugInfo(ref ImageDebugDirectory debugDirectory, uint dataCount, out uint dataCountPtr, byte* data); void DefineSequencePoints(ISymUnmanagedDocumentWriter document, int count, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] offsets, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] lines, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] columns, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endLines, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endColumns); void RemapToken(uint oldToken, uint newToken); void Initialize2([MarshalAs(UnmanagedType.IUnknown)] object emitter, string tempfilename, [MarshalAs(UnmanagedType.IUnknown)] object ptrIStream, bool fullBuild, string finalfilename); void DefineConstant(string name, object value, uint sig, byte* signature); void Abort(); #endregion #region ISymUnmanagedWriter2 void DefineLocalVariable2(string name, int attributes, int localSignatureToken, uint addrKind, int index, uint addr2, uint addr3, uint startOffset, uint endOffset); void DefineGlobalVariable2(string name, int attributes, int sigToken, uint addrKind, uint addr1, uint addr2, uint addr3); /// <remarks> /// <paramref name="value"/> has type <see cref="VariantStructure"/>, rather than <see cref="object"/>, /// so that we can do custom marshalling of <see cref="System.DateTime"/>. Unfortunately, .NET marshals /// <see cref="System.DateTime"/>s as the number of days since 1899/12/30, whereas the native VB compiler /// marshalled them as the number of ticks since the Unix epoch (i.e. a much, much larger number). /// </remarks> void DefineConstant2([MarshalAs(UnmanagedType.LPWStr)] string name, VariantStructure value, int constantSignatureToken); #endregion #region ISymUnmanagedWriter3 void OpenMethod2(uint methodToken, int sectionIndex, int offsetRelativeOffset); void Commit(); #endregion #region ISymUnmanagedWriter4 void GetDebugInfoWithPadding(ref ImageDebugDirectory debugDirectory, uint dataCount, out uint dataCountPtr, byte* data); #endregion #region ISymUnmanagedWriter5 /// <summary> /// Open a special custom data section to emit token to source span mapping information into. /// Opening this section while a method is already open or vice versa is an error. /// </summary> void OpenMapTokensToSourceSpans(); /// <summary> /// Close the special custom data section for token to source span mapping /// information. Once it is closed no more mapping information can be added. /// </summary> void CloseMapTokensToSourceSpans(); /// <summary> /// Maps the given metadata token to the given source line span in the specified source file. /// Must be called between calls to <see cref="OpenMapTokensToSourceSpans"/> and <see cref="CloseMapTokensToSourceSpans"/>. /// </summary> void MapTokenToSourceSpan(int token, ISymUnmanagedDocumentWriter document, int startLine, int startColumn, int endLine, int endColumn); #endregion } /// <summary> /// The highest version of the interface available in Microsoft.DiaSymReader.Native. /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("5ba52f3b-6bf8-40fc-b476-d39c529b331e"), SuppressUnmanagedCodeSecurity] internal interface ISymUnmanagedWriter8 : ISymUnmanagedWriter5 { // ISymUnmanagedWriter, ISymUnmanagedWriter2, ISymUnmanagedWriter3, ISymUnmanagedWriter4, ISymUnmanagedWriter5 void _VtblGap1_33(); // ISymUnmanagedWriter6 void InitializeDeterministic([MarshalAs(UnmanagedType.IUnknown)] object emitter, [MarshalAs(UnmanagedType.IUnknown)] object stream); // ISymUnmanagedWriter7 unsafe void UpdateSignatureByHashingContent([In] byte* buffer, int size); // ISymUnmanagedWriter8 void UpdateSignature(Guid pdbId, uint stamp, int age); unsafe void SetSourceServerData([In] byte* data, int size); unsafe void SetSourceLinkData([In] byte* data, int size); } /// <summary> /// A struct with the same size and layout as the native VARIANT type: /// 2 bytes for a discriminator (i.e. which type of variant it is). /// 6 bytes of padding /// 8 or 16 bytes of data /// </summary> [StructLayout(LayoutKind.Explicit)] internal struct VariantStructure { public VariantStructure(DateTime date) : this() // Need this to avoid errors about the uninteresting union fields. { _longValue = date.Ticks; #pragma warning disable CS0618 // Type or member is obsolete _type = (short)VarEnum.VT_DATE; #pragma warning restore CS0618 } [FieldOffset(0)] private readonly short _type; [FieldOffset(8)] private readonly long _longValue; /// <summary> /// This field determines the size of the struct /// (16 bytes on 32-bit platforms, 24 bytes on 64-bit platforms). /// </summary> [FieldOffset(8)] private readonly VariantPadding _padding; // Fields below this point are only used to make inspecting this struct in the debugger easier. [FieldOffset(0)] // NB: 0, not 8 private readonly decimal _decimalValue; [FieldOffset(8)] private readonly bool _boolValue; [FieldOffset(8)] private readonly long _intValue; [FieldOffset(8)] private readonly double _doubleValue; } /// <summary> /// This type is 8 bytes on a 32-bit platforms and 16 bytes on 64-bit platforms. /// </summary> [StructLayout(LayoutKind.Sequential)] internal unsafe struct VariantPadding { public readonly byte* Data2; public readonly byte* Data3; } [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct ImageDebugDirectory { internal int Characteristics; internal int TimeDateStamp; internal short MajorVersion; internal short MinorVersion; internal int Type; internal int SizeOfData; internal int AddressOfRawData; internal int PointerToRawData; } }
// 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. #nullable disable #pragma warning disable 436 // SuppressUnmanagedCodeSecurityAttribute defined in source and mscorlib using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.DiaSymReader { [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("98ECEE1E-752D-11d3-8D56-00C04F680B2B"), SuppressUnmanagedCodeSecurity] internal interface IPdbWriter { int __SetPath(/*[in] const WCHAR* szFullPathName, [in] IStream* pIStream, [in] BOOL fFullBuild*/); int __OpenMod(/*[in] const WCHAR* szModuleName, [in] const WCHAR* szFileName*/); int __CloseMod(); int __GetPath(/*[in] DWORD ccData,[out] DWORD* pccData,[out, size_is(ccData),length_is(*pccData)] WCHAR szPath[]*/); void GetSignatureAge(out uint sig, out int age); } /// <summary> /// The highest version of the interface available on Desktop FX 4.0+. /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("DCF7780D-BDE9-45DF-ACFE-21731A32000C"), SuppressUnmanagedCodeSecurity] internal unsafe interface ISymUnmanagedWriter5 { #region ISymUnmanagedWriter ISymUnmanagedDocumentWriter DefineDocument(string url, ref Guid language, ref Guid languageVendor, ref Guid documentType); void SetUserEntryPoint(int entryMethodToken); void OpenMethod(uint methodToken); void CloseMethod(); uint OpenScope(int startOffset); void CloseScope(int endOffset); void SetScopeRange(uint scopeID, uint startOffset, uint endOffset); void DefineLocalVariable(string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint startOffset, uint endOffset); void DefineParameter(string name, uint attributes, uint sequence, uint addrKind, uint addr1, uint addr2, uint addr3); void DefineField(uint parent, string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint addr3); void DefineGlobalVariable(string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint addr3); void Close(); void SetSymAttribute(uint parent, string name, int length, byte* data); void OpenNamespace(string name); void CloseNamespace(); void UsingNamespace(string fullName); void SetMethodSourceRange(ISymUnmanagedDocumentWriter startDoc, uint startLine, uint startColumn, object endDoc, uint endLine, uint endColumn); void Initialize([MarshalAs(UnmanagedType.IUnknown)] object emitter, string filename, [MarshalAs(UnmanagedType.IUnknown)] object ptrIStream, bool fullBuild); void GetDebugInfo(ref ImageDebugDirectory debugDirectory, uint dataCount, out uint dataCountPtr, byte* data); void DefineSequencePoints(ISymUnmanagedDocumentWriter document, int count, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] offsets, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] lines, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] columns, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endLines, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endColumns); void RemapToken(uint oldToken, uint newToken); void Initialize2([MarshalAs(UnmanagedType.IUnknown)] object emitter, string tempfilename, [MarshalAs(UnmanagedType.IUnknown)] object ptrIStream, bool fullBuild, string finalfilename); void DefineConstant(string name, object value, uint sig, byte* signature); void Abort(); #endregion #region ISymUnmanagedWriter2 void DefineLocalVariable2(string name, int attributes, int localSignatureToken, uint addrKind, int index, uint addr2, uint addr3, uint startOffset, uint endOffset); void DefineGlobalVariable2(string name, int attributes, int sigToken, uint addrKind, uint addr1, uint addr2, uint addr3); /// <remarks> /// <paramref name="value"/> has type <see cref="VariantStructure"/>, rather than <see cref="object"/>, /// so that we can do custom marshalling of <see cref="System.DateTime"/>. Unfortunately, .NET marshals /// <see cref="System.DateTime"/>s as the number of days since 1899/12/30, whereas the native VB compiler /// marshalled them as the number of ticks since the Unix epoch (i.e. a much, much larger number). /// </remarks> void DefineConstant2([MarshalAs(UnmanagedType.LPWStr)] string name, VariantStructure value, int constantSignatureToken); #endregion #region ISymUnmanagedWriter3 void OpenMethod2(uint methodToken, int sectionIndex, int offsetRelativeOffset); void Commit(); #endregion #region ISymUnmanagedWriter4 void GetDebugInfoWithPadding(ref ImageDebugDirectory debugDirectory, uint dataCount, out uint dataCountPtr, byte* data); #endregion #region ISymUnmanagedWriter5 /// <summary> /// Open a special custom data section to emit token to source span mapping information into. /// Opening this section while a method is already open or vice versa is an error. /// </summary> void OpenMapTokensToSourceSpans(); /// <summary> /// Close the special custom data section for token to source span mapping /// information. Once it is closed no more mapping information can be added. /// </summary> void CloseMapTokensToSourceSpans(); /// <summary> /// Maps the given metadata token to the given source line span in the specified source file. /// Must be called between calls to <see cref="OpenMapTokensToSourceSpans"/> and <see cref="CloseMapTokensToSourceSpans"/>. /// </summary> void MapTokenToSourceSpan(int token, ISymUnmanagedDocumentWriter document, int startLine, int startColumn, int endLine, int endColumn); #endregion } /// <summary> /// The highest version of the interface available in Microsoft.DiaSymReader.Native. /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("5ba52f3b-6bf8-40fc-b476-d39c529b331e"), SuppressUnmanagedCodeSecurity] internal interface ISymUnmanagedWriter8 : ISymUnmanagedWriter5 { // ISymUnmanagedWriter, ISymUnmanagedWriter2, ISymUnmanagedWriter3, ISymUnmanagedWriter4, ISymUnmanagedWriter5 void _VtblGap1_33(); // ISymUnmanagedWriter6 void InitializeDeterministic([MarshalAs(UnmanagedType.IUnknown)] object emitter, [MarshalAs(UnmanagedType.IUnknown)] object stream); // ISymUnmanagedWriter7 unsafe void UpdateSignatureByHashingContent([In] byte* buffer, int size); // ISymUnmanagedWriter8 void UpdateSignature(Guid pdbId, uint stamp, int age); unsafe void SetSourceServerData([In] byte* data, int size); unsafe void SetSourceLinkData([In] byte* data, int size); } /// <summary> /// A struct with the same size and layout as the native VARIANT type: /// 2 bytes for a discriminator (i.e. which type of variant it is). /// 6 bytes of padding /// 8 or 16 bytes of data /// </summary> [StructLayout(LayoutKind.Explicit)] internal struct VariantStructure { public VariantStructure(DateTime date) : this() // Need this to avoid errors about the uninteresting union fields. { _longValue = date.Ticks; #pragma warning disable CS0618 // Type or member is obsolete _type = (short)VarEnum.VT_DATE; #pragma warning restore CS0618 } [FieldOffset(0)] private readonly short _type; [FieldOffset(8)] private readonly long _longValue; /// <summary> /// This field determines the size of the struct /// (16 bytes on 32-bit platforms, 24 bytes on 64-bit platforms). /// </summary> [FieldOffset(8)] private readonly VariantPadding _padding; // Fields below this point are only used to make inspecting this struct in the debugger easier. [FieldOffset(0)] // NB: 0, not 8 private readonly decimal _decimalValue; [FieldOffset(8)] private readonly bool _boolValue; [FieldOffset(8)] private readonly long _intValue; [FieldOffset(8)] private readonly double _doubleValue; } /// <summary> /// This type is 8 bytes on a 32-bit platforms and 16 bytes on 64-bit platforms. /// </summary> [StructLayout(LayoutKind.Sequential)] internal unsafe struct VariantPadding { public readonly byte* Data2; public readonly byte* Data3; } [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct ImageDebugDirectory { internal int Characteristics; internal int TimeDateStamp; internal short MajorVersion; internal short MinorVersion; internal int Type; internal int SizeOfData; internal int AddressOfRawData; internal int PointerToRawData; } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/GenerateMember/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.State.cs
// 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. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal partial class AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> { internal abstract class State { public INamedTypeSymbol ContainingType { get; protected set; } public INamedTypeSymbol TypeToGenerateIn { get; protected set; } public bool IsStatic { get; protected set; } public bool IsContainedInUnsafeType { get; protected set; } // Just the name of the method. i.e. "Goo" in "X.Goo" or "X.Goo()" public SyntaxToken IdentifierToken { get; protected set; } public TSimpleNameSyntax SimpleNameOpt { get; protected set; } // The entire expression containing the name, not including the invocation. i.e. "X.Goo" // in "X.Goo()". public TExpressionSyntax SimpleNameOrMemberAccessExpression { get; protected set; } public TInvocationExpressionSyntax InvocationExpressionOpt { get; protected set; } public bool IsInConditionalAccessExpression { get; protected set; } public bool IsWrittenTo { get; protected set; } public SignatureInfo SignatureInfo { get; protected set; } public MethodKind MethodKind { get; internal set; } public MethodGenerationKind MethodGenerationKind { get; protected set; } protected Location location = null; public Location Location { get { if (IdentifierToken.SyntaxTree != null) { return IdentifierToken.GetLocation(); } return location; } } protected async Task<bool> TryFinishInitializingStateAsync(TService service, SemanticDocument document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); TypeToGenerateIn = await SymbolFinder.FindSourceDefinitionAsync(TypeToGenerateIn, document.Project.Solution, cancellationToken).ConfigureAwait(false) as INamedTypeSymbol; if (TypeToGenerateIn.IsErrorType()) { return false; } if (!ValidateTypeToGenerateIn(TypeToGenerateIn, IsStatic, ClassInterfaceModuleStructTypes)) { return false; } if (!CodeGenerator.CanAdd(document.Project.Solution, TypeToGenerateIn, cancellationToken)) { return false; } // Ok. It either didn't bind to any symbols, or it bound to a symbol but with // errors. In the former case we definitely want to offer to generate a method. In // the latter case, we want to generate a method *unless* there's an existing method // with the same signature. var existingMethods = TypeToGenerateIn.GetMembers(IdentifierToken.ValueText) .OfType<IMethodSymbol>(); var destinationProvider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var syntaxFacts = destinationProvider.GetService<ISyntaxFactsService>(); var syntaxFactory = destinationProvider.GetService<SyntaxGenerator>(); IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); var generatedMethod = await SignatureInfo.GenerateMethodAsync(syntaxFactory, false, cancellationToken).ConfigureAwait(false); return !existingMethods.Any(m => SignatureComparer.Instance.HaveSameSignature(m, generatedMethod, caseSensitive: syntaxFacts.IsCaseSensitive, compareParameterName: true, isParameterCaseSensitive: syntaxFacts.IsCaseSensitive)); } } } }
// 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. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal partial class AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> { internal abstract class State { public INamedTypeSymbol ContainingType { get; protected set; } public INamedTypeSymbol TypeToGenerateIn { get; protected set; } public bool IsStatic { get; protected set; } public bool IsContainedInUnsafeType { get; protected set; } // Just the name of the method. i.e. "Goo" in "X.Goo" or "X.Goo()" public SyntaxToken IdentifierToken { get; protected set; } public TSimpleNameSyntax SimpleNameOpt { get; protected set; } // The entire expression containing the name, not including the invocation. i.e. "X.Goo" // in "X.Goo()". public TExpressionSyntax SimpleNameOrMemberAccessExpression { get; protected set; } public TInvocationExpressionSyntax InvocationExpressionOpt { get; protected set; } public bool IsInConditionalAccessExpression { get; protected set; } public bool IsWrittenTo { get; protected set; } public SignatureInfo SignatureInfo { get; protected set; } public MethodKind MethodKind { get; internal set; } public MethodGenerationKind MethodGenerationKind { get; protected set; } protected Location location = null; public Location Location { get { if (IdentifierToken.SyntaxTree != null) { return IdentifierToken.GetLocation(); } return location; } } protected async Task<bool> TryFinishInitializingStateAsync(TService service, SemanticDocument document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); TypeToGenerateIn = await SymbolFinder.FindSourceDefinitionAsync(TypeToGenerateIn, document.Project.Solution, cancellationToken).ConfigureAwait(false) as INamedTypeSymbol; if (TypeToGenerateIn.IsErrorType()) { return false; } if (!ValidateTypeToGenerateIn(TypeToGenerateIn, IsStatic, ClassInterfaceModuleStructTypes)) { return false; } if (!CodeGenerator.CanAdd(document.Project.Solution, TypeToGenerateIn, cancellationToken)) { return false; } // Ok. It either didn't bind to any symbols, or it bound to a symbol but with // errors. In the former case we definitely want to offer to generate a method. In // the latter case, we want to generate a method *unless* there's an existing method // with the same signature. var existingMethods = TypeToGenerateIn.GetMembers(IdentifierToken.ValueText) .OfType<IMethodSymbol>(); var destinationProvider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var syntaxFacts = destinationProvider.GetService<ISyntaxFactsService>(); var syntaxFactory = destinationProvider.GetService<SyntaxGenerator>(); IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); var generatedMethod = await SignatureInfo.GenerateMethodAsync(syntaxFactory, false, cancellationToken).ConfigureAwait(false); return !existingMethods.Any(m => SignatureComparer.Instance.HaveSameSignature(m, generatedMethod, caseSensitive: syntaxFacts.IsCaseSensitive, compareParameterName: true, isParameterCaseSensitive: syntaxFacts.IsCaseSensitive)); } } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/VisualBasicTest/ChangeSignature/AddParameterTests.Formatting.vb
' 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.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests Inherits AbstractChangeSignatureTests <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_KeepCountsPerLine() As Task Dim markup = <Text><![CDATA[ Class C Sub $$Method(a As Integer, b As Integer, c As Integer, d As Integer, e As Integer, f As Integer) Method(1, 2, 3, 4, 5, 6) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(5), New AddedParameterOrExistingIndex(4), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(3), New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub Method(f As Integer, e As Integer, newIntegerParameter As Integer, d As Integer, c As Integer, b As Integer, a As Integer) Method(6, 5, 12345, 4, 3, 2, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_SubMethods() As Task Dim markup = <Text><![CDATA[ Class C Sub $$Method(x As Integer, y As Integer) Method(1, 2) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub Method(y As Integer, newIntegerParameter As Integer, x As Integer) Method(2, 12345, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_FunctionMethods() As Task Dim markup = <Text><![CDATA[ Class C Sub $$Method(x As Integer, y As Integer) Method(1, 2) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub Method(y As Integer, newIntegerParameter As Integer, x As Integer) Method(2, 12345, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_Events() As Task Dim markup = <Text><![CDATA[ Class C Public Event $$MyEvent(a As Integer, b As Integer) End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Public Event MyEvent(b As Integer, newIntegerParameter As Integer, a As Integer) End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_CustomEvents() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub $$MyDelegate(a As Integer, b As Integer) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(a As Integer, b As Integer) End RaiseEvent End Event End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(b As Integer, newIntegerParameter As Integer, a As Integer) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(b As Integer, newIntegerParameter As Integer, a As Integer) End RaiseEvent End Event End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_Constructors() As Task Dim markup = <Text><![CDATA[ Class C Sub $$New(a As Integer, b As Integer) End Sub Sub M() Dim x = New C(1, 2) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub New(b As Integer, newIntegerParameter As Integer, a As Integer) End Sub Sub M() Dim x = New C(2, 12345, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_Properties() As Task Dim markup = <Text><![CDATA[ Class C Public Property $$NewProperty(x As Integer, y As Integer) As Integer Get Return 1 End Get Set(value As Integer) End Set End Property Sub M() Dim x = NewProperty(1, 2) NewProperty(1, 2) = x End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Public Property NewProperty(y As Integer, newIntegerParameter As Integer, x As Integer) As Integer Get Return 1 End Get Set(value As Integer) End Set End Property Sub M() Dim x = NewProperty(2, 12345, 1) NewProperty(2, 12345, 1) = x End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_Attribute() As Task Dim markup = <Text><![CDATA[ <Custom(1, 2)> Class CustomAttribute Inherits Attribute Sub $$New(x As Integer, y As Integer) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ <Custom(2, 12345, 1)> Class CustomAttribute Inherits Attribute Sub New(y As Integer, newIntegerParameter As Integer, x As Integer) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_DelegateFunction() As Task Dim markup = <Text><![CDATA[ Class C Delegate Function $$MyDelegate(x As Integer, y As Integer) End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Function MyDelegate(y As Integer, newIntegerParameter As Integer, x As Integer) End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_MultilineSubLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub $$MyDelegate(a As Integer, b As Integer) Sub M(del As MyDelegate) M(Sub(a As Integer, b As Integer) End Sub) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(b As Integer, newIntegerParameter As Integer, a As Integer) Sub M(del As MyDelegate) M(Sub(b As Integer, newIntegerParameter As Integer, a As Integer) End Sub) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_MultilineFunctionLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Function $$MyDelegate(a As Integer, b As Integer) As Integer Sub M(del As MyDelegate) M(Function(a As Integer, b As Integer) Return 1 End Function) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Function MyDelegate(b As Integer, newIntegerParameter As Integer, a As Integer) As Integer Sub M(del As MyDelegate) M(Function(b As Integer, newIntegerParameter As Integer, a As Integer) Return 1 End Function) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_SingleLineSubLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub $$MyDelegate(a As Integer, b As Integer) Sub M(del As MyDelegate) M(Sub(a As Integer, b As Integer) System.Console.WriteLine("Test")) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(b As Integer, newIntegerParameter As Integer, a As Integer) Sub M(del As MyDelegate) M(Sub(b As Integer, newIntegerParameter As Integer, a As Integer) System.Console.WriteLine("Test")) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_SingleLineFunctionLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Function $$MyDelegate(a As Integer, b As Integer) As Integer Sub M(del As MyDelegate) M(Function(a As Integer, b As Integer) 1) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Function MyDelegate(b As Integer, newIntegerParameter As Integer, a As Integer) As Integer Sub M(del As MyDelegate) M(Function(b As Integer, newIntegerParameter As Integer, a As Integer) 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function End Class End Namespace
' 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.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests Inherits AbstractChangeSignatureTests <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_KeepCountsPerLine() As Task Dim markup = <Text><![CDATA[ Class C Sub $$Method(a As Integer, b As Integer, c As Integer, d As Integer, e As Integer, f As Integer) Method(1, 2, 3, 4, 5, 6) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(5), New AddedParameterOrExistingIndex(4), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(3), New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub Method(f As Integer, e As Integer, newIntegerParameter As Integer, d As Integer, c As Integer, b As Integer, a As Integer) Method(6, 5, 12345, 4, 3, 2, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_SubMethods() As Task Dim markup = <Text><![CDATA[ Class C Sub $$Method(x As Integer, y As Integer) Method(1, 2) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub Method(y As Integer, newIntegerParameter As Integer, x As Integer) Method(2, 12345, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_FunctionMethods() As Task Dim markup = <Text><![CDATA[ Class C Sub $$Method(x As Integer, y As Integer) Method(1, 2) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub Method(y As Integer, newIntegerParameter As Integer, x As Integer) Method(2, 12345, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_Events() As Task Dim markup = <Text><![CDATA[ Class C Public Event $$MyEvent(a As Integer, b As Integer) End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Public Event MyEvent(b As Integer, newIntegerParameter As Integer, a As Integer) End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_CustomEvents() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub $$MyDelegate(a As Integer, b As Integer) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(a As Integer, b As Integer) End RaiseEvent End Event End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(b As Integer, newIntegerParameter As Integer, a As Integer) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(b As Integer, newIntegerParameter As Integer, a As Integer) End RaiseEvent End Event End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_Constructors() As Task Dim markup = <Text><![CDATA[ Class C Sub $$New(a As Integer, b As Integer) End Sub Sub M() Dim x = New C(1, 2) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub New(b As Integer, newIntegerParameter As Integer, a As Integer) End Sub Sub M() Dim x = New C(2, 12345, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_Properties() As Task Dim markup = <Text><![CDATA[ Class C Public Property $$NewProperty(x As Integer, y As Integer) As Integer Get Return 1 End Get Set(value As Integer) End Set End Property Sub M() Dim x = NewProperty(1, 2) NewProperty(1, 2) = x End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Public Property NewProperty(y As Integer, newIntegerParameter As Integer, x As Integer) As Integer Get Return 1 End Get Set(value As Integer) End Set End Property Sub M() Dim x = NewProperty(2, 12345, 1) NewProperty(2, 12345, 1) = x End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_Attribute() As Task Dim markup = <Text><![CDATA[ <Custom(1, 2)> Class CustomAttribute Inherits Attribute Sub $$New(x As Integer, y As Integer) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ <Custom(2, 12345, 1)> Class CustomAttribute Inherits Attribute Sub New(y As Integer, newIntegerParameter As Integer, x As Integer) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_DelegateFunction() As Task Dim markup = <Text><![CDATA[ Class C Delegate Function $$MyDelegate(x As Integer, y As Integer) End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Function MyDelegate(y As Integer, newIntegerParameter As Integer, x As Integer) End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_MultilineSubLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub $$MyDelegate(a As Integer, b As Integer) Sub M(del As MyDelegate) M(Sub(a As Integer, b As Integer) End Sub) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(b As Integer, newIntegerParameter As Integer, a As Integer) Sub M(del As MyDelegate) M(Sub(b As Integer, newIntegerParameter As Integer, a As Integer) End Sub) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_MultilineFunctionLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Function $$MyDelegate(a As Integer, b As Integer) As Integer Sub M(del As MyDelegate) M(Function(a As Integer, b As Integer) Return 1 End Function) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Function MyDelegate(b As Integer, newIntegerParameter As Integer, a As Integer) As Integer Sub M(del As MyDelegate) M(Function(b As Integer, newIntegerParameter As Integer, a As Integer) Return 1 End Function) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_SingleLineSubLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub $$MyDelegate(a As Integer, b As Integer) Sub M(del As MyDelegate) M(Sub(a As Integer, b As Integer) System.Console.WriteLine("Test")) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(b As Integer, newIntegerParameter As Integer, a As Integer) Sub M(del As MyDelegate) M(Sub(b As Integer, newIntegerParameter As Integer, a As Integer) System.Console.WriteLine("Test")) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Formatting_SingleLineFunctionLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Function $$MyDelegate(a As Integer, b As Integer) As Integer Sub M(del As MyDelegate) M(Function(a As Integer, b As Integer) 1) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(0)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Function MyDelegate(b As Integer, newIntegerParameter As Integer, a As Integer) As Integer Sub M(del As MyDelegate) M(Function(b As Integer, newIntegerParameter As Integer, a As Integer) 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function End Class End Namespace
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests_Razor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing { [Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public partial class AddUsingTests_Razor : AbstractAddUsingTests { [Theory, CombinatorialData] public async Task TestAddIntoHiddenRegionWithModernSpanMapper(TestHost host) { await TestAsync( @"#line hidden using System.Collections.Generic; #line default class Program { void Main() { [|DateTime|] d; } }", @"#line hidden using System; using System.Collections.Generic; #line default class Program { void Main() { DateTime d; } }", host); } private protected override IDocumentServiceProvider GetDocumentServiceProvider() { return new TestDocumentServiceProvider(supportsMappingImportDirectives: true); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing { [Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public partial class AddUsingTests_Razor : AbstractAddUsingTests { [Theory, CombinatorialData] public async Task TestAddIntoHiddenRegionWithModernSpanMapper(TestHost host) { await TestAsync( @"#line hidden using System.Collections.Generic; #line default class Program { void Main() { [|DateTime|] d; } }", @"#line hidden using System; using System.Collections.Generic; #line default class Program { void Main() { DateTime d; } }", host); } private protected override IDocumentServiceProvider GetDocumentServiceProvider() { return new TestDocumentServiceProvider(supportsMappingImportDirectives: true); } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/IteratorKeywordRecommender.vb
' 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 System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Iterator" keyword in member declaration contexts ''' </summary> Friend Class IteratorKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Iterator", VBFeaturesResources.Indicates_an_iterator_method_that_can_use_the_Yield_statement)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsTypeMemberDeclarationKeywordContext Then Dim modifiers = context.ModifierCollectionFacts If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.IteratorFunction Or PossibleDeclarationTypes.IteratorProperty) AndAlso modifiers.IteratorKeyword.Kind = SyntaxKind.None Then Return s_keywords End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
' 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 System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Iterator" keyword in member declaration contexts ''' </summary> Friend Class IteratorKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Iterator", VBFeaturesResources.Indicates_an_iterator_method_that_can_use_the_Yield_statement)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsTypeMemberDeclarationKeywordContext Then Dim modifiers = context.ModifierCollectionFacts If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.IteratorFunction Or PossibleDeclarationTypes.IteratorProperty) AndAlso modifiers.IteratorKeyword.Kind = SyntaxKind.None Then Return s_keywords End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/LanguageServer/ProtocolUnitTests/Highlights/DocumentHighlightTests.cs
// 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. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Highlights { public class DocumentHighlightTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGetDocumentHighlightAsync() { var markup = @"class B { } class A { B {|text:classB|}; void M() { var someVar = {|read:classB|}; {|caret:|}{|write:classB|} = new B(); } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expected = new LSP.DocumentHighlight[] { CreateDocumentHighlight(LSP.DocumentHighlightKind.Text, locations["text"].Single()), CreateDocumentHighlight(LSP.DocumentHighlightKind.Read, locations["read"].Single()), CreateDocumentHighlight(LSP.DocumentHighlightKind.Write, locations["write"].Single()) }; var results = await RunGetDocumentHighlightAsync(testLspServer, locations["caret"].Single()); AssertJsonEquals(expected, results); } [Fact] public async Task TestGetDocumentHighlightAsync_InvalidLocation() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGetDocumentHighlightAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } private static async Task<LSP.DocumentHighlight[]> RunGetDocumentHighlightAsync(TestLspServer testLspServer, LSP.Location caret) { var results = await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.DocumentHighlight[]>(LSP.Methods.TextDocumentDocumentHighlightName, CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), null, CancellationToken.None); Array.Sort(results, (h1, h2) => { var compareKind = h1.Kind.CompareTo(h2.Kind); var compareRange = CompareRange(h1.Range, h2.Range); return compareKind != 0 ? compareKind : compareRange; }); return results; } private static LSP.DocumentHighlight CreateDocumentHighlight(LSP.DocumentHighlightKind kind, LSP.Location location) => new LSP.DocumentHighlight() { Kind = kind, Range = location.Range }; } }
// 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. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Highlights { public class DocumentHighlightTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGetDocumentHighlightAsync() { var markup = @"class B { } class A { B {|text:classB|}; void M() { var someVar = {|read:classB|}; {|caret:|}{|write:classB|} = new B(); } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expected = new LSP.DocumentHighlight[] { CreateDocumentHighlight(LSP.DocumentHighlightKind.Text, locations["text"].Single()), CreateDocumentHighlight(LSP.DocumentHighlightKind.Read, locations["read"].Single()), CreateDocumentHighlight(LSP.DocumentHighlightKind.Write, locations["write"].Single()) }; var results = await RunGetDocumentHighlightAsync(testLspServer, locations["caret"].Single()); AssertJsonEquals(expected, results); } [Fact] public async Task TestGetDocumentHighlightAsync_InvalidLocation() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGetDocumentHighlightAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } private static async Task<LSP.DocumentHighlight[]> RunGetDocumentHighlightAsync(TestLspServer testLspServer, LSP.Location caret) { var results = await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.DocumentHighlight[]>(LSP.Methods.TextDocumentDocumentHighlightName, CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), null, CancellationToken.None); Array.Sort(results, (h1, h2) => { var compareKind = h1.Kind.CompareTo(h2.Kind); var compareRange = CompareRange(h1.Range, h2.Range); return compareKind != 0 ? compareKind : compareRange; }); return results; } private static LSP.DocumentHighlight CreateDocumentHighlight(LSP.DocumentHighlightKind kind, LSP.Location location) => new LSP.DocumentHighlight() { Kind = kind, Range = location.Range }; } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/IUnitTestingIncrementalAnalyzerProviderImplementation.cs
// 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. #nullable disable namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal interface IUnitTestingIncrementalAnalyzerProviderImplementation { IUnitTestingIncrementalAnalyzerImplementation CreateIncrementalAnalyzer(); } }
// 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. #nullable disable namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal interface IUnitTestingIncrementalAnalyzerProviderImplementation { IUnitTestingIncrementalAnalyzerImplementation CreateIncrementalAnalyzer(); } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Syntax/Parsing/RefReadonlyTests.cs
// 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. #nullable disable using Xunit; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public class RefReadonlyTests : ParsingTests { public RefReadonlyTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options); } [Fact] public void RefReadonlyReturn_CSharp7() { var text = @" unsafe class Program { delegate ref readonly int D1(); static ref readonly T M<T>() { return ref (new T[1])[0]; } public virtual ref readonly int* P1 => throw null; public ref readonly int[][] this[int i] => throw null; } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (4,18): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // delegate ref readonly int D1(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(4, 18), // (6,16): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // static ref readonly T M<T>() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(6, 16), // (11,24): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // public virtual ref readonly int* P1 => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(11, 24), // (13,16): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // public ref readonly int[][] this[int i] => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(13, 16) ); } [Fact] public void InArgs_CSharp7() { var text = @" class Program { static void M(in int x) { } int this[in int x] { get { return 1; } } static void Test1() { int x = 1; M(in x); _ = (new Program())[in x]; } } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (4,19): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // static void M(in int x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(4, 19), // (8,14): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // int this[in int x] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(8, 14), // (19,11): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // M(in x); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(19, 11), // (21,29): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // _ = (new Program())[in x]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(21, 29) ); } [Fact] public void RefReadonlyReturn_Unexpected() { var text = @" class Program { static void Main() { } ref readonly int Field; public static ref readonly Program operator +(Program x, Program y) { throw null; } // this parses fine static async ref readonly Task M<T>() { throw null; } public ref readonly virtual int* P1 => throw null; } "; ParseAndValidate(text, TestOptions.Regular9, // (9,27): error CS1003: Syntax error, '(' expected // ref readonly int Field; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments("(", ";").WithLocation(9, 27), // (9,27): error CS1026: ) expected // ref readonly int Field; Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(9, 27), // (11,41): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration // public static ref readonly Program operator +(Program x, Program y) Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(11, 41), // (11,41): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration // public static ref readonly Program operator +(Program x, Program y) Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(11, 41), // (12,5): error CS1519: Invalid token '{' ref readonly class, struct, or interface member declaration // { Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "{").WithArguments("{").WithLocation(12, 5), // (12,5): error CS1519: Invalid token '{' in class, record, struct, or interface member declaration // { Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "{").WithArguments("{").WithLocation(12, 5), // (17,5): error CS8803: Top-level statements must precede namespace and type declarations. // static async ref readonly Task M<T>() Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, @"static async ref readonly Task M<T>() { throw null; }").WithLocation(17, 5), // (22,25): error CS1031: Type expected // public ref readonly virtual int* P1 => throw null; Diagnostic(ErrorCode.ERR_TypeExpected, "virtual").WithLocation(22, 25), // (24,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(24, 1)); } [Fact] public void RefReadonlyReturn_UnexpectedBindTime() { var text = @" class Program { static void Main() { ref readonly int local = ref (new int[1])[0]; (ref readonly int, ref readonly int Alice)? t = null; System.Collections.Generic.List<ref readonly int> x = null; Use(local); Use(t); Use(x); } static void Use<T>(T dummy) { } } "; var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (9,10): error CS1073: Unexpected token 'ref' // (ref readonly int, ref readonly int Alice)? t = null; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 10), // (9,28): error CS1073: Unexpected token 'ref' // (ref readonly int, ref readonly int Alice)? t = null; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 28), // (11,41): error CS1073: Unexpected token 'ref' // System.Collections.Generic.List<ref readonly int> x = null; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(11, 41)); } [Fact] public void RefReadOnlyLocalsAreDisallowed() { CreateCompilation(@" class Test { void M() { int value = 0; ref int valid = ref value; ref readonly int invalid = ref readonly value; } }").GetParseDiagnostics().Verify( // (8,40): error CS1525: Invalid expression term 'readonly' // ref readonly int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 40), // (8,40): error CS1002: ; expected // ref readonly int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(8, 40), // (8,40): error CS0106: The modifier 'readonly' is not valid for this item // ref readonly int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 40), // (8,54): error CS1001: Identifier expected // ref readonly int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(8, 54)); } [Fact] public void LocalsWithRefReadOnlyExpressionsAreDisallowed() { CreateCompilation(@" class Test { void M() { int value = 0; ref int valid = ref value; ref int invalid = ref readonly value; } }").GetParseDiagnostics().Verify( // (8,31): error CS1525: Invalid expression term 'readonly' // ref int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 31), // (8,31): error CS1002: ; expected // ref int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(8, 31), // (8,31): error CS0106: The modifier 'readonly' is not valid for this item // ref int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 31), // (8,45): error CS1001: Identifier expected // ref int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(8, 45)); } [Fact] public void ReturnRefReadOnlyAreDisallowed() { CreateCompilation(@" class Test { int value = 0; ref readonly int Valid() => ref value; ref readonly int Invalid() => ref readonly value; }").GetParseDiagnostics().Verify( // (7,39): error CS1525: Invalid expression term 'readonly' // ref readonly int Invalid() => ref readonly value; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(7, 39), // (7,39): error CS1002: ; expected // ref readonly int Invalid() => ref readonly value; Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(7, 39), // (7,53): error CS1519: Invalid token ';' ref readonly class, struct, or interface member declaration // ref readonly int Invalid() => ref readonly value; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(7, 53), // (7,53): error CS1519: Invalid token ';' ref readonly class, struct, or interface member declaration // ref readonly int Invalid() => ref readonly value; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(7, 53)); } [Fact] public void RefReadOnlyForEachAreDisallowed() { CreateCompilation(@" class Test { void M() { var ar = new int[] { 1, 2, 3 }; foreach(ref readonly v in ar) { } } }").GetParseDiagnostics().Verify( // (8,17): error CS1525: Invalid expression term 'ref' // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref ").WithArguments("ref").WithLocation(8, 17), // (8,21): error CS1525: Invalid expression term 'readonly' // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 21), // (8,21): error CS1515: 'in' expected // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_InExpected, "readonly").WithLocation(8, 21), // (8,21): error CS0230: Type and identifier are both required in a foreach statement // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_BadForeachDecl, "readonly").WithLocation(8, 21), // (8,21): error CS1525: Invalid expression term 'readonly' // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 21), // (8,21): error CS1026: ) expected // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(8, 21), // (8,21): error CS0106: The modifier 'readonly' is not valid for this item // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 21), // (8,32): error CS1001: Identifier expected // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_IdentifierExpected, "in").WithLocation(8, 32), // (8,32): error CS1003: Syntax error, ',' expected // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_SyntaxError, "in").WithArguments(",", "in").WithLocation(8, 32), // (8,35): error CS1002: ; expected // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_SemicolonExpected, "ar").WithLocation(8, 35), // (8,37): error CS1002: ; expected // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(8, 37), // (8,37): error CS1513: } expected // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(8, 37)); } [Fact] public void RefReadOnlyAtCallSite() { CreateCompilation(@" class Test { void M(in int p) { } void N() { int x = 0; M(ref readonly x); } }").GetParseDiagnostics().Verify( // (10,15): error CS1525: Invalid expression term 'readonly' // M(in x); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(10, 15), // (10,15): error CS1026: ) expected // M(in x); Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(10, 15), // (10,15): error CS1002: ; expected // M(in x); Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(10, 15), // (10,15): error CS0106: The modifier 'readonly' is not valid for this item // M(in x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(10, 15), // (10,25): error CS1001: Identifier expected // M(in x); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(10, 25), // (10,25): error CS1002: ; expected // M(in x); Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(10, 25), // (10,25): error CS1513: } expected // M(in x); Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(10, 25)); } [Fact] public void InAtCallSite() { CreateCompilation(@" class Test { void M(in int p) { } void N() { int x = 0; M(in x); } }").GetParseDiagnostics().Verify(); } [Fact] public void NothingAtCallSite() { CreateCompilation(@" class Test { void M(in int p) { } void N() { int x = 0; M(x); } }").GetParseDiagnostics().Verify(); } [Fact] public void InverseReadOnlyRefShouldBeIllegal() { CreateCompilation(@" class Test { void M(readonly ref int p) { } }").GetParseDiagnostics().Verify( // (4,12): error CS1026: ) expected // void M(readonly ref int p) Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(4, 12), // (4,12): error CS1002: ; expected // void M(readonly ref int p) Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(4, 12), // (4,30): error CS1003: Syntax error, '(' expected // void M(readonly ref int p) Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("(", ")").WithLocation(4, 30)); } [Fact] public void RefReadOnlyReturnIllegalInOperators() { CreateCompilation(@" public class Test { public static ref readonly bool operator!(Test obj) => throw null; }").GetParseDiagnostics().Verify( // (4,37): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration // public static ref readonly bool operator!(Test obj) => throw null; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(4, 37), // (4,37): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration // public static ref readonly bool operator!(Test obj) => throw null; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(4, 37), // (4,55): error CS8124: Tuple must contain at least two elements. // public static ref readonly bool operator!(Test obj) => throw null; Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 55), // (4,57): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration // public static ref readonly bool operator!(Test obj) => throw null; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(4, 57)); } [Fact] public void InNotAllowedInReturnType() { CreateCompilation(@" class Test { in int M() => throw null; }").VerifyDiagnostics( // (4,5): error CS1519: Invalid token 'in' in class, record, struct, or interface member declaration // in int M() => throw null; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "in").WithArguments("in").WithLocation(4, 5)); } [Fact] public void RefReadOnlyNotAllowedInParameters() { CreateCompilation(@" class Test { void M(ref readonly int p) => throw null; }").VerifyDiagnostics( // (4,16): error CS1031: Type expected // void M(ref readonly int p) => throw null; Diagnostic(ErrorCode.ERR_TypeExpected, "readonly").WithLocation(4, 16), // (4,16): error CS1001: Identifier expected // void M(ref readonly int p) => throw null; Diagnostic(ErrorCode.ERR_IdentifierExpected, "readonly").WithLocation(4, 16), // (4,16): error CS1026: ) expected // void M(ref readonly int p) => throw null; Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(4, 16), // (4,16): error CS1002: ; expected // void M(ref readonly int p) => throw null; Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(4, 16), // (4,30): error CS1003: Syntax error, ',' expected // void M(ref readonly int p) => throw null; Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(",", ")").WithLocation(4, 30), // (4,10): error CS0501: 'Test.M(ref ?)' must declare a body because it is not marked abstract, extern, or partial // void M(ref readonly int p) => throw null; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("Test.M(ref ?)").WithLocation(4, 10), // (4,29): warning CS0169: The field 'Test.p' is never used // void M(ref readonly int p) => throw null; Diagnostic(ErrorCode.WRN_UnreferencedField, "p").WithArguments("Test.p").WithLocation(4, 29)); } [Fact, WorkItem(25264, "https://github.com/dotnet/roslyn/issues/25264")] public void TestNewRefArray() { UsingStatement("new ref[];", // (1,8): error CS1031: Type expected // new ref[]; Diagnostic(ErrorCode.ERR_TypeExpected, "[").WithLocation(1, 8)); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.ArrayType); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.ArgumentList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } } }
// 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. #nullable disable using Xunit; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public class RefReadonlyTests : ParsingTests { public RefReadonlyTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options); } [Fact] public void RefReadonlyReturn_CSharp7() { var text = @" unsafe class Program { delegate ref readonly int D1(); static ref readonly T M<T>() { return ref (new T[1])[0]; } public virtual ref readonly int* P1 => throw null; public ref readonly int[][] this[int i] => throw null; } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (4,18): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // delegate ref readonly int D1(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(4, 18), // (6,16): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // static ref readonly T M<T>() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(6, 16), // (11,24): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // public virtual ref readonly int* P1 => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(11, 24), // (13,16): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // public ref readonly int[][] this[int i] => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(13, 16) ); } [Fact] public void InArgs_CSharp7() { var text = @" class Program { static void M(in int x) { } int this[in int x] { get { return 1; } } static void Test1() { int x = 1; M(in x); _ = (new Program())[in x]; } } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (4,19): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // static void M(in int x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(4, 19), // (8,14): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // int this[in int x] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(8, 14), // (19,11): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // M(in x); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(19, 11), // (21,29): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater. // _ = (new Program())[in x]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(21, 29) ); } [Fact] public void RefReadonlyReturn_Unexpected() { var text = @" class Program { static void Main() { } ref readonly int Field; public static ref readonly Program operator +(Program x, Program y) { throw null; } // this parses fine static async ref readonly Task M<T>() { throw null; } public ref readonly virtual int* P1 => throw null; } "; ParseAndValidate(text, TestOptions.Regular9, // (9,27): error CS1003: Syntax error, '(' expected // ref readonly int Field; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments("(", ";").WithLocation(9, 27), // (9,27): error CS1026: ) expected // ref readonly int Field; Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(9, 27), // (11,41): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration // public static ref readonly Program operator +(Program x, Program y) Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(11, 41), // (11,41): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration // public static ref readonly Program operator +(Program x, Program y) Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(11, 41), // (12,5): error CS1519: Invalid token '{' ref readonly class, struct, or interface member declaration // { Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "{").WithArguments("{").WithLocation(12, 5), // (12,5): error CS1519: Invalid token '{' in class, record, struct, or interface member declaration // { Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "{").WithArguments("{").WithLocation(12, 5), // (17,5): error CS8803: Top-level statements must precede namespace and type declarations. // static async ref readonly Task M<T>() Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, @"static async ref readonly Task M<T>() { throw null; }").WithLocation(17, 5), // (22,25): error CS1031: Type expected // public ref readonly virtual int* P1 => throw null; Diagnostic(ErrorCode.ERR_TypeExpected, "virtual").WithLocation(22, 25), // (24,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(24, 1)); } [Fact] public void RefReadonlyReturn_UnexpectedBindTime() { var text = @" class Program { static void Main() { ref readonly int local = ref (new int[1])[0]; (ref readonly int, ref readonly int Alice)? t = null; System.Collections.Generic.List<ref readonly int> x = null; Use(local); Use(t); Use(x); } static void Use<T>(T dummy) { } } "; var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (9,10): error CS1073: Unexpected token 'ref' // (ref readonly int, ref readonly int Alice)? t = null; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 10), // (9,28): error CS1073: Unexpected token 'ref' // (ref readonly int, ref readonly int Alice)? t = null; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 28), // (11,41): error CS1073: Unexpected token 'ref' // System.Collections.Generic.List<ref readonly int> x = null; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(11, 41)); } [Fact] public void RefReadOnlyLocalsAreDisallowed() { CreateCompilation(@" class Test { void M() { int value = 0; ref int valid = ref value; ref readonly int invalid = ref readonly value; } }").GetParseDiagnostics().Verify( // (8,40): error CS1525: Invalid expression term 'readonly' // ref readonly int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 40), // (8,40): error CS1002: ; expected // ref readonly int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(8, 40), // (8,40): error CS0106: The modifier 'readonly' is not valid for this item // ref readonly int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 40), // (8,54): error CS1001: Identifier expected // ref readonly int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(8, 54)); } [Fact] public void LocalsWithRefReadOnlyExpressionsAreDisallowed() { CreateCompilation(@" class Test { void M() { int value = 0; ref int valid = ref value; ref int invalid = ref readonly value; } }").GetParseDiagnostics().Verify( // (8,31): error CS1525: Invalid expression term 'readonly' // ref int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 31), // (8,31): error CS1002: ; expected // ref int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(8, 31), // (8,31): error CS0106: The modifier 'readonly' is not valid for this item // ref int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 31), // (8,45): error CS1001: Identifier expected // ref int invalid = ref readonly value; Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(8, 45)); } [Fact] public void ReturnRefReadOnlyAreDisallowed() { CreateCompilation(@" class Test { int value = 0; ref readonly int Valid() => ref value; ref readonly int Invalid() => ref readonly value; }").GetParseDiagnostics().Verify( // (7,39): error CS1525: Invalid expression term 'readonly' // ref readonly int Invalid() => ref readonly value; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(7, 39), // (7,39): error CS1002: ; expected // ref readonly int Invalid() => ref readonly value; Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(7, 39), // (7,53): error CS1519: Invalid token ';' ref readonly class, struct, or interface member declaration // ref readonly int Invalid() => ref readonly value; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(7, 53), // (7,53): error CS1519: Invalid token ';' ref readonly class, struct, or interface member declaration // ref readonly int Invalid() => ref readonly value; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(7, 53)); } [Fact] public void RefReadOnlyForEachAreDisallowed() { CreateCompilation(@" class Test { void M() { var ar = new int[] { 1, 2, 3 }; foreach(ref readonly v in ar) { } } }").GetParseDiagnostics().Verify( // (8,17): error CS1525: Invalid expression term 'ref' // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref ").WithArguments("ref").WithLocation(8, 17), // (8,21): error CS1525: Invalid expression term 'readonly' // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 21), // (8,21): error CS1515: 'in' expected // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_InExpected, "readonly").WithLocation(8, 21), // (8,21): error CS0230: Type and identifier are both required in a foreach statement // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_BadForeachDecl, "readonly").WithLocation(8, 21), // (8,21): error CS1525: Invalid expression term 'readonly' // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 21), // (8,21): error CS1026: ) expected // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(8, 21), // (8,21): error CS0106: The modifier 'readonly' is not valid for this item // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 21), // (8,32): error CS1001: Identifier expected // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_IdentifierExpected, "in").WithLocation(8, 32), // (8,32): error CS1003: Syntax error, ',' expected // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_SyntaxError, "in").WithArguments(",", "in").WithLocation(8, 32), // (8,35): error CS1002: ; expected // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_SemicolonExpected, "ar").WithLocation(8, 35), // (8,37): error CS1002: ; expected // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(8, 37), // (8,37): error CS1513: } expected // foreach(ref readonly v in ar) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(8, 37)); } [Fact] public void RefReadOnlyAtCallSite() { CreateCompilation(@" class Test { void M(in int p) { } void N() { int x = 0; M(ref readonly x); } }").GetParseDiagnostics().Verify( // (10,15): error CS1525: Invalid expression term 'readonly' // M(in x); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(10, 15), // (10,15): error CS1026: ) expected // M(in x); Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(10, 15), // (10,15): error CS1002: ; expected // M(in x); Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(10, 15), // (10,15): error CS0106: The modifier 'readonly' is not valid for this item // M(in x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(10, 15), // (10,25): error CS1001: Identifier expected // M(in x); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(10, 25), // (10,25): error CS1002: ; expected // M(in x); Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(10, 25), // (10,25): error CS1513: } expected // M(in x); Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(10, 25)); } [Fact] public void InAtCallSite() { CreateCompilation(@" class Test { void M(in int p) { } void N() { int x = 0; M(in x); } }").GetParseDiagnostics().Verify(); } [Fact] public void NothingAtCallSite() { CreateCompilation(@" class Test { void M(in int p) { } void N() { int x = 0; M(x); } }").GetParseDiagnostics().Verify(); } [Fact] public void InverseReadOnlyRefShouldBeIllegal() { CreateCompilation(@" class Test { void M(readonly ref int p) { } }").GetParseDiagnostics().Verify( // (4,12): error CS1026: ) expected // void M(readonly ref int p) Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(4, 12), // (4,12): error CS1002: ; expected // void M(readonly ref int p) Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(4, 12), // (4,30): error CS1003: Syntax error, '(' expected // void M(readonly ref int p) Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("(", ")").WithLocation(4, 30)); } [Fact] public void RefReadOnlyReturnIllegalInOperators() { CreateCompilation(@" public class Test { public static ref readonly bool operator!(Test obj) => throw null; }").GetParseDiagnostics().Verify( // (4,37): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration // public static ref readonly bool operator!(Test obj) => throw null; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(4, 37), // (4,37): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration // public static ref readonly bool operator!(Test obj) => throw null; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(4, 37), // (4,55): error CS8124: Tuple must contain at least two elements. // public static ref readonly bool operator!(Test obj) => throw null; Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 55), // (4,57): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration // public static ref readonly bool operator!(Test obj) => throw null; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(4, 57)); } [Fact] public void InNotAllowedInReturnType() { CreateCompilation(@" class Test { in int M() => throw null; }").VerifyDiagnostics( // (4,5): error CS1519: Invalid token 'in' in class, record, struct, or interface member declaration // in int M() => throw null; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "in").WithArguments("in").WithLocation(4, 5)); } [Fact] public void RefReadOnlyNotAllowedInParameters() { CreateCompilation(@" class Test { void M(ref readonly int p) => throw null; }").VerifyDiagnostics( // (4,16): error CS1031: Type expected // void M(ref readonly int p) => throw null; Diagnostic(ErrorCode.ERR_TypeExpected, "readonly").WithLocation(4, 16), // (4,16): error CS1001: Identifier expected // void M(ref readonly int p) => throw null; Diagnostic(ErrorCode.ERR_IdentifierExpected, "readonly").WithLocation(4, 16), // (4,16): error CS1026: ) expected // void M(ref readonly int p) => throw null; Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(4, 16), // (4,16): error CS1002: ; expected // void M(ref readonly int p) => throw null; Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(4, 16), // (4,30): error CS1003: Syntax error, ',' expected // void M(ref readonly int p) => throw null; Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(",", ")").WithLocation(4, 30), // (4,10): error CS0501: 'Test.M(ref ?)' must declare a body because it is not marked abstract, extern, or partial // void M(ref readonly int p) => throw null; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("Test.M(ref ?)").WithLocation(4, 10), // (4,29): warning CS0169: The field 'Test.p' is never used // void M(ref readonly int p) => throw null; Diagnostic(ErrorCode.WRN_UnreferencedField, "p").WithArguments("Test.p").WithLocation(4, 29)); } [Fact, WorkItem(25264, "https://github.com/dotnet/roslyn/issues/25264")] public void TestNewRefArray() { UsingStatement("new ref[];", // (1,8): error CS1031: Type expected // new ref[]; Diagnostic(ErrorCode.ERR_TypeExpected, "[").WithLocation(1, 8)); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.ArrayType); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.ArgumentList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.NamespaceSymbolKey.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class NamespaceSymbolKey { // The containing symbol can be one of many things. // 1) Null when this is the global namespace for a compilation. // 2) The SymbolId for an assembly symbol if this is the global namespace for an // assembly. // 3) The SymbolId for a module symbol if this is the global namespace for a module. // 4) The SymbolId for the containing namespace symbol if this is not a global // namespace. public static void Create(INamespaceSymbol symbol, SymbolKeyWriter visitor) { visitor.WriteString(symbol.MetadataName); if (symbol.ContainingNamespace != null) { visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingNamespace); } else { // A global namespace can either belong to a module or to a compilation. Debug.Assert(symbol.IsGlobalNamespace); switch (symbol.NamespaceKind) { case NamespaceKind.Module: visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingModule); break; case NamespaceKind.Assembly: visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingAssembly); break; case NamespaceKind.Compilation: visitor.WriteBoolean(true); visitor.WriteSymbolKey(null); break; default: throw new NotImplementedException(); } } } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var metadataName = reader.ReadString()!; var isCompilationGlobalNamespace = reader.ReadBoolean(); var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason); if (containingSymbolFailureReason != null) { failureReason = $"({nameof(EventSymbolKey)} {nameof(containingSymbolResolution)} failed -> {containingSymbolFailureReason})"; return default; } if (isCompilationGlobalNamespace) { failureReason = null; return new SymbolKeyResolution(reader.Compilation.GlobalNamespace); } using var result = PooledArrayBuilder<INamespaceSymbol>.GetInstance(); foreach (var container in containingSymbolResolution) { switch (container) { case IAssemblySymbol assembly: Debug.Assert(metadataName == string.Empty); result.AddIfNotNull(assembly.GlobalNamespace); break; case IModuleSymbol module: Debug.Assert(metadataName == string.Empty); result.AddIfNotNull(module.GlobalNamespace); break; case INamespaceSymbol namespaceSymbol: foreach (var member in namespaceSymbol.GetMembers(metadataName)) { if (member is INamespaceSymbol childNamespace) { result.AddIfNotNull(childNamespace); } } break; } } return CreateResolution(result, $"({nameof(NamespaceSymbolKey)} '{metadataName}' not found)", out failureReason); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class NamespaceSymbolKey { // The containing symbol can be one of many things. // 1) Null when this is the global namespace for a compilation. // 2) The SymbolId for an assembly symbol if this is the global namespace for an // assembly. // 3) The SymbolId for a module symbol if this is the global namespace for a module. // 4) The SymbolId for the containing namespace symbol if this is not a global // namespace. public static void Create(INamespaceSymbol symbol, SymbolKeyWriter visitor) { visitor.WriteString(symbol.MetadataName); if (symbol.ContainingNamespace != null) { visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingNamespace); } else { // A global namespace can either belong to a module or to a compilation. Debug.Assert(symbol.IsGlobalNamespace); switch (symbol.NamespaceKind) { case NamespaceKind.Module: visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingModule); break; case NamespaceKind.Assembly: visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingAssembly); break; case NamespaceKind.Compilation: visitor.WriteBoolean(true); visitor.WriteSymbolKey(null); break; default: throw new NotImplementedException(); } } } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var metadataName = reader.ReadString()!; var isCompilationGlobalNamespace = reader.ReadBoolean(); var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason); if (containingSymbolFailureReason != null) { failureReason = $"({nameof(EventSymbolKey)} {nameof(containingSymbolResolution)} failed -> {containingSymbolFailureReason})"; return default; } if (isCompilationGlobalNamespace) { failureReason = null; return new SymbolKeyResolution(reader.Compilation.GlobalNamespace); } using var result = PooledArrayBuilder<INamespaceSymbol>.GetInstance(); foreach (var container in containingSymbolResolution) { switch (container) { case IAssemblySymbol assembly: Debug.Assert(metadataName == string.Empty); result.AddIfNotNull(assembly.GlobalNamespace); break; case IModuleSymbol module: Debug.Assert(metadataName == string.Empty); result.AddIfNotNull(module.GlobalNamespace); break; case INamespaceSymbol namespaceSymbol: foreach (var member in namespaceSymbol.GetMembers(metadataName)) { if (member is INamespaceSymbol childNamespace) { result.AddIfNotNull(childNamespace); } } break; } } return CreateResolution(result, $"({nameof(NamespaceSymbolKey)} '{metadataName}' not found)", out failureReason); } } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Impl/CodeModel/Collections/ParameterCollection.cs
// 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. #nullable disable using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class ParameterCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, AbstractCodeMember parent) { var collection = new ParameterCollection(state, parent); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private ParameterCollection( CodeModelState state, AbstractCodeMember parent) : base(state, parent) { } private AbstractCodeMember ParentElement { get { return (AbstractCodeMember)Parent; } } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var parameters = this.ParentElement.GetParameters(); if (index < parameters.Length) { var parameter = parameters[index]; element = (EnvDTE.CodeElement)CodeParameter.Create(this.State, this.ParentElement, CodeModelService.GetParameterName(parameter)); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var parentNode = this.ParentElement.LookupNode(); if (parentNode != null) { if (CodeModelService.TryGetParameterNode(parentNode, name, out _)) { // The name of the CodeElement should be just the identifier name associated with the element // devoid of the type characters hence we use the just identifier name for both creation and // later searches element = (EnvDTE.CodeElement)CodeParameter.Create(this.State, this.ParentElement, name); return true; } } element = null; return false; } public override int Count { get { return ParentElement.GetParameters().Length; } } } }
// 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. #nullable disable using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class ParameterCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, AbstractCodeMember parent) { var collection = new ParameterCollection(state, parent); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private ParameterCollection( CodeModelState state, AbstractCodeMember parent) : base(state, parent) { } private AbstractCodeMember ParentElement { get { return (AbstractCodeMember)Parent; } } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var parameters = this.ParentElement.GetParameters(); if (index < parameters.Length) { var parameter = parameters[index]; element = (EnvDTE.CodeElement)CodeParameter.Create(this.State, this.ParentElement, CodeModelService.GetParameterName(parameter)); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var parentNode = this.ParentElement.LookupNode(); if (parentNode != null) { if (CodeModelService.TryGetParameterNode(parentNode, name, out _)) { // The name of the CodeElement should be just the identifier name associated with the element // devoid of the type characters hence we use the just identifier name for both creation and // later searches element = (EnvDTE.CodeElement)CodeParameter.Create(this.State, this.ParentElement, name); return true; } } element = null; return false; } public override int Count { get { return ParentElement.GetParameters().Length; } } } }
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/GreenNodes/GreenNodeWriter.vb
' 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. '----------------------------------------------------------------------------------------------------------- ' This is the code that actually outputs the VB code that defines the tree. It is passed a read and validated ' ParseTree, and outputs the code to defined the node classes for that tree, and also additional data ' structures like the kinds, visitor, etc. '----------------------------------------------------------------------------------------------------------- Imports System.IO ' Class to write out the code for the code tree. Friend Class GreenNodeWriter Inherits WriteUtils Private _writer As TextWriter 'output is sent here. Private ReadOnly _nonterminalsWithOneChild As List(Of String) = New List(Of String) Private ReadOnly _nonterminalsWithTwoChildren As List(Of String) = New List(Of String) ' Initialize the class with the parse tree to write. Public Sub New(parseTree As ParseTree) MyBase.New(parseTree) End Sub ' Write out the code defining the tree to the give file. Public Sub WriteTreeAsCode(writer As TextWriter) _writer = writer GenerateFile() End Sub Private Sub GenerateFile() GenerateNamespace() End Sub Private Sub GenerateNamespace() _writer.WriteLine() If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("Namespace {0}", Ident(_parseTree.NamespaceName) + ".Syntax.InternalSyntax") _writer.WriteLine() End If GenerateNodeStructures() If Not String.IsNullOrEmpty(_parseTree.VisitorName) Then GenerateVisitorClass() End If If Not String.IsNullOrEmpty(_parseTree.RewriteVisitorName) Then GenerateRewriteVisitorClass() End If If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("End Namespace") End If 'DumpNames("Nodes with One Child", _nonterminalsWithOneChild) 'DumpNames("Nodes with Two Children", _nonterminalsWithTwoChildren) End Sub Private Sub DumpNames(title As String, names As List(Of String)) Console.WriteLine(title) Console.WriteLine("=======================================") Dim sortedNames = From n In names Order By n For Each name In sortedNames Console.WriteLine(name) Next Console.WriteLine() End Sub Private Sub GenerateNodeStructures() For Each nodeStructure In _parseTree.NodeStructures.Values If Not nodeStructure.NoFactory Then GenerateNodeStructureClass(nodeStructure) End If Next End Sub ' Generate a constant value Private Function GetConstantValue(val As Long) As String Return val.ToString() End Function ' Generate a class declaration for a node structure. Private Sub GenerateNodeStructureClass(nodeStructure As ParseNodeStructure) ' XML comment GenerateXmlComment(_writer, nodeStructure, 4, includeRemarks:=False) ' Class name _writer.Write(" ") If (nodeStructure.PartialClass) Then _writer.Write("Partial ") End If Dim visibility As String = "Friend" If _parseTree.IsAbstract(nodeStructure) Then _writer.WriteLine("{0} MustInherit Class {1}", visibility, StructureTypeName(nodeStructure)) ElseIf Not nodeStructure.HasDerivedStructure Then _writer.WriteLine("{0} NotInheritable Class {1}", visibility, StructureTypeName(nodeStructure)) Else _writer.WriteLine("{0} Class {1}", visibility, StructureTypeName(nodeStructure)) End If ' Base class If Not IsRoot(nodeStructure) Then _writer.WriteLine(" Inherits {0}", StructureTypeName(nodeStructure.ParentStructure)) End If _writer.WriteLine() 'Create members GenerateNodeStructureMembers(nodeStructure) ' Create the constructor. GenerateNodeStructureConstructor(nodeStructure, False, noExtra:=True) GenerateNodeStructureConstructor(nodeStructure, False, noExtra:=True, contextual:=True) GenerateNodeStructureConstructor(nodeStructure, False) ' Serialization GenerateNodeStructureSerialization(nodeStructure) GenerateCreateRed(nodeStructure) ' Create the property accessor for each of the fields Dim fields = nodeStructure.Fields For i = 0 To fields.Count - 1 GenerateNodeFieldProperty(fields(i), i, fields(i).ContainingStructure IsNot nodeStructure) Next ' Create the property accessor for each of the children Dim children = nodeStructure.Children For i = 0 To children.Count - 1 GenerateNodeChildProperty(nodeStructure, children(i), i) GenerateNodeWithChildProperty(children(i), i, nodeStructure) Next If Not (_parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken) Then If children.Count = 1 Then If Not children(0).IsList AndAlso Not KindTypeStructure(children(0).ChildKind).Name = "ExpressionSyntax" Then _nonterminalsWithOneChild.Add(nodeStructure.Name) End If ElseIf children.Count = 2 Then If Not children(0).IsList AndAlso Not KindTypeStructure(children(0).ChildKind).Name = "ExpressionSyntax" AndAlso Not children(1).IsList AndAlso Not KindTypeStructure(children(1).ChildKind).Name = "ExpressionSyntax" Then _nonterminalsWithTwoChildren.Add(nodeStructure.Name) End If End If End If 'Create GetChild GenerateGetChild(nodeStructure) GenerateWithTrivia(nodeStructure) GenerateSetDiagnostics(nodeStructure) GenerateSetAnnotations(nodeStructure) ' Visitor accept method If Not String.IsNullOrEmpty(_parseTree.VisitorName) Then GenerateAccept(nodeStructure) End If 'GenerateUpdate(nodeStructure) ' Special methods for the root node. If IsRoot(nodeStructure) Then GenerateRootNodeSpecialMethods(nodeStructure) End If ' End the class _writer.WriteLine(" End Class") _writer.WriteLine() End Sub ' Generate CreateRed method Private Sub GenerateCreateRed(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If _writer.WriteLine(" Friend Overrides Function CreateRed(ByVal parent As SyntaxNode, ByVal startLocation As Integer) As SyntaxNode") _writer.WriteLine(" Return new {0}.Syntax.{1}(Me, parent, startLocation)", _parseTree.NamespaceName, StructureTypeName(nodeStructure)) _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate SetDiagnostics method Private Sub GenerateSetDiagnostics(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) Then Return End If _writer.WriteLine(" Friend Overrides Function SetDiagnostics(ByVal newErrors As DiagnosticInfo()) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "newErrors", "GetAnnotations", "GetLeadingTrivia", "GetTrailingTrivia") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate SetAnnotations method Private Sub GenerateSetAnnotations(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) Then Return End If _writer.WriteLine(" Friend Overrides Function SetAnnotations(ByVal annotations As SyntaxAnnotation()) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "annotations", "GetLeadingTrivia", "GetTrailingTrivia") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate Update method . But only for non terminals Private Sub GenerateUpdate(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If Dim structureName = StructureTypeName(nodeStructure) Dim factory = FactoryName(nodeStructure) Dim needComma = False _writer.Write(" Friend ") If nodeStructure.ParentStructure IsNot Nothing AndAlso Not nodeStructure.ParentStructure.Abstract Then _writer.Write("Shadows ") End If _writer.Write("Function Update(") For Each child In GetAllChildrenOfStructure(nodeStructure) If needComma Then _writer.Write(", ") End If GenerateFactoryChildParameter(nodeStructure, child, Nothing, False) needComma = True Next _writer.WriteLine(") As {0}", structureName) needComma = False _writer.Write(" If ") For Each child In GetAllChildrenOfStructure(nodeStructure) If needComma Then _writer.Write(" OrElse ") End If If child.IsList OrElse KindTypeStructure(child.ChildKind).IsToken Then _writer.Write("{0}.Node IsNot Me.{1}", ChildParamName(child), ChildVarName(child)) Else _writer.Write("{0} IsNot Me.{1}", ChildParamName(child), ChildVarName(child)) End If needComma = True Next _writer.WriteLine(" Then") needComma = False _writer.Write(" Return SyntaxFactory.{0}(", factory) If nodeStructure.NodeKinds.Count >= 2 And Not _parseTree.NodeKinds.ContainsKey(FactoryName(nodeStructure)) Then _writer.Write("Me.Kind, ") End If For Each child In GetAllChildrenOfStructure(nodeStructure) If needComma Then _writer.Write(", ") End If _writer.Write("{0}", ChildParamName(child)) needComma = True Next _writer.WriteLine(")") _writer.WriteLine(" End If") _writer.WriteLine(" Return Me") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate WithTrivia method s Private Sub GenerateWithTrivia(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse Not nodeStructure.IsToken Then Return End If _writer.WriteLine(" Public Overrides Function WithLeadingTrivia(ByVal trivia As GreenNode) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "GetAnnotations", "trivia", "GetTrailingTrivia") _writer.WriteLine(" End Function") _writer.WriteLine() _writer.WriteLine(" Public Overrides Function WithTrailingTrivia(ByVal trivia As GreenNode) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "GetAnnotations", "GetLeadingTrivia", "trivia") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate GetChild, GetChildrenCount so members can be accessed by index Private Sub GenerateGetChild(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken Then Return End If Dim allChildren = GetAllChildrenOfStructure(nodeStructure) Dim childrenCount = allChildren.Count If childrenCount = 0 Then Return End If _writer.WriteLine(" Friend Overrides Function GetSlot(i as Integer) as GreenNode") ' Create the property accessor for each of the children Dim children = allChildren If childrenCount <> 1 Then _writer.WriteLine(" Select case i") For i = 0 To childrenCount - 1 _writer.WriteLine(" Case {0}", i) _writer.WriteLine(" Return Me.{0}", ChildVarName(children(i))) Next _writer.WriteLine(" Case Else") _writer.WriteLine(" Debug.Assert(false, ""child index out of range"")") _writer.WriteLine(" Return Nothing") _writer.WriteLine(" End Select") Else _writer.WriteLine(" If i = 0 Then") _writer.WriteLine(" Return Me.{0}", ChildVarName(children(0))) _writer.WriteLine(" Else") _writer.WriteLine(" Debug.Assert(false, ""child index out of range"")") _writer.WriteLine(" Return Nothing") _writer.WriteLine(" End If") End If _writer.WriteLine(" End Function") _writer.WriteLine() '_writer.WriteLine(" Friend Overrides ReadOnly Property SlotCount() As Integer") '_writer.WriteLine(" Get") '_writer.WriteLine(" Return {0}", childrenCount) '_writer.WriteLine(" End Get") '_writer.WriteLine(" End Property") _writer.WriteLine() End Sub ' Generate IsTerminal property. Private Sub GenerateIsTerminal(nodeStructure As ParseNodeStructure) _writer.WriteLine(" Friend Overrides ReadOnly Property IsTerminal As Boolean") _writer.WriteLine(" Get") _writer.WriteLine(" Return {0}", If(nodeStructure.IsTerminal, "True", "False")) _writer.WriteLine(" End Get") _writer.WriteLine(" End Property") _writer.WriteLine() End Sub Private Sub GenerateNodeStructureMembers(nodeStructure As ParseNodeStructure) Dim fields = nodeStructure.Fields For Each field In fields _writer.WriteLine(" Friend ReadOnly {0} as {1}", FieldVarName(field), FieldTypeRef(field)) Next Dim children = nodeStructure.Children For Each child In children _writer.WriteLine(" Friend ReadOnly {0} as {1}", ChildVarName(child), ChildFieldTypeRef(child, True)) Next _writer.WriteLine() End Sub Private Sub GenerateNodeStructureSerialization(nodeStructure As ParseNodeStructure) If nodeStructure.IsTokenRoot OrElse nodeStructure.IsTriviaRoot OrElse nodeStructure.IsPredefined OrElse nodeStructure.Name = "StructuredTriviaSyntax" Then Return End If _writer.WriteLine(" Friend Sub New(reader as ObjectReader)") _writer.WriteLine(" MyBase.New(reader)") If Not nodeStructure.Abstract Then Dim allChildren = GetAllChildrenOfStructure(nodeStructure) Dim childrenCount = allChildren.Count If childrenCount <> 0 Then _writer.WriteLine(" MyBase._slotCount = {0}", childrenCount) End If End If For Each child In nodeStructure.Children _writer.WriteLine(" Dim {0} = DirectCast(reader.ReadValue(), {1})", ChildVarName(child), ChildFieldTypeRef(child, isGreen:=True)) _writer.WriteLine(" If {0} isnot Nothing", ChildVarName(child)) _writer.WriteLine(" AdjustFlagsAndWidth({0})", ChildVarName(child)) _writer.WriteLine(" Me.{0} = {0}", ChildVarName(child)) _writer.WriteLine(" End If") Next For Each field In nodeStructure.Fields _writer.WriteLine(" Me.{0} = CType(reader.{1}(), {2})", FieldVarName(field), ReaderMethod(FieldTypeRef(field)), FieldTypeRef(field)) Next 'TODO: BLUE If StructureTypeName(nodeStructure) = "DirectiveTriviaSyntax" Then _writer.WriteLine(" SetFlags(NodeFlags.ContainsDirectives)") End If _writer.WriteLine(" End Sub") If Not nodeStructure.Abstract Then ' Friend Shared CreateInstance As Func(Of ObjectReader, Object) = Function(o) New BinaryExpressionSyntax(o) _writer.WriteLine(" Friend Shared CreateInstance As Func(Of ObjectReader, Object) = Function(o) New {0}(o)", StructureTypeName(nodeStructure)) _writer.WriteLine() End If If nodeStructure.Children.Count > 0 OrElse nodeStructure.Fields.Count > 0 Then _writer.WriteLine() _writer.WriteLine(" Friend Overrides Sub WriteTo(writer as ObjectWriter)") _writer.WriteLine(" MyBase.WriteTo(writer)") For Each child In nodeStructure.Children _writer.WriteLine(" writer.WriteValue(Me.{0})", ChildVarName(child)) Next For Each field In nodeStructure.Fields _writer.WriteLine(" writer.{0}(Me.{1})", WriterMethod(FieldTypeRef(field)), FieldVarName(field)) Next _writer.WriteLine(" End Sub") End If If Not _parseTree.IsAbstract(nodeStructure) Then _writer.WriteLine() _writer.WriteLine(" Shared Sub New()") _writer.WriteLine(" ObjectBinder.RegisterTypeReader(GetType({0}), Function(r) New {0}(r))", StructureTypeName(nodeStructure)) _writer.WriteLine(" End Sub") End If _writer.WriteLine() End Sub Private Function ReaderMethod(type As String) As String Select Case type Case "Integer", "SyntaxKind", "TypeCharacter" Return "ReadInt32" Case "Boolean" Return "ReadBoolean" Case Else Return "ReadValue" End Select End Function Private Function WriterMethod(type As String) As String Select Case type Case "Integer", "SyntaxKind", "TypeCharacter" Return "WriteInt32" Case "Boolean" Return "WriteBoolean" Case Else Return "WriteValue" End Select End Function ' Generate constructor for a node structure Private Sub GenerateNodeStructureConstructor(nodeStructure As ParseNodeStructure, isRaw As Boolean, Optional noExtra As Boolean = False, Optional contextual As Boolean = False) ' these constructors are hardcoded If nodeStructure.IsTokenRoot OrElse nodeStructure.IsTriviaRoot OrElse nodeStructure.Name = "StructuredTriviaSyntax" Then Return End If If nodeStructure.ParentStructure Is Nothing Then Return End If Dim allFields = GetAllFieldsOfStructure(nodeStructure) _writer.Write(" Friend Sub New(") ' Generate each of the field parameters _writer.Write("ByVal kind As {0}", NodeKindType()) If Not noExtra Then _writer.Write(", ByVal errors as DiagnosticInfo(), ByVal annotations as SyntaxAnnotation()", NodeKindType()) End If If nodeStructure.IsTerminal Then ' terminals have a text _writer.Write(", text as String") End If If nodeStructure.IsToken Then ' tokens have trivia _writer.Write(", leadingTrivia As GreenNode, trailingTrivia As GreenNode", StructureTypeName(_parseTree.RootStructure)) End If For Each field In allFields _writer.Write(", ") GenerateNodeStructureFieldParameter(field) Next For Each child In GetAllChildrenOfStructure(nodeStructure) _writer.Write(", ") GenerateNodeStructureChildParameter(child, Nothing, True) Next If contextual Then _writer.Write(", context As ISyntaxFactoryContext") End If _writer.WriteLine(")") ' Generate each of the field parameters _writer.Write(" MyBase.New(kind", NodeKindType()) If Not noExtra Then _writer.Write(", errors, annotations") End If If nodeStructure.IsToken AndAlso Not nodeStructure.IsTokenRoot Then ' nonterminals have text. _writer.Write(", text") If Not nodeStructure.IsTrivia Then ' tokens have trivia, but only if they are not trivia. _writer.Write(", leadingTrivia, trailingTrivia") End If End If Dim baseClass = nodeStructure.ParentStructure If baseClass IsNot Nothing Then For Each child In GetAllChildrenOfStructure(baseClass) _writer.Write(", {0}", ChildParamName(child)) Next End If _writer.WriteLine(")") If Not nodeStructure.Abstract Then Dim allChildren = GetAllChildrenOfStructure(nodeStructure) Dim childrenCount = allChildren.Count If childrenCount <> 0 Then _writer.WriteLine(" MyBase._slotCount = {0}", childrenCount) End If End If ' Generate code to initialize this class If contextual Then _writer.WriteLine(" Me.SetFactoryContext(context)") End If If allFields.Count > 0 Then For i = 0 To allFields.Count - 1 _writer.WriteLine(" Me.{0} = {1}", FieldVarName(allFields(i)), FieldParamName(allFields(i))) Next End If If nodeStructure.Children.Count > 0 Then '_writer.WriteLine(" Dim fullWidth as integer") _writer.WriteLine() For Each child In nodeStructure.Children Dim indent = "" If child.IsOptional OrElse child.IsList Then 'If endKeyword IsNot Nothing Then _writer.WriteLine(" If {0} IsNot Nothing Then", ChildParamName(child)) indent = " " End If '_writer.WriteLine("{0} fullWidth += {1}.FullWidth", indent, ChildParamName(child)) _writer.WriteLine("{0} AdjustFlagsAndWidth({1})", indent, ChildParamName(child)) _writer.WriteLine("{0} Me.{1} = {2}", indent, ChildVarName(child), ChildParamName(child)) If child.IsOptional OrElse child.IsList Then 'If endKeyword IsNot Nothing Then _writer.WriteLine(" End If", ChildParamName(child)) End If Next '_writer.WriteLine(" Me._fullWidth += fullWidth") _writer.WriteLine() End If 'TODO: BLUE If StructureTypeName(nodeStructure) = "DirectiveTriviaSyntax" Then _writer.WriteLine(" SetFlags(NodeFlags.ContainsDirectives)") End If ' Generate End Sub _writer.WriteLine(" End Sub") _writer.WriteLine() End Sub Private Sub GenerateNodeStructureConstructorParameters(nodeStructure As ParseNodeStructure, errorParam As String, annotationParam As String, precedingTriviaParam As String, followingTriviaParam As String) ' Generate each of the field parameters _writer.Write("(Me.Kind") _writer.Write(", {0}", errorParam) _writer.Write(", {0}", annotationParam) If nodeStructure.IsToken Then ' nonterminals have text. _writer.Write(", text") If Not nodeStructure.IsTrivia Then ' tokens have trivia, but only if they are not trivia. _writer.Write(", {0}, {1}", precedingTriviaParam, followingTriviaParam) End If ElseIf nodeStructure.IsTrivia AndAlso nodeStructure.IsTriviaRoot Then _writer.Write(", Me.Text") End If For Each field In GetAllFieldsOfStructure(nodeStructure) _writer.Write(", {0}", FieldVarName(field)) Next For Each child In GetAllChildrenOfStructure(nodeStructure) _writer.Write(", {0}", ChildVarName(child)) Next _writer.WriteLine(")") End Sub ' Generate a parameter corresponding to a node structure field Private Sub GenerateNodeStructureFieldParameter(field As ParseNodeField, Optional conflictName As String = Nothing) _writer.Write("{0} As {1}", FieldParamName(field, conflictName), FieldTypeRef(field)) End Sub ' Generate a parameter corresponding to a node structure child Private Sub GenerateNodeStructureChildParameter(child As ParseNodeChild, Optional conflictName As String = Nothing, Optional isGreen As Boolean = False) _writer.Write("{0} As {1}", ChildParamName(child, conflictName), ChildConstructorTypeRef(child, isGreen)) End Sub ' Generate a parameter corresponding to a node structure child Private Sub GenerateFactoryChildParameter(node As ParseNodeStructure, child As ParseNodeChild, Optional conflictName As String = Nothing, Optional internalForm As Boolean = False) _writer.Write("{0} As {1}", ChildParamName(child, conflictName), ChildFactoryTypeRef(node, child, True, internalForm)) End Sub ' Get modifiers Private Function GetModifiers(containingStructure As ParseNodeStructure, isOverride As Boolean, name As String) As String ' Is this overridable or an override? Dim modifiers = "" 'If isOverride Then ' modifiers = "Overrides " 'ElseIf containingStructure.HasDerivedStructure Then ' modifiers = "Overridable " 'End If ' Put Shadows modifier on if useful. ' Object has Equals and GetType ' root name has members for every kind and structure (factory methods) If (name = "Equals" OrElse name = "GetType") Then 'OrElse _parseTree.NodeKinds.ContainsKey(name) OrElse _parseTree.NodeStructures.ContainsKey(name)) Then modifiers = "Shadows " + modifiers End If Return modifiers End Function ' Generate a public property for a node field Private Sub GenerateNodeFieldProperty(field As ParseNodeField, fieldIndex As Integer, isOverride As Boolean) ' XML comment GenerateXmlComment(_writer, field, 8) _writer.WriteLine(" Friend {2}ReadOnly Property {0} As {1}", FieldPropertyName(field), FieldTypeRef(field), GetModifiers(field.ContainingStructure, isOverride, field.Name)) _writer.WriteLine(" Get") _writer.WriteLine(" Return Me.{0}", FieldVarName(field)) _writer.WriteLine(" End Get") _writer.WriteLine(" End Property") _writer.WriteLine("") End Sub ' Generate a public property for a child Private Sub GenerateNodeChildProperty(node As ParseNodeStructure, child As ParseNodeChild, childIndex As Integer) ' XML comment GenerateXmlComment(_writer, child, 8) Dim isToken = KindTypeStructure(child.ChildKind).IsToken _writer.WriteLine(" Friend {2}ReadOnly Property {0} As {1}", ChildPropertyName(child), ChildPropertyTypeRef(node, child, True), GetModifiers(child.ContainingStructure, False, child.Name)) _writer.WriteLine(" Get") If Not child.IsList Then _writer.WriteLine(" Return Me.{0}", ChildVarName(child)) ElseIf child.IsSeparated Then _writer.WriteLine(" Return new {0}(New Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList(of {1})(Me.{2}))", ChildPropertyTypeRef(node, child, True), BaseTypeReference(child), ChildVarName(child)) ElseIf KindTypeStructure(child.ChildKind).IsToken Then _writer.WriteLine(" Return New Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList(of GreenNode)(Me.{1})", BaseTypeReference(child), ChildVarName(child)) Else _writer.WriteLine(" Return new {0}(Me.{1})", ChildPropertyTypeRef(node, child, True), ChildVarName(child)) End If _writer.WriteLine(" End Get") _writer.WriteLine(" End Property") _writer.WriteLine("") End Sub ' Generate a public property for a child Private Sub GenerateNodeWithChildProperty(withChild As ParseNodeChild, childIndex As Integer, nodeStructure As ParseNodeStructure) Dim isOverride As Boolean = withChild.ContainingStructure IsNot nodeStructure If withChild.GenerateWith Then Dim isAbstract As Boolean = _parseTree.IsAbstract(nodeStructure) If Not isAbstract Then ' XML comment GenerateWithXmlComment(_writer, withChild, 8) _writer.WriteLine(" Friend {2}Function {0}({3} as {4}) As {1}", ChildWithFunctionName(withChild), StructureTypeName(withChild.ContainingStructure), GetModifiers(withChild.ContainingStructure, isOverride, withChild.Name), Ident(UpperFirstCharacter(withChild.Name)), ChildConstructorTypeRef(withChild)) _writer.WriteLine(" Ensures(Result(Of {0}) IsNot Nothing)", StructureTypeName(withChild.ContainingStructure)) _writer.Write(" return New {0}(", StructureTypeName(nodeStructure)) _writer.Write("Kind, Green.Errors") Dim allFields = GetAllFieldsOfStructure(nodeStructure) If allFields.Count > 0 Then For i = 0 To allFields.Count - 1 _writer.Write(", {0}", FieldParamName(allFields(i))) Next End If For Each child In nodeStructure.Children If child IsNot withChild Then _writer.Write(", {0}", ChildParamName(child)) Else _writer.Write(", {0}", Ident(UpperFirstCharacter(child.Name))) End If Next _writer.WriteLine(")") _writer.WriteLine(" End Function") ElseIf nodeStructure.Children.Contains(withChild) Then ' XML comment GenerateWithXmlComment(_writer, withChild, 8) _writer.WriteLine(" Friend {2} Function {0}({3} as {4}) As {1}", ChildWithFunctionName(withChild), StructureTypeName(withChild.ContainingStructure), "MustOverride", Ident(UpperFirstCharacter(withChild.Name)), ChildConstructorTypeRef(withChild)) End If _writer.WriteLine("") End If End Sub ' Generate public properties for a child that is a separated list Private Sub GenerateAccept(nodeStructure As ParseNodeStructure) If nodeStructure.ParentStructure IsNot Nothing AndAlso (_parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia) Then Return End If _writer.WriteLine(" Public {0} Function Accept(ByVal visitor As {1}) As VisualBasicSyntaxNode", If(IsRoot(nodeStructure), "Overridable", "Overrides"), _parseTree.VisitorName) _writer.WriteLine(" Return visitor.{0}(Me)", VisitorMethodName(nodeStructure)) _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate special methods and properties for the root node. These only appear in the root node. Private Sub GenerateRootNodeSpecialMethods(nodeStructure As ParseNodeStructure) _writer.WriteLine() End Sub ' Generate the Visitor class definition Private Sub GenerateVisitorClass() _writer.WriteLine(" Friend MustInherit Class {0}", Ident(_parseTree.VisitorName)) ' Basic Visit method that dispatches. _writer.WriteLine(" Public Overridable Function Visit(ByVal node As {0}) As VisualBasicSyntaxNode", StructureTypeName(_parseTree.RootStructure)) _writer.WriteLine(" If node IsNot Nothing") _writer.WriteLine(" Return node.Accept(Me)") _writer.WriteLine(" Else") _writer.WriteLine(" Return Nothing") _writer.WriteLine(" End If") _writer.WriteLine(" End Function") For Each nodeStructure In _parseTree.NodeStructures.Values GenerateVisitorMethod(nodeStructure) Next _writer.WriteLine(" End Class") _writer.WriteLine() End Sub ' Generate a method in the Visitor class Private Sub GenerateVisitorMethod(nodeStructure As ParseNodeStructure) If nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If Dim methodName = VisitorMethodName(nodeStructure) Dim structureName = StructureTypeName(nodeStructure) _writer.WriteLine(" Public Overridable Function {0}(ByVal node As {1}) As VisualBasicSyntaxNode", methodName, structureName) _writer.WriteLine(" Debug.Assert(node IsNot Nothing)") If Not IsRoot(nodeStructure) Then _writer.WriteLine(" Return {0}(node)", VisitorMethodName(nodeStructure.ParentStructure)) Else _writer.WriteLine(" Return node") End If _writer.WriteLine(" End Function") End Sub ' Generate the RewriteVisitor class definition Private Sub GenerateRewriteVisitorClass() _writer.WriteLine(" Friend MustInherit Class {0}", Ident(_parseTree.RewriteVisitorName)) _writer.WriteLine(" Inherits {0}", Ident(_parseTree.VisitorName), StructureTypeName(_parseTree.RootStructure)) _writer.WriteLine() For Each nodeStructure In _parseTree.NodeStructures.Values GenerateRewriteVisitorMethod(nodeStructure) Next _writer.WriteLine(" End Class") _writer.WriteLine() End Sub ' Generate a method in the RewriteVisitor class Private Sub GenerateRewriteVisitorMethod(nodeStructure As ParseNodeStructure) If nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If If nodeStructure.Abstract Then ' do nothing for abstract nodes Return End If Dim methodName = VisitorMethodName(nodeStructure) Dim structureName = StructureTypeName(nodeStructure) _writer.WriteLine(" Public Overrides Function {0}(ByVal node As {1}) As {2}", methodName, structureName, StructureTypeName(_parseTree.RootStructure)) ' non-abstract non-terminals need to rewrite their children and recreate as needed. Dim allFields = GetAllFieldsOfStructure(nodeStructure) Dim allChildren = GetAllChildrenOfStructure(nodeStructure) ' create anyChanges variable _writer.WriteLine(" Dim anyChanges As Boolean = False") _writer.WriteLine() ' visit all children For i = 0 To allChildren.Count - 1 If allChildren(i).IsList Then _writer.WriteLine(" Dim {0} = VisitList(node.{1})" + Environment.NewLine + " If node.{2} IsNot {0}.Node Then anyChanges = True", ChildNewVarName(allChildren(i)), ChildPropertyName(allChildren(i)), ChildVarName(allChildren(i))) ElseIf KindTypeStructure(allChildren(i).ChildKind).IsToken Then _writer.WriteLine(" Dim {0} = DirectCast(Visit(node.{2}), {1})" + Environment.NewLine + " If node.{3} IsNot {0} Then anyChanges = True", ChildNewVarName(allChildren(i)), BaseTypeReference(allChildren(i)), ChildPropertyName(allChildren(i)), ChildVarName(allChildren(i))) Else _writer.WriteLine(" Dim {0} = DirectCast(Visit(node.{2}), {1})" + Environment.NewLine + " If node.{2} IsNot {0} Then anyChanges = True", ChildNewVarName(allChildren(i)), ChildPropertyTypeRef(nodeStructure, allChildren(i)), ChildVarName(allChildren(i))) End If Next _writer.WriteLine() ' check if any changes. _writer.WriteLine(" If anyChanges Then") _writer.Write(" Return New {0}(node.Kind", StructureTypeName(nodeStructure)) _writer.Write(", node.GetDiagnostics, node.GetAnnotations") For Each field In allFields _writer.Write(", node.{0}", FieldPropertyName(field)) Next For Each child In allChildren If child.IsList Then _writer.Write(", {0}.Node", ChildNewVarName(child)) ElseIf KindTypeStructure(child.ChildKind).IsToken Then _writer.Write(", {0}", ChildNewVarName(child)) Else _writer.Write(", {0}", ChildNewVarName(child)) End If Next _writer.WriteLine(")") _writer.WriteLine(" Else") _writer.WriteLine(" Return node") _writer.WriteLine(" End If") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub End Class
' 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. '----------------------------------------------------------------------------------------------------------- ' This is the code that actually outputs the VB code that defines the tree. It is passed a read and validated ' ParseTree, and outputs the code to defined the node classes for that tree, and also additional data ' structures like the kinds, visitor, etc. '----------------------------------------------------------------------------------------------------------- Imports System.IO ' Class to write out the code for the code tree. Friend Class GreenNodeWriter Inherits WriteUtils Private _writer As TextWriter 'output is sent here. Private ReadOnly _nonterminalsWithOneChild As List(Of String) = New List(Of String) Private ReadOnly _nonterminalsWithTwoChildren As List(Of String) = New List(Of String) ' Initialize the class with the parse tree to write. Public Sub New(parseTree As ParseTree) MyBase.New(parseTree) End Sub ' Write out the code defining the tree to the give file. Public Sub WriteTreeAsCode(writer As TextWriter) _writer = writer GenerateFile() End Sub Private Sub GenerateFile() GenerateNamespace() End Sub Private Sub GenerateNamespace() _writer.WriteLine() If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("Namespace {0}", Ident(_parseTree.NamespaceName) + ".Syntax.InternalSyntax") _writer.WriteLine() End If GenerateNodeStructures() If Not String.IsNullOrEmpty(_parseTree.VisitorName) Then GenerateVisitorClass() End If If Not String.IsNullOrEmpty(_parseTree.RewriteVisitorName) Then GenerateRewriteVisitorClass() End If If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("End Namespace") End If 'DumpNames("Nodes with One Child", _nonterminalsWithOneChild) 'DumpNames("Nodes with Two Children", _nonterminalsWithTwoChildren) End Sub Private Sub DumpNames(title As String, names As List(Of String)) Console.WriteLine(title) Console.WriteLine("=======================================") Dim sortedNames = From n In names Order By n For Each name In sortedNames Console.WriteLine(name) Next Console.WriteLine() End Sub Private Sub GenerateNodeStructures() For Each nodeStructure In _parseTree.NodeStructures.Values If Not nodeStructure.NoFactory Then GenerateNodeStructureClass(nodeStructure) End If Next End Sub ' Generate a constant value Private Function GetConstantValue(val As Long) As String Return val.ToString() End Function ' Generate a class declaration for a node structure. Private Sub GenerateNodeStructureClass(nodeStructure As ParseNodeStructure) ' XML comment GenerateXmlComment(_writer, nodeStructure, 4, includeRemarks:=False) ' Class name _writer.Write(" ") If (nodeStructure.PartialClass) Then _writer.Write("Partial ") End If Dim visibility As String = "Friend" If _parseTree.IsAbstract(nodeStructure) Then _writer.WriteLine("{0} MustInherit Class {1}", visibility, StructureTypeName(nodeStructure)) ElseIf Not nodeStructure.HasDerivedStructure Then _writer.WriteLine("{0} NotInheritable Class {1}", visibility, StructureTypeName(nodeStructure)) Else _writer.WriteLine("{0} Class {1}", visibility, StructureTypeName(nodeStructure)) End If ' Base class If Not IsRoot(nodeStructure) Then _writer.WriteLine(" Inherits {0}", StructureTypeName(nodeStructure.ParentStructure)) End If _writer.WriteLine() 'Create members GenerateNodeStructureMembers(nodeStructure) ' Create the constructor. GenerateNodeStructureConstructor(nodeStructure, False, noExtra:=True) GenerateNodeStructureConstructor(nodeStructure, False, noExtra:=True, contextual:=True) GenerateNodeStructureConstructor(nodeStructure, False) ' Serialization GenerateNodeStructureSerialization(nodeStructure) GenerateCreateRed(nodeStructure) ' Create the property accessor for each of the fields Dim fields = nodeStructure.Fields For i = 0 To fields.Count - 1 GenerateNodeFieldProperty(fields(i), i, fields(i).ContainingStructure IsNot nodeStructure) Next ' Create the property accessor for each of the children Dim children = nodeStructure.Children For i = 0 To children.Count - 1 GenerateNodeChildProperty(nodeStructure, children(i), i) GenerateNodeWithChildProperty(children(i), i, nodeStructure) Next If Not (_parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken) Then If children.Count = 1 Then If Not children(0).IsList AndAlso Not KindTypeStructure(children(0).ChildKind).Name = "ExpressionSyntax" Then _nonterminalsWithOneChild.Add(nodeStructure.Name) End If ElseIf children.Count = 2 Then If Not children(0).IsList AndAlso Not KindTypeStructure(children(0).ChildKind).Name = "ExpressionSyntax" AndAlso Not children(1).IsList AndAlso Not KindTypeStructure(children(1).ChildKind).Name = "ExpressionSyntax" Then _nonterminalsWithTwoChildren.Add(nodeStructure.Name) End If End If End If 'Create GetChild GenerateGetChild(nodeStructure) GenerateWithTrivia(nodeStructure) GenerateSetDiagnostics(nodeStructure) GenerateSetAnnotations(nodeStructure) ' Visitor accept method If Not String.IsNullOrEmpty(_parseTree.VisitorName) Then GenerateAccept(nodeStructure) End If 'GenerateUpdate(nodeStructure) ' Special methods for the root node. If IsRoot(nodeStructure) Then GenerateRootNodeSpecialMethods(nodeStructure) End If ' End the class _writer.WriteLine(" End Class") _writer.WriteLine() End Sub ' Generate CreateRed method Private Sub GenerateCreateRed(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If _writer.WriteLine(" Friend Overrides Function CreateRed(ByVal parent As SyntaxNode, ByVal startLocation As Integer) As SyntaxNode") _writer.WriteLine(" Return new {0}.Syntax.{1}(Me, parent, startLocation)", _parseTree.NamespaceName, StructureTypeName(nodeStructure)) _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate SetDiagnostics method Private Sub GenerateSetDiagnostics(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) Then Return End If _writer.WriteLine(" Friend Overrides Function SetDiagnostics(ByVal newErrors As DiagnosticInfo()) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "newErrors", "GetAnnotations", "GetLeadingTrivia", "GetTrailingTrivia") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate SetAnnotations method Private Sub GenerateSetAnnotations(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) Then Return End If _writer.WriteLine(" Friend Overrides Function SetAnnotations(ByVal annotations As SyntaxAnnotation()) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "annotations", "GetLeadingTrivia", "GetTrailingTrivia") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate Update method . But only for non terminals Private Sub GenerateUpdate(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If Dim structureName = StructureTypeName(nodeStructure) Dim factory = FactoryName(nodeStructure) Dim needComma = False _writer.Write(" Friend ") If nodeStructure.ParentStructure IsNot Nothing AndAlso Not nodeStructure.ParentStructure.Abstract Then _writer.Write("Shadows ") End If _writer.Write("Function Update(") For Each child In GetAllChildrenOfStructure(nodeStructure) If needComma Then _writer.Write(", ") End If GenerateFactoryChildParameter(nodeStructure, child, Nothing, False) needComma = True Next _writer.WriteLine(") As {0}", structureName) needComma = False _writer.Write(" If ") For Each child In GetAllChildrenOfStructure(nodeStructure) If needComma Then _writer.Write(" OrElse ") End If If child.IsList OrElse KindTypeStructure(child.ChildKind).IsToken Then _writer.Write("{0}.Node IsNot Me.{1}", ChildParamName(child), ChildVarName(child)) Else _writer.Write("{0} IsNot Me.{1}", ChildParamName(child), ChildVarName(child)) End If needComma = True Next _writer.WriteLine(" Then") needComma = False _writer.Write(" Return SyntaxFactory.{0}(", factory) If nodeStructure.NodeKinds.Count >= 2 And Not _parseTree.NodeKinds.ContainsKey(FactoryName(nodeStructure)) Then _writer.Write("Me.Kind, ") End If For Each child In GetAllChildrenOfStructure(nodeStructure) If needComma Then _writer.Write(", ") End If _writer.Write("{0}", ChildParamName(child)) needComma = True Next _writer.WriteLine(")") _writer.WriteLine(" End If") _writer.WriteLine(" Return Me") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate WithTrivia method s Private Sub GenerateWithTrivia(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse Not nodeStructure.IsToken Then Return End If _writer.WriteLine(" Public Overrides Function WithLeadingTrivia(ByVal trivia As GreenNode) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "GetAnnotations", "trivia", "GetTrailingTrivia") _writer.WriteLine(" End Function") _writer.WriteLine() _writer.WriteLine(" Public Overrides Function WithTrailingTrivia(ByVal trivia As GreenNode) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "GetAnnotations", "GetLeadingTrivia", "trivia") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate GetChild, GetChildrenCount so members can be accessed by index Private Sub GenerateGetChild(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken Then Return End If Dim allChildren = GetAllChildrenOfStructure(nodeStructure) Dim childrenCount = allChildren.Count If childrenCount = 0 Then Return End If _writer.WriteLine(" Friend Overrides Function GetSlot(i as Integer) as GreenNode") ' Create the property accessor for each of the children Dim children = allChildren If childrenCount <> 1 Then _writer.WriteLine(" Select case i") For i = 0 To childrenCount - 1 _writer.WriteLine(" Case {0}", i) _writer.WriteLine(" Return Me.{0}", ChildVarName(children(i))) Next _writer.WriteLine(" Case Else") _writer.WriteLine(" Debug.Assert(false, ""child index out of range"")") _writer.WriteLine(" Return Nothing") _writer.WriteLine(" End Select") Else _writer.WriteLine(" If i = 0 Then") _writer.WriteLine(" Return Me.{0}", ChildVarName(children(0))) _writer.WriteLine(" Else") _writer.WriteLine(" Debug.Assert(false, ""child index out of range"")") _writer.WriteLine(" Return Nothing") _writer.WriteLine(" End If") End If _writer.WriteLine(" End Function") _writer.WriteLine() '_writer.WriteLine(" Friend Overrides ReadOnly Property SlotCount() As Integer") '_writer.WriteLine(" Get") '_writer.WriteLine(" Return {0}", childrenCount) '_writer.WriteLine(" End Get") '_writer.WriteLine(" End Property") _writer.WriteLine() End Sub ' Generate IsTerminal property. Private Sub GenerateIsTerminal(nodeStructure As ParseNodeStructure) _writer.WriteLine(" Friend Overrides ReadOnly Property IsTerminal As Boolean") _writer.WriteLine(" Get") _writer.WriteLine(" Return {0}", If(nodeStructure.IsTerminal, "True", "False")) _writer.WriteLine(" End Get") _writer.WriteLine(" End Property") _writer.WriteLine() End Sub Private Sub GenerateNodeStructureMembers(nodeStructure As ParseNodeStructure) Dim fields = nodeStructure.Fields For Each field In fields _writer.WriteLine(" Friend ReadOnly {0} as {1}", FieldVarName(field), FieldTypeRef(field)) Next Dim children = nodeStructure.Children For Each child In children _writer.WriteLine(" Friend ReadOnly {0} as {1}", ChildVarName(child), ChildFieldTypeRef(child, True)) Next _writer.WriteLine() End Sub Private Sub GenerateNodeStructureSerialization(nodeStructure As ParseNodeStructure) If nodeStructure.IsTokenRoot OrElse nodeStructure.IsTriviaRoot OrElse nodeStructure.IsPredefined OrElse nodeStructure.Name = "StructuredTriviaSyntax" Then Return End If _writer.WriteLine(" Friend Sub New(reader as ObjectReader)") _writer.WriteLine(" MyBase.New(reader)") If Not nodeStructure.Abstract Then Dim allChildren = GetAllChildrenOfStructure(nodeStructure) Dim childrenCount = allChildren.Count If childrenCount <> 0 Then _writer.WriteLine(" MyBase._slotCount = {0}", childrenCount) End If End If For Each child In nodeStructure.Children _writer.WriteLine(" Dim {0} = DirectCast(reader.ReadValue(), {1})", ChildVarName(child), ChildFieldTypeRef(child, isGreen:=True)) _writer.WriteLine(" If {0} isnot Nothing", ChildVarName(child)) _writer.WriteLine(" AdjustFlagsAndWidth({0})", ChildVarName(child)) _writer.WriteLine(" Me.{0} = {0}", ChildVarName(child)) _writer.WriteLine(" End If") Next For Each field In nodeStructure.Fields _writer.WriteLine(" Me.{0} = CType(reader.{1}(), {2})", FieldVarName(field), ReaderMethod(FieldTypeRef(field)), FieldTypeRef(field)) Next 'TODO: BLUE If StructureTypeName(nodeStructure) = "DirectiveTriviaSyntax" Then _writer.WriteLine(" SetFlags(NodeFlags.ContainsDirectives)") End If _writer.WriteLine(" End Sub") If Not nodeStructure.Abstract Then ' Friend Shared CreateInstance As Func(Of ObjectReader, Object) = Function(o) New BinaryExpressionSyntax(o) _writer.WriteLine(" Friend Shared CreateInstance As Func(Of ObjectReader, Object) = Function(o) New {0}(o)", StructureTypeName(nodeStructure)) _writer.WriteLine() End If If nodeStructure.Children.Count > 0 OrElse nodeStructure.Fields.Count > 0 Then _writer.WriteLine() _writer.WriteLine(" Friend Overrides Sub WriteTo(writer as ObjectWriter)") _writer.WriteLine(" MyBase.WriteTo(writer)") For Each child In nodeStructure.Children _writer.WriteLine(" writer.WriteValue(Me.{0})", ChildVarName(child)) Next For Each field In nodeStructure.Fields _writer.WriteLine(" writer.{0}(Me.{1})", WriterMethod(FieldTypeRef(field)), FieldVarName(field)) Next _writer.WriteLine(" End Sub") End If If Not _parseTree.IsAbstract(nodeStructure) Then _writer.WriteLine() _writer.WriteLine(" Shared Sub New()") _writer.WriteLine(" ObjectBinder.RegisterTypeReader(GetType({0}), Function(r) New {0}(r))", StructureTypeName(nodeStructure)) _writer.WriteLine(" End Sub") End If _writer.WriteLine() End Sub Private Function ReaderMethod(type As String) As String Select Case type Case "Integer", "SyntaxKind", "TypeCharacter" Return "ReadInt32" Case "Boolean" Return "ReadBoolean" Case Else Return "ReadValue" End Select End Function Private Function WriterMethod(type As String) As String Select Case type Case "Integer", "SyntaxKind", "TypeCharacter" Return "WriteInt32" Case "Boolean" Return "WriteBoolean" Case Else Return "WriteValue" End Select End Function ' Generate constructor for a node structure Private Sub GenerateNodeStructureConstructor(nodeStructure As ParseNodeStructure, isRaw As Boolean, Optional noExtra As Boolean = False, Optional contextual As Boolean = False) ' these constructors are hardcoded If nodeStructure.IsTokenRoot OrElse nodeStructure.IsTriviaRoot OrElse nodeStructure.Name = "StructuredTriviaSyntax" Then Return End If If nodeStructure.ParentStructure Is Nothing Then Return End If Dim allFields = GetAllFieldsOfStructure(nodeStructure) _writer.Write(" Friend Sub New(") ' Generate each of the field parameters _writer.Write("ByVal kind As {0}", NodeKindType()) If Not noExtra Then _writer.Write(", ByVal errors as DiagnosticInfo(), ByVal annotations as SyntaxAnnotation()", NodeKindType()) End If If nodeStructure.IsTerminal Then ' terminals have a text _writer.Write(", text as String") End If If nodeStructure.IsToken Then ' tokens have trivia _writer.Write(", leadingTrivia As GreenNode, trailingTrivia As GreenNode", StructureTypeName(_parseTree.RootStructure)) End If For Each field In allFields _writer.Write(", ") GenerateNodeStructureFieldParameter(field) Next For Each child In GetAllChildrenOfStructure(nodeStructure) _writer.Write(", ") GenerateNodeStructureChildParameter(child, Nothing, True) Next If contextual Then _writer.Write(", context As ISyntaxFactoryContext") End If _writer.WriteLine(")") ' Generate each of the field parameters _writer.Write(" MyBase.New(kind", NodeKindType()) If Not noExtra Then _writer.Write(", errors, annotations") End If If nodeStructure.IsToken AndAlso Not nodeStructure.IsTokenRoot Then ' nonterminals have text. _writer.Write(", text") If Not nodeStructure.IsTrivia Then ' tokens have trivia, but only if they are not trivia. _writer.Write(", leadingTrivia, trailingTrivia") End If End If Dim baseClass = nodeStructure.ParentStructure If baseClass IsNot Nothing Then For Each child In GetAllChildrenOfStructure(baseClass) _writer.Write(", {0}", ChildParamName(child)) Next End If _writer.WriteLine(")") If Not nodeStructure.Abstract Then Dim allChildren = GetAllChildrenOfStructure(nodeStructure) Dim childrenCount = allChildren.Count If childrenCount <> 0 Then _writer.WriteLine(" MyBase._slotCount = {0}", childrenCount) End If End If ' Generate code to initialize this class If contextual Then _writer.WriteLine(" Me.SetFactoryContext(context)") End If If allFields.Count > 0 Then For i = 0 To allFields.Count - 1 _writer.WriteLine(" Me.{0} = {1}", FieldVarName(allFields(i)), FieldParamName(allFields(i))) Next End If If nodeStructure.Children.Count > 0 Then '_writer.WriteLine(" Dim fullWidth as integer") _writer.WriteLine() For Each child In nodeStructure.Children Dim indent = "" If child.IsOptional OrElse child.IsList Then 'If endKeyword IsNot Nothing Then _writer.WriteLine(" If {0} IsNot Nothing Then", ChildParamName(child)) indent = " " End If '_writer.WriteLine("{0} fullWidth += {1}.FullWidth", indent, ChildParamName(child)) _writer.WriteLine("{0} AdjustFlagsAndWidth({1})", indent, ChildParamName(child)) _writer.WriteLine("{0} Me.{1} = {2}", indent, ChildVarName(child), ChildParamName(child)) If child.IsOptional OrElse child.IsList Then 'If endKeyword IsNot Nothing Then _writer.WriteLine(" End If", ChildParamName(child)) End If Next '_writer.WriteLine(" Me._fullWidth += fullWidth") _writer.WriteLine() End If 'TODO: BLUE If StructureTypeName(nodeStructure) = "DirectiveTriviaSyntax" Then _writer.WriteLine(" SetFlags(NodeFlags.ContainsDirectives)") End If ' Generate End Sub _writer.WriteLine(" End Sub") _writer.WriteLine() End Sub Private Sub GenerateNodeStructureConstructorParameters(nodeStructure As ParseNodeStructure, errorParam As String, annotationParam As String, precedingTriviaParam As String, followingTriviaParam As String) ' Generate each of the field parameters _writer.Write("(Me.Kind") _writer.Write(", {0}", errorParam) _writer.Write(", {0}", annotationParam) If nodeStructure.IsToken Then ' nonterminals have text. _writer.Write(", text") If Not nodeStructure.IsTrivia Then ' tokens have trivia, but only if they are not trivia. _writer.Write(", {0}, {1}", precedingTriviaParam, followingTriviaParam) End If ElseIf nodeStructure.IsTrivia AndAlso nodeStructure.IsTriviaRoot Then _writer.Write(", Me.Text") End If For Each field In GetAllFieldsOfStructure(nodeStructure) _writer.Write(", {0}", FieldVarName(field)) Next For Each child In GetAllChildrenOfStructure(nodeStructure) _writer.Write(", {0}", ChildVarName(child)) Next _writer.WriteLine(")") End Sub ' Generate a parameter corresponding to a node structure field Private Sub GenerateNodeStructureFieldParameter(field As ParseNodeField, Optional conflictName As String = Nothing) _writer.Write("{0} As {1}", FieldParamName(field, conflictName), FieldTypeRef(field)) End Sub ' Generate a parameter corresponding to a node structure child Private Sub GenerateNodeStructureChildParameter(child As ParseNodeChild, Optional conflictName As String = Nothing, Optional isGreen As Boolean = False) _writer.Write("{0} As {1}", ChildParamName(child, conflictName), ChildConstructorTypeRef(child, isGreen)) End Sub ' Generate a parameter corresponding to a node structure child Private Sub GenerateFactoryChildParameter(node As ParseNodeStructure, child As ParseNodeChild, Optional conflictName As String = Nothing, Optional internalForm As Boolean = False) _writer.Write("{0} As {1}", ChildParamName(child, conflictName), ChildFactoryTypeRef(node, child, True, internalForm)) End Sub ' Get modifiers Private Function GetModifiers(containingStructure As ParseNodeStructure, isOverride As Boolean, name As String) As String ' Is this overridable or an override? Dim modifiers = "" 'If isOverride Then ' modifiers = "Overrides " 'ElseIf containingStructure.HasDerivedStructure Then ' modifiers = "Overridable " 'End If ' Put Shadows modifier on if useful. ' Object has Equals and GetType ' root name has members for every kind and structure (factory methods) If (name = "Equals" OrElse name = "GetType") Then 'OrElse _parseTree.NodeKinds.ContainsKey(name) OrElse _parseTree.NodeStructures.ContainsKey(name)) Then modifiers = "Shadows " + modifiers End If Return modifiers End Function ' Generate a public property for a node field Private Sub GenerateNodeFieldProperty(field As ParseNodeField, fieldIndex As Integer, isOverride As Boolean) ' XML comment GenerateXmlComment(_writer, field, 8) _writer.WriteLine(" Friend {2}ReadOnly Property {0} As {1}", FieldPropertyName(field), FieldTypeRef(field), GetModifiers(field.ContainingStructure, isOverride, field.Name)) _writer.WriteLine(" Get") _writer.WriteLine(" Return Me.{0}", FieldVarName(field)) _writer.WriteLine(" End Get") _writer.WriteLine(" End Property") _writer.WriteLine("") End Sub ' Generate a public property for a child Private Sub GenerateNodeChildProperty(node As ParseNodeStructure, child As ParseNodeChild, childIndex As Integer) ' XML comment GenerateXmlComment(_writer, child, 8) Dim isToken = KindTypeStructure(child.ChildKind).IsToken _writer.WriteLine(" Friend {2}ReadOnly Property {0} As {1}", ChildPropertyName(child), ChildPropertyTypeRef(node, child, True), GetModifiers(child.ContainingStructure, False, child.Name)) _writer.WriteLine(" Get") If Not child.IsList Then _writer.WriteLine(" Return Me.{0}", ChildVarName(child)) ElseIf child.IsSeparated Then _writer.WriteLine(" Return new {0}(New Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList(of {1})(Me.{2}))", ChildPropertyTypeRef(node, child, True), BaseTypeReference(child), ChildVarName(child)) ElseIf KindTypeStructure(child.ChildKind).IsToken Then _writer.WriteLine(" Return New Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList(of GreenNode)(Me.{1})", BaseTypeReference(child), ChildVarName(child)) Else _writer.WriteLine(" Return new {0}(Me.{1})", ChildPropertyTypeRef(node, child, True), ChildVarName(child)) End If _writer.WriteLine(" End Get") _writer.WriteLine(" End Property") _writer.WriteLine("") End Sub ' Generate a public property for a child Private Sub GenerateNodeWithChildProperty(withChild As ParseNodeChild, childIndex As Integer, nodeStructure As ParseNodeStructure) Dim isOverride As Boolean = withChild.ContainingStructure IsNot nodeStructure If withChild.GenerateWith Then Dim isAbstract As Boolean = _parseTree.IsAbstract(nodeStructure) If Not isAbstract Then ' XML comment GenerateWithXmlComment(_writer, withChild, 8) _writer.WriteLine(" Friend {2}Function {0}({3} as {4}) As {1}", ChildWithFunctionName(withChild), StructureTypeName(withChild.ContainingStructure), GetModifiers(withChild.ContainingStructure, isOverride, withChild.Name), Ident(UpperFirstCharacter(withChild.Name)), ChildConstructorTypeRef(withChild)) _writer.WriteLine(" Ensures(Result(Of {0}) IsNot Nothing)", StructureTypeName(withChild.ContainingStructure)) _writer.Write(" return New {0}(", StructureTypeName(nodeStructure)) _writer.Write("Kind, Green.Errors") Dim allFields = GetAllFieldsOfStructure(nodeStructure) If allFields.Count > 0 Then For i = 0 To allFields.Count - 1 _writer.Write(", {0}", FieldParamName(allFields(i))) Next End If For Each child In nodeStructure.Children If child IsNot withChild Then _writer.Write(", {0}", ChildParamName(child)) Else _writer.Write(", {0}", Ident(UpperFirstCharacter(child.Name))) End If Next _writer.WriteLine(")") _writer.WriteLine(" End Function") ElseIf nodeStructure.Children.Contains(withChild) Then ' XML comment GenerateWithXmlComment(_writer, withChild, 8) _writer.WriteLine(" Friend {2} Function {0}({3} as {4}) As {1}", ChildWithFunctionName(withChild), StructureTypeName(withChild.ContainingStructure), "MustOverride", Ident(UpperFirstCharacter(withChild.Name)), ChildConstructorTypeRef(withChild)) End If _writer.WriteLine("") End If End Sub ' Generate public properties for a child that is a separated list Private Sub GenerateAccept(nodeStructure As ParseNodeStructure) If nodeStructure.ParentStructure IsNot Nothing AndAlso (_parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia) Then Return End If _writer.WriteLine(" Public {0} Function Accept(ByVal visitor As {1}) As VisualBasicSyntaxNode", If(IsRoot(nodeStructure), "Overridable", "Overrides"), _parseTree.VisitorName) _writer.WriteLine(" Return visitor.{0}(Me)", VisitorMethodName(nodeStructure)) _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate special methods and properties for the root node. These only appear in the root node. Private Sub GenerateRootNodeSpecialMethods(nodeStructure As ParseNodeStructure) _writer.WriteLine() End Sub ' Generate the Visitor class definition Private Sub GenerateVisitorClass() _writer.WriteLine(" Friend MustInherit Class {0}", Ident(_parseTree.VisitorName)) ' Basic Visit method that dispatches. _writer.WriteLine(" Public Overridable Function Visit(ByVal node As {0}) As VisualBasicSyntaxNode", StructureTypeName(_parseTree.RootStructure)) _writer.WriteLine(" If node IsNot Nothing") _writer.WriteLine(" Return node.Accept(Me)") _writer.WriteLine(" Else") _writer.WriteLine(" Return Nothing") _writer.WriteLine(" End If") _writer.WriteLine(" End Function") For Each nodeStructure In _parseTree.NodeStructures.Values GenerateVisitorMethod(nodeStructure) Next _writer.WriteLine(" End Class") _writer.WriteLine() End Sub ' Generate a method in the Visitor class Private Sub GenerateVisitorMethod(nodeStructure As ParseNodeStructure) If nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If Dim methodName = VisitorMethodName(nodeStructure) Dim structureName = StructureTypeName(nodeStructure) _writer.WriteLine(" Public Overridable Function {0}(ByVal node As {1}) As VisualBasicSyntaxNode", methodName, structureName) _writer.WriteLine(" Debug.Assert(node IsNot Nothing)") If Not IsRoot(nodeStructure) Then _writer.WriteLine(" Return {0}(node)", VisitorMethodName(nodeStructure.ParentStructure)) Else _writer.WriteLine(" Return node") End If _writer.WriteLine(" End Function") End Sub ' Generate the RewriteVisitor class definition Private Sub GenerateRewriteVisitorClass() _writer.WriteLine(" Friend MustInherit Class {0}", Ident(_parseTree.RewriteVisitorName)) _writer.WriteLine(" Inherits {0}", Ident(_parseTree.VisitorName), StructureTypeName(_parseTree.RootStructure)) _writer.WriteLine() For Each nodeStructure In _parseTree.NodeStructures.Values GenerateRewriteVisitorMethod(nodeStructure) Next _writer.WriteLine(" End Class") _writer.WriteLine() End Sub ' Generate a method in the RewriteVisitor class Private Sub GenerateRewriteVisitorMethod(nodeStructure As ParseNodeStructure) If nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If If nodeStructure.Abstract Then ' do nothing for abstract nodes Return End If Dim methodName = VisitorMethodName(nodeStructure) Dim structureName = StructureTypeName(nodeStructure) _writer.WriteLine(" Public Overrides Function {0}(ByVal node As {1}) As {2}", methodName, structureName, StructureTypeName(_parseTree.RootStructure)) ' non-abstract non-terminals need to rewrite their children and recreate as needed. Dim allFields = GetAllFieldsOfStructure(nodeStructure) Dim allChildren = GetAllChildrenOfStructure(nodeStructure) ' create anyChanges variable _writer.WriteLine(" Dim anyChanges As Boolean = False") _writer.WriteLine() ' visit all children For i = 0 To allChildren.Count - 1 If allChildren(i).IsList Then _writer.WriteLine(" Dim {0} = VisitList(node.{1})" + Environment.NewLine + " If node.{2} IsNot {0}.Node Then anyChanges = True", ChildNewVarName(allChildren(i)), ChildPropertyName(allChildren(i)), ChildVarName(allChildren(i))) ElseIf KindTypeStructure(allChildren(i).ChildKind).IsToken Then _writer.WriteLine(" Dim {0} = DirectCast(Visit(node.{2}), {1})" + Environment.NewLine + " If node.{3} IsNot {0} Then anyChanges = True", ChildNewVarName(allChildren(i)), BaseTypeReference(allChildren(i)), ChildPropertyName(allChildren(i)), ChildVarName(allChildren(i))) Else _writer.WriteLine(" Dim {0} = DirectCast(Visit(node.{2}), {1})" + Environment.NewLine + " If node.{2} IsNot {0} Then anyChanges = True", ChildNewVarName(allChildren(i)), ChildPropertyTypeRef(nodeStructure, allChildren(i)), ChildVarName(allChildren(i))) End If Next _writer.WriteLine() ' check if any changes. _writer.WriteLine(" If anyChanges Then") _writer.Write(" Return New {0}(node.Kind", StructureTypeName(nodeStructure)) _writer.Write(", node.GetDiagnostics, node.GetAnnotations") For Each field In allFields _writer.Write(", node.{0}", FieldPropertyName(field)) Next For Each child In allChildren If child.IsList Then _writer.Write(", {0}.Node", ChildNewVarName(child)) ElseIf KindTypeStructure(child.ChildKind).IsToken Then _writer.Write(", {0}", ChildNewVarName(child)) Else _writer.Write(", {0}", ChildNewVarName(child)) End If Next _writer.WriteLine(")") _writer.WriteLine(" Else") _writer.WriteLine(" Return node") _writer.WriteLine(" End If") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub End Class
-1
dotnet/roslyn
56,178
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-03T21:01:12Z"
"2021-09-03T22:10:51Z"
28d4d9d9869cf2b37e3e700e1057adf367fe9cd0
9e0b1adf36ff313a8e5374b401352b927ef3fb59
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Def/EditorConfigSettings/CodeStyle/ViewModel/CodeStyleSettingsViewModel.SettingsEntriesSnapshot.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.ViewModel { internal partial class CodeStyleSettingsViewModel { internal class SettingsEntriesSnapshot : SettingsEntriesSnapshotBase<CodeStyleSetting> { public SettingsEntriesSnapshot(ImmutableArray<CodeStyleSetting> data, int currentVersionNumber) : base(data, currentVersionNumber) { } protected override bool TryGetValue(CodeStyleSetting result, string keyName, out object? content) { content = keyName switch { ColumnDefinitions.CodeStyle.Description => result.Description, ColumnDefinitions.CodeStyle.Category => result.Category, ColumnDefinitions.CodeStyle.Severity => result, ColumnDefinitions.CodeStyle.Value => result, ColumnDefinitions.CodeStyle.Location => GetLocationString(result.Location), _ => null, }; return content is not null; } private string? GetLocationString(SettingLocation location) { return location.LocationKind switch { LocationKind.EditorConfig or LocationKind.GlobalConfig => location.Path, _ => ServicesVSResources.Visual_Studio_Settings }; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.ViewModel { internal partial class CodeStyleSettingsViewModel { internal class SettingsEntriesSnapshot : SettingsEntriesSnapshotBase<CodeStyleSetting> { public SettingsEntriesSnapshot(ImmutableArray<CodeStyleSetting> data, int currentVersionNumber) : base(data, currentVersionNumber) { } protected override bool TryGetValue(CodeStyleSetting result, string keyName, out object? content) { content = keyName switch { ColumnDefinitions.CodeStyle.Description => result.Description, ColumnDefinitions.CodeStyle.Category => result.Category, ColumnDefinitions.CodeStyle.Severity => result, ColumnDefinitions.CodeStyle.Value => result, ColumnDefinitions.CodeStyle.Location => GetLocationString(result.Location), _ => null, }; return content is not null; } private string? GetLocationString(SettingLocation location) { return location.LocationKind switch { LocationKind.EditorConfig or LocationKind.GlobalConfig => location.Path, _ => ServicesVSResources.Visual_Studio_Settings }; } } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./eng/Versions.props
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project> <!-- Roslyn version --> <PropertyGroup> <MajorVersion>4</MajorVersion> <MinorVersion>0</MinorVersion> <PatchVersion>0</PatchVersion> <PreReleaseVersionLabel>5</PreReleaseVersionLabel> <VersionPrefix>$(MajorVersion).$(MinorVersion).$(PatchVersion)</VersionPrefix> <!-- By default the assembly version in official builds is "$(MajorVersion).$(MinorVersion).0.0". Keep the setting conditional. The toolset sets the assembly version to 42.42.42.42 if not set explicitly. --> <AssemblyVersion Condition="'$(OfficialBuild)' == 'true' or '$(DotNetUseShippingVersions)' == 'true'">$(MajorVersion).$(MinorVersion).0.0</AssemblyVersion> <!-- Arcade overrides our VersionPrefix when MajorVersion and MinorVersion are specified. Clear them so that we can keep the PatchVersion until we are using an SDK that includes https://github.com/dotnet/arcade/pull/3601 --> <MajorVersion> </MajorVersion> <MinorVersion> </MinorVersion> <MicrosoftNetCompilersToolsetVersion>4.0.0-4.21420.19</MicrosoftNetCompilersToolsetVersion> </PropertyGroup> <PropertyGroup> <!-- Versions used by several individual references below --> <RoslynDiagnosticsNugetPackageVersion>3.3.3-beta1.21105.3</RoslynDiagnosticsNugetPackageVersion> <MicrosoftCodeAnalysisNetAnalyzersVersion>6.0.0-rc1.21366.2</MicrosoftCodeAnalysisNetAnalyzersVersion> <MicrosoftCodeAnalysisTestingVersion>1.1.0-beta1.21322.2</MicrosoftCodeAnalysisTestingVersion> <!-- CodeStyleAnalyzerVersion should we updated together with version of dotnet-format in dotnet-tools.json --> <CodeStyleAnalyzerVersion>4.0.0-3.final</CodeStyleAnalyzerVersion> <VisualStudioEditorPackagesVersion>16.10.230</VisualStudioEditorPackagesVersion> <VisualStudioEditorNewPackagesVersion>17.0.83-preview</VisualStudioEditorNewPackagesVersion> <ILAsmPackageVersion>5.0.0-alpha1.19409.1</ILAsmPackageVersion> <ILDAsmPackageVersion>5.0.0-preview.1.20112.8</ILDAsmPackageVersion> <MicrosoftVisualStudioLanguageServerProtocolPackagesVersion>17.0.3094-g82ddffa096</MicrosoftVisualStudioLanguageServerProtocolPackagesVersion> <MicrosoftVisualStudioShellPackagesVersion>17.0.0-previews-1-31421-229</MicrosoftVisualStudioShellPackagesVersion> <MicrosoftBuildPackagesVersion>16.5.0</MicrosoftBuildPackagesVersion> <!-- The version of Roslyn we build Source Generators against that are built in this repository. This must be lower than MicrosoftNetCompilersToolsetVersion, but not higher than our minimum dogfoodable Visual Studio version, or else the generators we build would load on the command line but not load in IDEs. --> <SourceGeneratorMicrosoftCodeAnalysisVersion>3.8.0</SourceGeneratorMicrosoftCodeAnalysisVersion> </PropertyGroup> <!-- Dependency versions --> <PropertyGroup> <BasicUndoVersion>0.9.3</BasicUndoVersion> <BasicReferenceAssembliesNetStandard20Version>1.2.1</BasicReferenceAssembliesNetStandard20Version> <BasicReferenceAssembliesNet50Version>1.2.1</BasicReferenceAssembliesNet50Version> <BenchmarkDotNetVersion>0.13.0</BenchmarkDotNetVersion> <BenchmarkDotNetDiagnosticsWindowsVersion>0.13.0</BenchmarkDotNetDiagnosticsWindowsVersion> <DiffPlexVersion>1.4.4</DiffPlexVersion> <FakeSignVersion>0.9.2</FakeSignVersion> <HumanizerCoreVersion>2.2.0</HumanizerCoreVersion> <ICSharpCodeDecompilerVersion>6.1.0.5902</ICSharpCodeDecompilerVersion> <MicrosoftBuildVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildVersion> <MicrosoftBuildFrameworkVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildFrameworkVersion> <MicrosoftBuildLocatorVersion>1.2.6</MicrosoftBuildLocatorVersion> <MicrosoftBuildRuntimeVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildRuntimeVersion> <MicrosoftBuildTasksCoreVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildTasksCoreVersion> <NuGetVisualStudioContractsVersion>6.0.0-preview.0.15</NuGetVisualStudioContractsVersion> <MicrosoftVisualStudioRpcContractsVersion>16.10.23</MicrosoftVisualStudioRpcContractsVersion> <!-- Since the Microsoft.CodeAnalysis.Analyzers package is a public dependency of our NuGet packages we will keep it untied to the RoslynDiagnosticsNugetPackageVersion we use for other analyzers to ensure it stays on a release version. --> <MicrosoftCodeAnalysisAnalyzersVersion>3.3.2</MicrosoftCodeAnalysisAnalyzersVersion> <MicrosoftCodeAnalysisBuildTasksVersion>2.0.0-rc2-61102-09</MicrosoftCodeAnalysisBuildTasksVersion> <MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisCSharpCodeStyleVersion> <MicrosoftCodeAnalysisElfieVersion>1.0.0-rc14</MicrosoftCodeAnalysisElfieVersion> <MicrosoftCodeAnalysisTestResourcesProprietaryVersion>2.0.41</MicrosoftCodeAnalysisTestResourcesProprietaryVersion> <MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisVisualBasicCodeStyleVersion> <MicrosoftCodeAnalysisAnalyzerUtilitiesVersion>3.3.0</MicrosoftCodeAnalysisAnalyzerUtilitiesVersion> <MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion> <MicrosoftCSharpVersion>4.3.0</MicrosoftCSharpVersion> <MicrosoftDevDivOptimizationDataPowerShellVersion>1.0.339</MicrosoftDevDivOptimizationDataPowerShellVersion> <MicrosoftDiagnosticsRuntimeVersion>0.8.31-beta</MicrosoftDiagnosticsRuntimeVersion> <MicrosoftDiagnosticsTracingTraceEventVersion>1.0.35</MicrosoftDiagnosticsTracingTraceEventVersion> <MicrosoftDiaSymReaderVersion>1.3.0</MicrosoftDiaSymReaderVersion> <MicrosoftDiaSymReaderConverterVersion>1.1.0-beta2-20115-01</MicrosoftDiaSymReaderConverterVersion> <MicrosoftDiaSymReaderConverterXmlVersion>1.1.0-beta2-20115-01</MicrosoftDiaSymReaderConverterXmlVersion> <MicrosoftDiaSymReaderNativeVersion>16.9.0-beta1.21055.5</MicrosoftDiaSymReaderNativeVersion> <MicrosoftDiaSymReaderPortablePdbVersion>1.5.0</MicrosoftDiaSymReaderPortablePdbVersion> <MicrosoftExtensionsLoggingVersion>5.0.0</MicrosoftExtensionsLoggingVersion> <MicrosoftExtensionsLoggingConsoleVersion>5.0.0</MicrosoftExtensionsLoggingConsoleVersion> <MicrosoftIdentityModelClientsActiveDirectoryVersion>3.13.8</MicrosoftIdentityModelClientsActiveDirectoryVersion> <MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion>15.8.27812-alpha</MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion> <MicrosoftInternalVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftInternalVisualStudioInteropVersion> <MicrosoftMetadataVisualizerVersion>1.0.0-beta3.21075.2</MicrosoftMetadataVisualizerVersion> <MicrosoftNETBuildExtensionsVersion>2.2.101</MicrosoftNETBuildExtensionsVersion> <MicrosoftNETCorePlatformsVersion>2.1.2</MicrosoftNETCorePlatformsVersion> <MicrosoftNETCoreAppRefVersion>5.0.0</MicrosoftNETCoreAppRefVersion> <MicrosoftNETFrameworkReferenceAssembliesnet461Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet461Version> <MicrosoftNETFrameworkReferenceAssembliesnet451Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet451Version> <MicrosoftNETFrameworkReferenceAssembliesnet40Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet40Version> <MicrosoftNETFrameworkReferenceAssembliesnet20Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet20Version> <jnm2ReferenceAssembliesnet35Version>1.0.1</jnm2ReferenceAssembliesnet35Version> <MicrosoftNETCoreTestHostVersion>1.1.0</MicrosoftNETCoreTestHostVersion> <MicrosoftNetFX20Version>1.0.3</MicrosoftNetFX20Version> <MicrosoftNETFrameworkReferenceAssembliesVersion>1.0.0</MicrosoftNETFrameworkReferenceAssembliesVersion> <MicrosoftNetSdkVersion>2.0.0-alpha-20170405-2</MicrosoftNetSdkVersion> <MicrosoftNuGetBuildTasksVersion>0.1.0</MicrosoftNuGetBuildTasksVersion> <MicrosoftPortableTargetsVersion>0.1.2-dev</MicrosoftPortableTargetsVersion> <MicrosoftServiceHubClientVersion>2.8.2019</MicrosoftServiceHubClientVersion> <MicrosoftServiceHubFrameworkVersion>2.8.2019</MicrosoftServiceHubFrameworkVersion> <MicrosoftVisualBasicVersion>10.1.0</MicrosoftVisualBasicVersion> <MicrosoftVisualStudioCacheVersion>17.0.13-alpha</MicrosoftVisualStudioCacheVersion> <MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion>15.8.27812-alpha</MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion> <MicrosoftVisualStudioCodeAnalysisSdkUIVersion>15.8.27812-alpha</MicrosoftVisualStudioCodeAnalysisSdkUIVersion> <MicrosoftVisualStudioComponentModelHostVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioComponentModelHostVersion> <MicrosoftVisualStudioCompositionVersion>16.9.20</MicrosoftVisualStudioCompositionVersion> <MicrosoftVisualStudioCoreUtilityVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioCoreUtilityVersion> <MicrosoftVisualStudioDebuggerUIInterfacesVersion>17.2.0-beta.21371.1</MicrosoftVisualStudioDebuggerUIInterfacesVersion> <MicrosoftVisualStudioDebuggerContractsVersion>17.2.0-beta.21371.1</MicrosoftVisualStudioDebuggerContractsVersion> <MicrosoftVisualStudioDebuggerEngineimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerEngineimplementationVersion> <MicrosoftVisualStudioDebuggerMetadataimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerMetadataimplementationVersion> <MicrosoftVisualStudioDesignerInterfacesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDesignerInterfacesVersion> <MicrosoftVisualStudioDiagnosticsMeasurementVersion>17.0.0-preview-1-30928-1112</MicrosoftVisualStudioDiagnosticsMeasurementVersion> <MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion> <MicrosoftVisualStudioSDKEmbedInteropTypesVersion>15.0.36</MicrosoftVisualStudioSDKEmbedInteropTypesVersion> <MicrosoftVisualStudioEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioEditorVersion> <MicrosoftVisualStudioGraphModelVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioGraphModelVersion> <MicrosoftVisualStudioImageCatalogVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImageCatalogVersion> <MicrosoftVisualStudioImagingVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingVersion> <MicrosoftVisualStudioImagingInterop140DesignTimeVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingInterop140DesignTimeVersion> <MicrosoftVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioInteropVersion> <MicrosoftVisualStudioLanguageVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageVersion> <MicrosoftVisualStudioLanguageCallHierarchyVersion>15.8.27812-alpha</MicrosoftVisualStudioLanguageCallHierarchyVersion> <MicrosoftVisualStudioLanguageIntellisenseVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageIntellisenseVersion> <MicrosoftVisualStudioLanguageNavigateToInterfacesVersion>17.0.25-g975cd8c52c</MicrosoftVisualStudioLanguageNavigateToInterfacesVersion> <MicrosoftVisualStudioLanguageServerProtocolVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolVersion> <MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion> <MicrosoftVisualStudioLanguageServerProtocolInternalVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolInternalVersion> <MicrosoftVisualStudioLanguageServerClientVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerClientVersion> <MicrosoftVisualStudioLanguageStandardClassificationVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageStandardClassificationVersion> <MicrosoftVisualStudioLiveShareVersion>2.18.6</MicrosoftVisualStudioLiveShareVersion> <MicrosoftVisualStudioLiveShareLanguageServicesVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesVersion> <MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion> <MicrosoftVisualStudioLiveShareWebEditorsVersion>3.0.8</MicrosoftVisualStudioLiveShareWebEditorsVersion> <MicrosoftVisualStudioPlatformVSEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioPlatformVSEditorVersion> <MicrosoftVisualStudioProgressionCodeSchemaVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCodeSchemaVersion> <MicrosoftVisualStudioProgressionCommonVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCommonVersion> <MicrosoftVisualStudioProgressionInterfacesVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionInterfacesVersion> <MicrosoftVisualStudioProjectSystemVersion>17.0.77-pre-g62a6cb5699</MicrosoftVisualStudioProjectSystemVersion> <MicrosoftVisualStudioProjectSystemManagedVersion>2.3.6152103</MicrosoftVisualStudioProjectSystemManagedVersion> <MicrosoftVisualStudioRemoteControlVersion>16.3.32</MicrosoftVisualStudioRemoteControlVersion> <MicrosoftVisualStudioSDKAnalyzersVersion>16.10.1</MicrosoftVisualStudioSDKAnalyzersVersion> <MicrosoftVisualStudioSetupConfigurationInteropVersion>1.16.30</MicrosoftVisualStudioSetupConfigurationInteropVersion> <MicrosoftVisualStudioShell150Version>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShell150Version> <MicrosoftVisualStudioShellFrameworkVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellFrameworkVersion> <MicrosoftVisualStudioShellDesignVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellDesignVersion> <MicrosoftVisualStudioTelemetryVersion>16.3.176</MicrosoftVisualStudioTelemetryVersion> <MicrosoftVisualStudioTemplateWizardInterfaceVersion>8.0.0.0-alpha</MicrosoftVisualStudioTemplateWizardInterfaceVersion> <MicrosoftVisualStudioTextDataVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextDataVersion> <MicrosoftVisualStudioTextInternalVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextInternalVersion> <MicrosoftVisualStudioTextLogicVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextLogicVersion> <MicrosoftVisualStudioTextUIVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIVersion> <MicrosoftVisualStudioTextUIWpfVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIWpfVersion> <MicrosoftVisualStudioTextUICocoaVersion>$(VisualStudioEditorPackagesVersion)</MicrosoftVisualStudioTextUICocoaVersion> <MicrosoftVisualStudioThreadingAnalyzersVersion>17.0.17-alpha</MicrosoftVisualStudioThreadingAnalyzersVersion> <MicrosoftVisualStudioThreadingVersion>17.0.17-alpha</MicrosoftVisualStudioThreadingVersion> <MicrosoftVisualStudioUtilitiesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioUtilitiesVersion> <MicrosoftVisualStudioValidationVersion>17.0.16-alpha</MicrosoftVisualStudioValidationVersion> <MicrosoftVisualStudioInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioInteractiveWindowVersion> <MicrosoftVisualStudioVsInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioVsInteractiveWindowVersion> <MicrosoftVisualStudioWorkspaceVSIntegrationVersion>16.3.43</MicrosoftVisualStudioWorkspaceVSIntegrationVersion> <MicrosoftWin32PrimitivesVersion>4.3.0</MicrosoftWin32PrimitivesVersion> <MicrosoftWin32RegistryVersion>5.0.0</MicrosoftWin32RegistryVersion> <MSBuildStructuredLoggerVersion>2.1.500</MSBuildStructuredLoggerVersion> <MDbgVersion>0.1.0</MDbgVersion> <MonoOptionsVersion>6.6.0.161</MonoOptionsVersion> <MoqVersion>4.10.1</MoqVersion> <NerdbankStreamsVersion>2.7.74</NerdbankStreamsVersion> <NuGetVisualStudioVersion>6.0.0-preview.0.15</NuGetVisualStudioVersion> <NuGetSolutionRestoreManagerInteropVersion>4.8.0</NuGetSolutionRestoreManagerInteropVersion> <MicrosoftDiaSymReaderPdb2PdbVersion>1.1.0-beta1-62506-02</MicrosoftDiaSymReaderPdb2PdbVersion> <RestSharpVersion>105.2.3</RestSharpVersion> <RichCodeNavEnvVarDumpVersion>0.1.1643-alpha</RichCodeNavEnvVarDumpVersion> <RoslynBuildUtilVersion>0.9.8-beta</RoslynBuildUtilVersion> <RoslynDependenciesOptimizationDataVersion>3.0.0-beta2-19053-01</RoslynDependenciesOptimizationDataVersion> <RoslynDiagnosticsAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</RoslynDiagnosticsAnalyzersVersion> <RoslynToolsVSIXExpInstallerVersion>1.1.0-beta3.21418.3</RoslynToolsVSIXExpInstallerVersion> <RoslynMicrosoftVisualStudioExtensionManagerVersion>0.0.4</RoslynMicrosoftVisualStudioExtensionManagerVersion> <SourceBrowserVersion>1.0.21</SourceBrowserVersion> <SystemBuffersVersion>4.5.1</SystemBuffersVersion> <SystemCompositionVersion>1.0.31</SystemCompositionVersion> <SystemCodeDomVersion>4.7.0</SystemCodeDomVersion> <SystemCommandLineVersion>2.0.0-beta1.20574.7</SystemCommandLineVersion> <SystemCommandLineExperimentalVersion>0.3.0-alpha.19577.1</SystemCommandLineExperimentalVersion> <SystemComponentModelCompositionVersion>4.5.0</SystemComponentModelCompositionVersion> <SystemDrawingCommonVersion>4.5.0</SystemDrawingCommonVersion> <SystemIOFileSystemVersion>4.3.0</SystemIOFileSystemVersion> <SystemIOFileSystemPrimitivesVersion>4.3.0</SystemIOFileSystemPrimitivesVersion> <SystemIOPipesAccessControlVersion>4.5.1</SystemIOPipesAccessControlVersion> <SystemIOPipelinesVersion>5.0.1</SystemIOPipelinesVersion> <SystemManagementVersion>5.0.0-preview.8.20407.11</SystemManagementVersion> <SystemMemoryVersion>4.5.4</SystemMemoryVersion> <SystemResourcesExtensionsVersion>4.7.1</SystemResourcesExtensionsVersion> <SystemRuntimeCompilerServicesUnsafeVersion>5.0.0</SystemRuntimeCompilerServicesUnsafeVersion> <SystemRuntimeLoaderVersion>4.3.0</SystemRuntimeLoaderVersion> <SystemSecurityPrincipalVersion>4.3.0</SystemSecurityPrincipalVersion> <SystemTextEncodingCodePagesVersion>4.5.1</SystemTextEncodingCodePagesVersion> <SystemTextEncodingExtensionsVersion>4.3.0</SystemTextEncodingExtensionsVersion> <!-- Note: When updating SystemTextJsonVersion ensure that the version is no higher than what is used by MSBuild. --> <SystemTextJsonVersion>4.7.0</SystemTextJsonVersion> <SystemThreadingTasksDataflowVersion>5.0.0</SystemThreadingTasksDataflowVersion> <!-- We need System.ValueTuple assembly version at least 4.0.3.0 on net47 to make F5 work against Dev15 - see https://github.com/dotnet/roslyn/issues/29705 --> <SystemValueTupleVersion>4.5.0</SystemValueTupleVersion> <SystemThreadingTasksExtensionsVersion>4.5.4</SystemThreadingTasksExtensionsVersion> <SQLitePCLRawbundle_greenVersion>2.0.4</SQLitePCLRawbundle_greenVersion> <UIAComWrapperVersion>1.1.0.14</UIAComWrapperVersion> <MicroBuildPluginsSwixBuildVersion>1.1.33</MicroBuildPluginsSwixBuildVersion> <MicrosoftVSSDKBuildToolsVersion>17.0.1056-Dev17PIAs-g9dffd635</MicrosoftVSSDKBuildToolsVersion> <MicrosoftVSSDKVSDConfigToolVersion>16.0.2032702</MicrosoftVSSDKVSDConfigToolVersion> <VsWebsiteInteropVersion>8.0.50727</VsWebsiteInteropVersion> <vswhereVersion>2.4.1</vswhereVersion> <XamarinMacVersion>1.0.0</XamarinMacVersion> <xunitVersion>2.4.1-pre.build.4059</xunitVersion> <xunitanalyzersVersion>0.10.0</xunitanalyzersVersion> <xunitassertVersion>$(xunitVersion)</xunitassertVersion> <XunitCombinatorialVersion>1.3.2</XunitCombinatorialVersion> <XUnitXmlTestLoggerVersion>2.1.26</XUnitXmlTestLoggerVersion> <xunitextensibilitycoreVersion>$(xunitVersion)</xunitextensibilitycoreVersion> <xunitrunnerconsoleVersion>2.4.1-pre.build.4059</xunitrunnerconsoleVersion> <xunitrunnerwpfVersion>1.0.51</xunitrunnerwpfVersion> <xunitrunnervisualstudioVersion>$(xunitVersion)</xunitrunnervisualstudioVersion> <xunitextensibilityexecutionVersion>$(xunitVersion)</xunitextensibilityexecutionVersion> <runtimeWinX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILAsmPackageVersion> <runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion> <runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion> <runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion> <runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion> <runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion> <!-- NOTE: The following dependencies have been identified as particularly problematic to update. If you bump their versions, you must push your changes to a dev branch in dotnet/roslyn and create a test insertion in Visual Studio to validate. --> <NewtonsoftJsonVersion>12.0.2</NewtonsoftJsonVersion> <StreamJsonRpcVersion>2.8.21</StreamJsonRpcVersion> <!-- When updating the S.C.I or S.R.M version please let the MSBuild team know in advance so they can update to the same version. Version changes require a VS test insertion for validation. --> <SystemCollectionsImmutableVersion>5.0.0</SystemCollectionsImmutableVersion> <SystemReflectionMetadataVersion>5.0.0</SystemReflectionMetadataVersion> <MicrosoftBclAsyncInterfacesVersion>5.0.0</MicrosoftBclAsyncInterfacesVersion> </PropertyGroup> <PropertyGroup> <UsingToolPdbConverter>true</UsingToolPdbConverter> <UsingToolSymbolUploader>true</UsingToolSymbolUploader> <UsingToolNuGetRepack>true</UsingToolNuGetRepack> <UsingToolVSSDK>true</UsingToolVSSDK> <UsingToolNetFrameworkReferenceAssemblies>true</UsingToolNetFrameworkReferenceAssemblies> <UsingToolIbcOptimization>true</UsingToolIbcOptimization> <UsingToolVisualStudioIbcTraining>true</UsingToolVisualStudioIbcTraining> <UsingToolXliff>true</UsingToolXliff> <UsingToolXUnit>true</UsingToolXUnit> <DiscoverEditorConfigFiles>true</DiscoverEditorConfigFiles> <!-- When using a bootstrap builder we don't want to use the Microsoft.Net.Compilers.Toolset package but rather explicitly override it. --> <UsingToolMicrosoftNetCompilers Condition="'$(BootstrapBuildPath)' == ''">true</UsingToolMicrosoftNetCompilers> <UseVSTestRunner>true</UseVSTestRunner> </PropertyGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project> <!-- Roslyn version --> <PropertyGroup> <MajorVersion>4</MajorVersion> <MinorVersion>0</MinorVersion> <PatchVersion>0</PatchVersion> <PreReleaseVersionLabel>5</PreReleaseVersionLabel> <VersionPrefix>$(MajorVersion).$(MinorVersion).$(PatchVersion)</VersionPrefix> <!-- By default the assembly version in official builds is "$(MajorVersion).$(MinorVersion).0.0". Keep the setting conditional. The toolset sets the assembly version to 42.42.42.42 if not set explicitly. --> <AssemblyVersion Condition="'$(OfficialBuild)' == 'true' or '$(DotNetUseShippingVersions)' == 'true'">$(MajorVersion).$(MinorVersion).0.0</AssemblyVersion> <!-- Arcade overrides our VersionPrefix when MajorVersion and MinorVersion are specified. Clear them so that we can keep the PatchVersion until we are using an SDK that includes https://github.com/dotnet/arcade/pull/3601 --> <MajorVersion> </MajorVersion> <MinorVersion> </MinorVersion> <MicrosoftNetCompilersToolsetVersion>4.0.0-4.21420.19</MicrosoftNetCompilersToolsetVersion> </PropertyGroup> <PropertyGroup> <!-- Versions used by several individual references below --> <RoslynDiagnosticsNugetPackageVersion>3.3.3-beta1.21105.3</RoslynDiagnosticsNugetPackageVersion> <MicrosoftCodeAnalysisNetAnalyzersVersion>6.0.0-rc1.21366.2</MicrosoftCodeAnalysisNetAnalyzersVersion> <MicrosoftCodeAnalysisTestingVersion>1.1.0-beta1.21322.2</MicrosoftCodeAnalysisTestingVersion> <!-- CodeStyleAnalyzerVersion should we updated together with version of dotnet-format in dotnet-tools.json --> <CodeStyleAnalyzerVersion>4.0.0-3.final</CodeStyleAnalyzerVersion> <VisualStudioEditorPackagesVersion>16.10.230</VisualStudioEditorPackagesVersion> <VisualStudioEditorNewPackagesVersion>17.0.83-preview</VisualStudioEditorNewPackagesVersion> <ILAsmPackageVersion>5.0.0-alpha1.19409.1</ILAsmPackageVersion> <ILDAsmPackageVersion>5.0.0-preview.1.20112.8</ILDAsmPackageVersion> <MicrosoftVisualStudioLanguageServerProtocolPackagesVersion>17.0.3094-g82ddffa096</MicrosoftVisualStudioLanguageServerProtocolPackagesVersion> <MicrosoftVisualStudioShellPackagesVersion>17.0.0-previews-1-31421-229</MicrosoftVisualStudioShellPackagesVersion> <MicrosoftBuildPackagesVersion>16.5.0</MicrosoftBuildPackagesVersion> <!-- The version of Roslyn we build Source Generators against that are built in this repository. This must be lower than MicrosoftNetCompilersToolsetVersion, but not higher than our minimum dogfoodable Visual Studio version, or else the generators we build would load on the command line but not load in IDEs. --> <SourceGeneratorMicrosoftCodeAnalysisVersion>3.8.0</SourceGeneratorMicrosoftCodeAnalysisVersion> </PropertyGroup> <!-- Dependency versions --> <PropertyGroup> <BasicUndoVersion>0.9.3</BasicUndoVersion> <BasicReferenceAssembliesNetStandard20Version>1.2.1</BasicReferenceAssembliesNetStandard20Version> <BasicReferenceAssembliesNet50Version>1.2.1</BasicReferenceAssembliesNet50Version> <BasicReferenceAssembliesNet60Version>1.2.2</BasicReferenceAssembliesNet60Version> <BenchmarkDotNetVersion>0.13.0</BenchmarkDotNetVersion> <BenchmarkDotNetDiagnosticsWindowsVersion>0.13.0</BenchmarkDotNetDiagnosticsWindowsVersion> <DiffPlexVersion>1.4.4</DiffPlexVersion> <FakeSignVersion>0.9.2</FakeSignVersion> <HumanizerCoreVersion>2.2.0</HumanizerCoreVersion> <ICSharpCodeDecompilerVersion>6.1.0.5902</ICSharpCodeDecompilerVersion> <MicrosoftBuildVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildVersion> <MicrosoftBuildFrameworkVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildFrameworkVersion> <MicrosoftBuildLocatorVersion>1.2.6</MicrosoftBuildLocatorVersion> <MicrosoftBuildRuntimeVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildRuntimeVersion> <MicrosoftBuildTasksCoreVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildTasksCoreVersion> <NuGetVisualStudioContractsVersion>6.0.0-preview.0.15</NuGetVisualStudioContractsVersion> <MicrosoftVisualStudioRpcContractsVersion>16.10.23</MicrosoftVisualStudioRpcContractsVersion> <!-- Since the Microsoft.CodeAnalysis.Analyzers package is a public dependency of our NuGet packages we will keep it untied to the RoslynDiagnosticsNugetPackageVersion we use for other analyzers to ensure it stays on a release version. --> <MicrosoftCodeAnalysisAnalyzersVersion>3.3.2</MicrosoftCodeAnalysisAnalyzersVersion> <MicrosoftCodeAnalysisBuildTasksVersion>2.0.0-rc2-61102-09</MicrosoftCodeAnalysisBuildTasksVersion> <MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisCSharpCodeStyleVersion> <MicrosoftCodeAnalysisElfieVersion>1.0.0-rc14</MicrosoftCodeAnalysisElfieVersion> <MicrosoftCodeAnalysisTestResourcesProprietaryVersion>2.0.41</MicrosoftCodeAnalysisTestResourcesProprietaryVersion> <MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisVisualBasicCodeStyleVersion> <MicrosoftCodeAnalysisAnalyzerUtilitiesVersion>3.3.0</MicrosoftCodeAnalysisAnalyzerUtilitiesVersion> <MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion> <MicrosoftCSharpVersion>4.3.0</MicrosoftCSharpVersion> <MicrosoftDevDivOptimizationDataPowerShellVersion>1.0.339</MicrosoftDevDivOptimizationDataPowerShellVersion> <MicrosoftDiagnosticsRuntimeVersion>0.8.31-beta</MicrosoftDiagnosticsRuntimeVersion> <MicrosoftDiagnosticsTracingTraceEventVersion>1.0.35</MicrosoftDiagnosticsTracingTraceEventVersion> <MicrosoftDiaSymReaderVersion>1.3.0</MicrosoftDiaSymReaderVersion> <MicrosoftDiaSymReaderConverterVersion>1.1.0-beta2-20115-01</MicrosoftDiaSymReaderConverterVersion> <MicrosoftDiaSymReaderConverterXmlVersion>1.1.0-beta2-20115-01</MicrosoftDiaSymReaderConverterXmlVersion> <MicrosoftDiaSymReaderNativeVersion>16.9.0-beta1.21055.5</MicrosoftDiaSymReaderNativeVersion> <MicrosoftDiaSymReaderPortablePdbVersion>1.5.0</MicrosoftDiaSymReaderPortablePdbVersion> <MicrosoftExtensionsLoggingVersion>5.0.0</MicrosoftExtensionsLoggingVersion> <MicrosoftExtensionsLoggingConsoleVersion>5.0.0</MicrosoftExtensionsLoggingConsoleVersion> <MicrosoftIdentityModelClientsActiveDirectoryVersion>3.13.8</MicrosoftIdentityModelClientsActiveDirectoryVersion> <MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion>15.8.27812-alpha</MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion> <MicrosoftInternalVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftInternalVisualStudioInteropVersion> <MicrosoftMetadataVisualizerVersion>1.0.0-beta3.21075.2</MicrosoftMetadataVisualizerVersion> <MicrosoftNETBuildExtensionsVersion>2.2.101</MicrosoftNETBuildExtensionsVersion> <MicrosoftNETCorePlatformsVersion>2.1.2</MicrosoftNETCorePlatformsVersion> <MicrosoftNETCoreAppRefVersion>5.0.0</MicrosoftNETCoreAppRefVersion> <MicrosoftNETFrameworkReferenceAssembliesnet461Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet461Version> <MicrosoftNETFrameworkReferenceAssembliesnet451Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet451Version> <MicrosoftNETFrameworkReferenceAssembliesnet40Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet40Version> <MicrosoftNETFrameworkReferenceAssembliesnet20Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet20Version> <jnm2ReferenceAssembliesnet35Version>1.0.1</jnm2ReferenceAssembliesnet35Version> <MicrosoftNETCoreTestHostVersion>1.1.0</MicrosoftNETCoreTestHostVersion> <MicrosoftNetFX20Version>1.0.3</MicrosoftNetFX20Version> <MicrosoftNETFrameworkReferenceAssembliesVersion>1.0.0</MicrosoftNETFrameworkReferenceAssembliesVersion> <MicrosoftNetSdkVersion>2.0.0-alpha-20170405-2</MicrosoftNetSdkVersion> <MicrosoftNuGetBuildTasksVersion>0.1.0</MicrosoftNuGetBuildTasksVersion> <MicrosoftPortableTargetsVersion>0.1.2-dev</MicrosoftPortableTargetsVersion> <MicrosoftServiceHubClientVersion>2.8.2019</MicrosoftServiceHubClientVersion> <MicrosoftServiceHubFrameworkVersion>2.8.2019</MicrosoftServiceHubFrameworkVersion> <MicrosoftVisualBasicVersion>10.1.0</MicrosoftVisualBasicVersion> <MicrosoftVisualStudioCacheVersion>17.0.13-alpha</MicrosoftVisualStudioCacheVersion> <MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion>15.8.27812-alpha</MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion> <MicrosoftVisualStudioCodeAnalysisSdkUIVersion>15.8.27812-alpha</MicrosoftVisualStudioCodeAnalysisSdkUIVersion> <MicrosoftVisualStudioComponentModelHostVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioComponentModelHostVersion> <MicrosoftVisualStudioCompositionVersion>16.9.20</MicrosoftVisualStudioCompositionVersion> <MicrosoftVisualStudioCoreUtilityVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioCoreUtilityVersion> <MicrosoftVisualStudioDebuggerUIInterfacesVersion>17.2.0-beta.21371.1</MicrosoftVisualStudioDebuggerUIInterfacesVersion> <MicrosoftVisualStudioDebuggerContractsVersion>17.2.0-beta.21371.1</MicrosoftVisualStudioDebuggerContractsVersion> <MicrosoftVisualStudioDebuggerEngineimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerEngineimplementationVersion> <MicrosoftVisualStudioDebuggerMetadataimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerMetadataimplementationVersion> <MicrosoftVisualStudioDesignerInterfacesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDesignerInterfacesVersion> <MicrosoftVisualStudioDiagnosticsMeasurementVersion>17.0.0-preview-1-30928-1112</MicrosoftVisualStudioDiagnosticsMeasurementVersion> <MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion> <MicrosoftVisualStudioSDKEmbedInteropTypesVersion>15.0.36</MicrosoftVisualStudioSDKEmbedInteropTypesVersion> <MicrosoftVisualStudioEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioEditorVersion> <MicrosoftVisualStudioGraphModelVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioGraphModelVersion> <MicrosoftVisualStudioImageCatalogVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImageCatalogVersion> <MicrosoftVisualStudioImagingVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingVersion> <MicrosoftVisualStudioImagingInterop140DesignTimeVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingInterop140DesignTimeVersion> <MicrosoftVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioInteropVersion> <MicrosoftVisualStudioLanguageVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageVersion> <MicrosoftVisualStudioLanguageCallHierarchyVersion>15.8.27812-alpha</MicrosoftVisualStudioLanguageCallHierarchyVersion> <MicrosoftVisualStudioLanguageIntellisenseVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageIntellisenseVersion> <MicrosoftVisualStudioLanguageNavigateToInterfacesVersion>17.0.25-g975cd8c52c</MicrosoftVisualStudioLanguageNavigateToInterfacesVersion> <MicrosoftVisualStudioLanguageServerProtocolVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolVersion> <MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion> <MicrosoftVisualStudioLanguageServerProtocolInternalVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolInternalVersion> <MicrosoftVisualStudioLanguageServerClientVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerClientVersion> <MicrosoftVisualStudioLanguageStandardClassificationVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageStandardClassificationVersion> <MicrosoftVisualStudioLiveShareVersion>2.18.6</MicrosoftVisualStudioLiveShareVersion> <MicrosoftVisualStudioLiveShareLanguageServicesVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesVersion> <MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion> <MicrosoftVisualStudioLiveShareWebEditorsVersion>3.0.8</MicrosoftVisualStudioLiveShareWebEditorsVersion> <MicrosoftVisualStudioPlatformVSEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioPlatformVSEditorVersion> <MicrosoftVisualStudioProgressionCodeSchemaVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCodeSchemaVersion> <MicrosoftVisualStudioProgressionCommonVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCommonVersion> <MicrosoftVisualStudioProgressionInterfacesVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionInterfacesVersion> <MicrosoftVisualStudioProjectSystemVersion>17.0.77-pre-g62a6cb5699</MicrosoftVisualStudioProjectSystemVersion> <MicrosoftVisualStudioProjectSystemManagedVersion>2.3.6152103</MicrosoftVisualStudioProjectSystemManagedVersion> <MicrosoftVisualStudioRemoteControlVersion>16.3.32</MicrosoftVisualStudioRemoteControlVersion> <MicrosoftVisualStudioSDKAnalyzersVersion>16.10.1</MicrosoftVisualStudioSDKAnalyzersVersion> <MicrosoftVisualStudioSetupConfigurationInteropVersion>1.16.30</MicrosoftVisualStudioSetupConfigurationInteropVersion> <MicrosoftVisualStudioShell150Version>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShell150Version> <MicrosoftVisualStudioShellFrameworkVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellFrameworkVersion> <MicrosoftVisualStudioShellDesignVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellDesignVersion> <MicrosoftVisualStudioTelemetryVersion>16.3.176</MicrosoftVisualStudioTelemetryVersion> <MicrosoftVisualStudioTemplateWizardInterfaceVersion>8.0.0.0-alpha</MicrosoftVisualStudioTemplateWizardInterfaceVersion> <MicrosoftVisualStudioTextDataVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextDataVersion> <MicrosoftVisualStudioTextInternalVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextInternalVersion> <MicrosoftVisualStudioTextLogicVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextLogicVersion> <MicrosoftVisualStudioTextUIVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIVersion> <MicrosoftVisualStudioTextUIWpfVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIWpfVersion> <MicrosoftVisualStudioTextUICocoaVersion>$(VisualStudioEditorPackagesVersion)</MicrosoftVisualStudioTextUICocoaVersion> <MicrosoftVisualStudioThreadingAnalyzersVersion>17.0.17-alpha</MicrosoftVisualStudioThreadingAnalyzersVersion> <MicrosoftVisualStudioThreadingVersion>17.0.17-alpha</MicrosoftVisualStudioThreadingVersion> <MicrosoftVisualStudioUtilitiesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioUtilitiesVersion> <MicrosoftVisualStudioValidationVersion>17.0.16-alpha</MicrosoftVisualStudioValidationVersion> <MicrosoftVisualStudioInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioInteractiveWindowVersion> <MicrosoftVisualStudioVsInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioVsInteractiveWindowVersion> <MicrosoftVisualStudioWorkspaceVSIntegrationVersion>16.3.43</MicrosoftVisualStudioWorkspaceVSIntegrationVersion> <MicrosoftWin32PrimitivesVersion>4.3.0</MicrosoftWin32PrimitivesVersion> <MicrosoftWin32RegistryVersion>5.0.0</MicrosoftWin32RegistryVersion> <MSBuildStructuredLoggerVersion>2.1.500</MSBuildStructuredLoggerVersion> <MDbgVersion>0.1.0</MDbgVersion> <MonoOptionsVersion>6.6.0.161</MonoOptionsVersion> <MoqVersion>4.10.1</MoqVersion> <NerdbankStreamsVersion>2.7.74</NerdbankStreamsVersion> <NuGetVisualStudioVersion>6.0.0-preview.0.15</NuGetVisualStudioVersion> <NuGetSolutionRestoreManagerInteropVersion>4.8.0</NuGetSolutionRestoreManagerInteropVersion> <MicrosoftDiaSymReaderPdb2PdbVersion>1.1.0-beta1-62506-02</MicrosoftDiaSymReaderPdb2PdbVersion> <RestSharpVersion>105.2.3</RestSharpVersion> <RichCodeNavEnvVarDumpVersion>0.1.1643-alpha</RichCodeNavEnvVarDumpVersion> <RoslynBuildUtilVersion>0.9.8-beta</RoslynBuildUtilVersion> <RoslynDependenciesOptimizationDataVersion>3.0.0-beta2-19053-01</RoslynDependenciesOptimizationDataVersion> <RoslynDiagnosticsAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</RoslynDiagnosticsAnalyzersVersion> <RoslynToolsVSIXExpInstallerVersion>1.1.0-beta3.21418.3</RoslynToolsVSIXExpInstallerVersion> <RoslynMicrosoftVisualStudioExtensionManagerVersion>0.0.4</RoslynMicrosoftVisualStudioExtensionManagerVersion> <SourceBrowserVersion>1.0.21</SourceBrowserVersion> <SystemBuffersVersion>4.5.1</SystemBuffersVersion> <SystemCompositionVersion>1.0.31</SystemCompositionVersion> <SystemCodeDomVersion>4.7.0</SystemCodeDomVersion> <SystemCommandLineVersion>2.0.0-beta1.20574.7</SystemCommandLineVersion> <SystemCommandLineExperimentalVersion>0.3.0-alpha.19577.1</SystemCommandLineExperimentalVersion> <SystemComponentModelCompositionVersion>4.5.0</SystemComponentModelCompositionVersion> <SystemDrawingCommonVersion>4.5.0</SystemDrawingCommonVersion> <SystemIOFileSystemVersion>4.3.0</SystemIOFileSystemVersion> <SystemIOFileSystemPrimitivesVersion>4.3.0</SystemIOFileSystemPrimitivesVersion> <SystemIOPipesAccessControlVersion>4.5.1</SystemIOPipesAccessControlVersion> <SystemIOPipelinesVersion>5.0.1</SystemIOPipelinesVersion> <SystemManagementVersion>5.0.0-preview.8.20407.11</SystemManagementVersion> <SystemMemoryVersion>4.5.4</SystemMemoryVersion> <SystemResourcesExtensionsVersion>4.7.1</SystemResourcesExtensionsVersion> <SystemRuntimeCompilerServicesUnsafeVersion>5.0.0</SystemRuntimeCompilerServicesUnsafeVersion> <SystemRuntimeLoaderVersion>4.3.0</SystemRuntimeLoaderVersion> <SystemSecurityPrincipalVersion>4.3.0</SystemSecurityPrincipalVersion> <SystemTextEncodingCodePagesVersion>4.5.1</SystemTextEncodingCodePagesVersion> <SystemTextEncodingExtensionsVersion>4.3.0</SystemTextEncodingExtensionsVersion> <!-- Note: When updating SystemTextJsonVersion ensure that the version is no higher than what is used by MSBuild. --> <SystemTextJsonVersion>4.7.0</SystemTextJsonVersion> <SystemThreadingTasksDataflowVersion>5.0.0</SystemThreadingTasksDataflowVersion> <!-- We need System.ValueTuple assembly version at least 4.0.3.0 on net47 to make F5 work against Dev15 - see https://github.com/dotnet/roslyn/issues/29705 --> <SystemValueTupleVersion>4.5.0</SystemValueTupleVersion> <SystemThreadingTasksExtensionsVersion>4.5.4</SystemThreadingTasksExtensionsVersion> <SQLitePCLRawbundle_greenVersion>2.0.4</SQLitePCLRawbundle_greenVersion> <UIAComWrapperVersion>1.1.0.14</UIAComWrapperVersion> <MicroBuildPluginsSwixBuildVersion>1.1.33</MicroBuildPluginsSwixBuildVersion> <MicrosoftVSSDKBuildToolsVersion>17.0.1056-Dev17PIAs-g9dffd635</MicrosoftVSSDKBuildToolsVersion> <MicrosoftVSSDKVSDConfigToolVersion>16.0.2032702</MicrosoftVSSDKVSDConfigToolVersion> <VsWebsiteInteropVersion>8.0.50727</VsWebsiteInteropVersion> <vswhereVersion>2.4.1</vswhereVersion> <XamarinMacVersion>1.0.0</XamarinMacVersion> <xunitVersion>2.4.1-pre.build.4059</xunitVersion> <xunitanalyzersVersion>0.10.0</xunitanalyzersVersion> <xunitassertVersion>$(xunitVersion)</xunitassertVersion> <XunitCombinatorialVersion>1.3.2</XunitCombinatorialVersion> <XUnitXmlTestLoggerVersion>2.1.26</XUnitXmlTestLoggerVersion> <xunitextensibilitycoreVersion>$(xunitVersion)</xunitextensibilitycoreVersion> <xunitrunnerconsoleVersion>2.4.1-pre.build.4059</xunitrunnerconsoleVersion> <xunitrunnerwpfVersion>1.0.51</xunitrunnerwpfVersion> <xunitrunnervisualstudioVersion>$(xunitVersion)</xunitrunnervisualstudioVersion> <xunitextensibilityexecutionVersion>$(xunitVersion)</xunitextensibilityexecutionVersion> <runtimeWinX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILAsmPackageVersion> <runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion> <runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion> <runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion> <runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion> <runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion> <!-- NOTE: The following dependencies have been identified as particularly problematic to update. If you bump their versions, you must push your changes to a dev branch in dotnet/roslyn and create a test insertion in Visual Studio to validate. --> <NewtonsoftJsonVersion>12.0.2</NewtonsoftJsonVersion> <StreamJsonRpcVersion>2.8.21</StreamJsonRpcVersion> <!-- When updating the S.C.I or S.R.M version please let the MSBuild team know in advance so they can update to the same version. Version changes require a VS test insertion for validation. --> <SystemCollectionsImmutableVersion>5.0.0</SystemCollectionsImmutableVersion> <SystemReflectionMetadataVersion>5.0.0</SystemReflectionMetadataVersion> <MicrosoftBclAsyncInterfacesVersion>5.0.0</MicrosoftBclAsyncInterfacesVersion> </PropertyGroup> <PropertyGroup> <UsingToolPdbConverter>true</UsingToolPdbConverter> <UsingToolSymbolUploader>true</UsingToolSymbolUploader> <UsingToolNuGetRepack>true</UsingToolNuGetRepack> <UsingToolVSSDK>true</UsingToolVSSDK> <UsingToolNetFrameworkReferenceAssemblies>true</UsingToolNetFrameworkReferenceAssemblies> <UsingToolIbcOptimization>true</UsingToolIbcOptimization> <UsingToolVisualStudioIbcTraining>true</UsingToolVisualStudioIbcTraining> <UsingToolXliff>true</UsingToolXliff> <UsingToolXUnit>true</UsingToolXUnit> <DiscoverEditorConfigFiles>true</DiscoverEditorConfigFiles> <!-- When using a bootstrap builder we don't want to use the Microsoft.Net.Compilers.Toolset package but rather explicitly override it. --> <UsingToolMicrosoftNetCompilers Condition="'$(BootstrapBuildPath)' == ''">true</UsingToolMicrosoftNetCompilers> <UseVSTestRunner>true</UseVSTestRunner> </PropertyGroup> </Project>
1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/CSharp/Portable/Symbols/AssemblySymbol.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a .NET assembly, consisting of one or more modules. /// </summary> internal abstract class AssemblySymbol : Symbol, IAssemblySymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /// <summary> /// The system assembly, which provides primitive types like Object, String, etc., e.g. mscorlib.dll. /// The value is provided by ReferenceManager and must not be modified. For SourceAssemblySymbol, non-missing /// coreLibrary must match one of the referenced assemblies returned by GetReferencedAssemblySymbols() method of /// the main module. If there is no existing assembly that can be used as a source for the primitive types, /// the value is a Compilation.MissingCorLibrary. /// </summary> private AssemblySymbol _corLibrary; /// <summary> /// The system assembly, which provides primitive types like Object, String, etc., e.g. mscorlib.dll. /// The value is MissingAssemblySymbol if none of the referenced assemblies can be used as a source for the /// primitive types and the owning assembly cannot be used as the source too. Otherwise, it is one of /// the referenced assemblies returned by GetReferencedAssemblySymbols() method or the owning assembly. /// </summary> internal AssemblySymbol CorLibrary { get { return _corLibrary; } } /// <summary> /// A helper method for ReferenceManager to set the system assembly, which provides primitive /// types like Object, String, etc., e.g. mscorlib.dll. /// </summary> internal void SetCorLibrary(AssemblySymbol corLibrary) { Debug.Assert((object)_corLibrary == null); _corLibrary = corLibrary; } /// <summary> /// Simple name the assembly. /// </summary> /// <remarks> /// This is equivalent to <see cref="Identity"/>.<see cref="AssemblyIdentity.Name"/>, but may be /// much faster to retrieve for source code assemblies, since it does not require binding /// the assembly-level attributes that contain the version number and other assembly /// information. /// </remarks> public override string Name { get { return Identity.Name; } } /// <summary> /// Gets the identity of this assembly. /// </summary> public abstract AssemblyIdentity Identity { get; } AssemblyIdentity IAssemblySymbolInternal.Identity => Identity; IAssemblySymbolInternal IAssemblySymbolInternal.CorLibrary => CorLibrary; /// <summary> /// Assembly version pattern with wildcards represented by <see cref="ushort.MaxValue"/>, /// or null if the version string specified in the <see cref="AssemblyVersionAttribute"/> doesn't contain a wildcard. /// /// For example, /// AssemblyVersion("1.2.*") is represented as 1.2.65535.65535, /// AssemblyVersion("1.2.3.*") is represented as 1.2.3.65535. /// </summary> public abstract Version AssemblyVersionPattern { get; } /// <summary> /// Target architecture of the machine. /// </summary> internal Machine Machine { get { return Modules[0].Machine; } } /// <summary> /// Indicates that this PE file makes Win32 calls. See CorPEKind.pe32BitRequired for more information (http://msdn.microsoft.com/en-us/library/ms230275.aspx). /// </summary> internal bool Bit32Required { get { return Modules[0].Bit32Required; } } /// <summary> /// Gets the merged root namespace that contains all namespaces and types defined in the modules /// of this assembly. If there is just one module in this assembly, this property just returns the /// GlobalNamespace of that module. /// </summary> public abstract NamespaceSymbol GlobalNamespace { get; } /// <summary> /// Given a namespace symbol, returns the corresponding assembly specific namespace symbol /// </summary> internal NamespaceSymbol GetAssemblyNamespace(NamespaceSymbol namespaceSymbol) { if (namespaceSymbol.IsGlobalNamespace) { return this.GlobalNamespace; } NamespaceSymbol container = namespaceSymbol.ContainingNamespace; if ((object)container == null) { return this.GlobalNamespace; } if (namespaceSymbol.NamespaceKind == NamespaceKind.Assembly && namespaceSymbol.ContainingAssembly == this) { // this is already the correct assembly namespace return namespaceSymbol; } NamespaceSymbol assemblyContainer = GetAssemblyNamespace(container); if ((object)assemblyContainer == (object)container) { // Trivial case, container isn't merged. return namespaceSymbol; } if ((object)assemblyContainer == null) { return null; } return assemblyContainer.GetNestedNamespace(namespaceSymbol.Name); } /// <summary> /// Gets a read-only list of all the modules in this assembly. (There must be at least one.) The first one is the main module /// that holds the assembly manifest. /// </summary> public abstract ImmutableArray<ModuleSymbol> Modules { get; } internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitAssembly(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitAssembly(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitAssembly(this); } public sealed override SymbolKind Kind { get { return SymbolKind.Assembly; } } public sealed override AssemblySymbol ContainingAssembly { get { return null; } } // Only the compiler can create AssemblySymbols. internal AssemblySymbol() { } /// <summary> /// Does this symbol represent a missing assembly. /// </summary> internal abstract bool IsMissing { get; } public sealed override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } public sealed override bool IsStatic { get { return false; } } public sealed override bool IsVirtual { get { return false; } } public sealed override bool IsOverride { get { return false; } } public sealed override bool IsAbstract { get { return false; } } public sealed override bool IsSealed { get { return false; } } public sealed override bool IsExtern { get { return false; } } /// <summary> /// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute. /// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet. /// </summary> internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } /// <summary> /// True if the assembly contains interactive code. /// </summary> public virtual bool IsInteractive { get { return false; } } public sealed override Symbol ContainingSymbol { get { return null; } } /// <summary> /// Lookup a top level type referenced from metadata, names should be /// compared case-sensitively. /// </summary> /// <param name="emittedName"> /// Full type name with generic name mangling. /// </param> /// <param name="digThroughForwardedTypes"> /// Take forwarded types into account. /// </param> /// <remarks></remarks> internal NamedTypeSymbol LookupTopLevelMetadataType(ref MetadataTypeName emittedName, bool digThroughForwardedTypes) { return LookupTopLevelMetadataTypeWithCycleDetection(ref emittedName, visitedAssemblies: null, digThroughForwardedTypes: digThroughForwardedTypes); } /// <summary> /// Lookup a top level type referenced from metadata, names should be /// compared case-sensitively. Detect cycles during lookup. /// </summary> /// <param name="emittedName"> /// Full type name, possibly with generic name mangling. /// </param> /// <param name="visitedAssemblies"> /// List of assemblies lookup has already visited (since type forwarding can introduce cycles). /// </param> /// <param name="digThroughForwardedTypes"> /// Take forwarded types into account. /// </param> internal abstract NamedTypeSymbol LookupTopLevelMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList<AssemblySymbol> visitedAssemblies, bool digThroughForwardedTypes); /// <summary> /// Returns the type symbol for a forwarded type based its canonical CLR metadata name. /// The name should refer to a non-nested type. If type with this name is not forwarded, /// null is returned. /// </summary> public NamedTypeSymbol ResolveForwardedType(string fullyQualifiedMetadataName) { if (fullyQualifiedMetadataName == null) { throw new ArgumentNullException(nameof(fullyQualifiedMetadataName)); } var emittedName = MetadataTypeName.FromFullName(fullyQualifiedMetadataName); return TryLookupForwardedMetadataType(ref emittedName); } /// <summary> /// Look up the given metadata type, if it is forwarded. /// </summary> internal NamedTypeSymbol TryLookupForwardedMetadataType(ref MetadataTypeName emittedName) { return TryLookupForwardedMetadataTypeWithCycleDetection(ref emittedName, visitedAssemblies: null); } /// <summary> /// Look up the given metadata type, if it is forwarded. /// </summary> internal virtual NamedTypeSymbol TryLookupForwardedMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList<AssemblySymbol> visitedAssemblies) { return null; } internal ErrorTypeSymbol CreateCycleInTypeForwarderErrorTypeSymbol(ref MetadataTypeName emittedName) { DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_CycleInTypeForwarder, emittedName.FullName, this.Name); return new MissingMetadataTypeSymbol.TopLevel(this.Modules[0], ref emittedName, diagnosticInfo); } internal ErrorTypeSymbol CreateMultipleForwardingErrorTypeSymbol(ref MetadataTypeName emittedName, ModuleSymbol forwardingModule, AssemblySymbol destination1, AssemblySymbol destination2) { var diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, forwardingModule, this, emittedName.FullName, destination1, destination2); return new MissingMetadataTypeSymbol.TopLevel(forwardingModule, ref emittedName, diagnosticInfo); } internal abstract IEnumerable<NamedTypeSymbol> GetAllTopLevelForwardedTypes(); /// <summary> /// Lookup declaration for predefined CorLib type in this Assembly. /// </summary> /// <returns>The symbol for the pre-defined type or an error type if the type is not defined in the core library.</returns> internal abstract NamedTypeSymbol GetDeclaredSpecialType(SpecialType type); /// <summary> /// Register declaration of predefined CorLib type in this Assembly. /// </summary> /// <param name="corType"></param> internal virtual void RegisterDeclaredSpecialType(NamedTypeSymbol corType) { throw ExceptionUtilities.Unreachable; } /// <summary> /// Continue looking for declaration of predefined CorLib type in this Assembly /// while symbols for new type declarations are constructed. /// </summary> internal virtual bool KeepLookingForDeclaredSpecialTypes { get { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Return the native integer type corresponding to the underlying type. /// </summary> internal virtual NamedTypeSymbol GetNativeIntegerType(NamedTypeSymbol underlyingType) { throw ExceptionUtilities.Unreachable; } /// <summary> /// Figure out if the target runtime supports default interface implementation. /// </summary> internal bool RuntimeSupportsDefaultInterfaceImplementation { get => RuntimeSupportsFeature(SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces); } /// <summary> /// Figure out if the target runtime supports static abstract members in interfaces. /// </summary> internal bool RuntimeSupportsStaticAbstractMembersInInterfaces { // https://github.com/dotnet/roslyn/issues/53800: Implement the actual check, this is a temporary stub. get => RuntimeSupportsDefaultInterfaceImplementation; } private bool RuntimeSupportsFeature(SpecialMember feature) { Debug.Assert((SpecialType)SpecialMembers.GetDescriptor(feature).DeclaringTypeId == SpecialType.System_Runtime_CompilerServices_RuntimeFeature); return GetSpecialType(SpecialType.System_Runtime_CompilerServices_RuntimeFeature) is { TypeKind: TypeKind.Class, IsStatic: true } && GetSpecialTypeMember(feature) is object; } internal bool RuntimeSupportsUnmanagedSignatureCallingConvention => RuntimeSupportsFeature(SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention); /// <summary> /// True if the target runtime support covariant returns of methods declared in classes. /// </summary> internal bool RuntimeSupportsCovariantReturnsOfClasses { get { // check for the runtime feature indicator and the required attribute. return RuntimeSupportsFeature(SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses) && GetSpecialType(SpecialType.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute) is { TypeKind: TypeKind.Class }; } } /// <summary> /// Return an array of assemblies involved in canonical type resolution of /// NoPia local types defined within this assembly. In other words, all /// references used by previous compilation referencing this assembly. /// </summary> /// <returns></returns> internal abstract ImmutableArray<AssemblySymbol> GetNoPiaResolutionAssemblies(); internal abstract void SetNoPiaResolutionAssemblies(ImmutableArray<AssemblySymbol> assemblies); /// <summary> /// Return an array of assemblies referenced by this assembly, which are linked (/l-ed) by /// each compilation that is using this AssemblySymbol as a reference. /// If this AssemblySymbol is linked too, it will be in this array too. /// </summary> internal abstract ImmutableArray<AssemblySymbol> GetLinkedReferencedAssemblies(); internal abstract void SetLinkedReferencedAssemblies(ImmutableArray<AssemblySymbol> assemblies); internal abstract IEnumerable<ImmutableArray<byte>> GetInternalsVisibleToPublicKeys(string simpleName); internal abstract bool AreInternalsVisibleToThisAssembly(AssemblySymbol other); /// <summary> /// Assembly is /l-ed by compilation that is using it as a reference. /// </summary> internal abstract bool IsLinked { get; } /// <summary> /// Returns true and a string from the first GuidAttribute on the assembly, /// the string might be null or an invalid guid representation. False, /// if there is no GuidAttribute with string argument. /// </summary> internal virtual bool GetGuidString(out string guidString) { return GetGuidStringDefaultImplementation(out guidString); } /// <summary> /// Gets the set of type identifiers from this assembly. /// </summary> /// <remarks> /// These names are the simple identifiers for the type, and do not include namespaces, /// outer type names, or type parameters. /// /// This functionality can be used for features that want to quickly know if a name could be /// a type for performance reasons. For example, classification does not want to incur an /// expensive binding call cost if it knows that there is no type with the name that they /// are looking at. /// </remarks> public abstract ICollection<string> TypeNames { get; } /// <summary> /// Gets the set of namespace names from this assembly. /// </summary> public abstract ICollection<string> NamespaceNames { get; } /// <summary> /// Returns true if this assembly might contain extension methods. If this property /// returns false, there are no extension methods in this assembly. /// </summary> /// <remarks> /// This property allows the search for extension methods to be narrowed quickly. /// </remarks> public abstract bool MightContainExtensionMethods { get; } /// <summary> /// Gets the symbol for the pre-defined type from core library associated with this assembly. /// </summary> /// <returns>The symbol for the pre-defined type or an error type if the type is not defined in the core library.</returns> internal NamedTypeSymbol GetSpecialType(SpecialType type) { return CorLibrary.GetDeclaredSpecialType(type); } internal static TypeSymbol DynamicType { get { return DynamicTypeSymbol.Instance; } } /// <summary> /// The NamedTypeSymbol for the .NET System.Object type, which could have a TypeKind of /// Error if there was no COR Library in a compilation using the assembly. /// </summary> internal NamedTypeSymbol ObjectType { get { return GetSpecialType(SpecialType.System_Object); } } /// <summary> /// Get symbol for predefined type from Cor Library used by this assembly. /// </summary> /// <param name="type"></param> /// <returns></returns> internal NamedTypeSymbol GetPrimitiveType(Microsoft.Cci.PrimitiveTypeCode type) { return GetSpecialType(SpecialTypes.GetTypeFromMetadataName(type)); } /// <summary> /// Lookup a type within the assembly using the canonical CLR metadata name of the type. /// </summary> /// <param name="fullyQualifiedMetadataName">Type name.</param> /// <returns>Symbol for the type or null if type cannot be found or is ambiguous. </returns> public NamedTypeSymbol GetTypeByMetadataName(string fullyQualifiedMetadataName) { if (fullyQualifiedMetadataName == null) { throw new ArgumentNullException(nameof(fullyQualifiedMetadataName)); } return this.GetTypeByMetadataName(fullyQualifiedMetadataName, includeReferences: false, isWellKnownType: false, conflicts: out var _); } /// <summary> /// Lookup a type within the assembly using its canonical CLR metadata name. /// </summary> /// <param name="metadataName"></param> /// <param name="includeReferences"> /// If search within assembly fails, lookup in assemblies referenced by the primary module. /// For source assembly, this is equivalent to all assembly references given to compilation. /// </param> /// <param name="isWellKnownType"> /// Extra restrictions apply when searching for a well-known type. In particular, the type must be public. /// </param> /// <param name="useCLSCompliantNameArityEncoding"> /// While resolving the name, consider only types following CLS-compliant generic type names and arity encoding (ECMA-335, section 10.7.2). /// I.e. arity is inferred from the name and matching type must have the same emitted name and arity. /// </param> /// <param name="warnings"> /// A diagnostic bag to receive warnings if we should allow multiple definitions and pick one. /// </param> /// <param name="ignoreCorLibraryDuplicatedTypes"> /// In case duplicate types are found, ignore the one from corlib. This is useful for any kind of compilation at runtime /// (EE/scripting/Powershell) using a type that is being migrated to corlib. /// </param> /// <param name="conflicts"> /// In cases a type could not be found because of ambiguity, we return two of the candidates that caused the ambiguity. /// </param> /// <returns>Null if the type can't be found.</returns> internal NamedTypeSymbol GetTypeByMetadataName( string metadataName, bool includeReferences, bool isWellKnownType, out (AssemblySymbol, AssemblySymbol) conflicts, bool useCLSCompliantNameArityEncoding = false, DiagnosticBag warnings = null, bool ignoreCorLibraryDuplicatedTypes = false) { NamedTypeSymbol type; MetadataTypeName mdName; if (metadataName.IndexOf('+') >= 0) { var parts = metadataName.Split(s_nestedTypeNameSeparators); Debug.Assert(parts.Length > 0); mdName = MetadataTypeName.FromFullName(parts[0], useCLSCompliantNameArityEncoding); type = GetTopLevelTypeByMetadataName(ref mdName, assemblyOpt: null, includeReferences: includeReferences, isWellKnownType: isWellKnownType, conflicts: out conflicts, warnings: warnings, ignoreCorLibraryDuplicatedTypes: ignoreCorLibraryDuplicatedTypes); for (int i = 1; (object)type != null && !type.IsErrorType() && i < parts.Length; i++) { mdName = MetadataTypeName.FromTypeName(parts[i]); NamedTypeSymbol temp = type.LookupMetadataType(ref mdName); type = (!isWellKnownType || IsValidWellKnownType(temp)) ? temp : null; } } else { mdName = MetadataTypeName.FromFullName(metadataName, useCLSCompliantNameArityEncoding); type = GetTopLevelTypeByMetadataName(ref mdName, assemblyOpt: null, includeReferences: includeReferences, isWellKnownType: isWellKnownType, conflicts: out conflicts, warnings: warnings, ignoreCorLibraryDuplicatedTypes: ignoreCorLibraryDuplicatedTypes); } return ((object)type == null || type.IsErrorType()) ? null : type; } private static readonly char[] s_nestedTypeNameSeparators = new char[] { '+' }; /// <summary> /// Resolves <see cref="System.Type"/> to a <see cref="TypeSymbol"/> available in this assembly /// its referenced assemblies. /// </summary> /// <param name="type">The type to resolve.</param> /// <param name="includeReferences">Use referenced assemblies for resolution.</param> /// <returns>The resolved symbol if successful or null on failure.</returns> internal TypeSymbol GetTypeByReflectionType(Type type, bool includeReferences) { System.Reflection.TypeInfo typeInfo = type.GetTypeInfo(); Debug.Assert(!typeInfo.IsByRef); // not supported (we don't accept open types as submission results nor host types): Debug.Assert(!typeInfo.ContainsGenericParameters); if (typeInfo.IsArray) { TypeSymbol symbol = GetTypeByReflectionType(typeInfo.GetElementType(), includeReferences); if ((object)symbol == null) { return null; } int rank = typeInfo.GetArrayRank(); return ArrayTypeSymbol.CreateCSharpArray(this, TypeWithAnnotations.Create(symbol), rank); } else if (typeInfo.IsPointer) { TypeSymbol symbol = GetTypeByReflectionType(typeInfo.GetElementType(), includeReferences); if ((object)symbol == null) { return null; } return new PointerTypeSymbol(TypeWithAnnotations.Create(symbol)); } else if (typeInfo.DeclaringType != null) { Debug.Assert(!typeInfo.IsArray); // consolidated generic arguments (includes arguments of all declaring types): Type[] genericArguments = typeInfo.GenericTypeArguments; int typeArgumentIndex = 0; var currentTypeInfo = typeInfo.IsGenericType ? typeInfo.GetGenericTypeDefinition().GetTypeInfo() : typeInfo; var nestedTypes = ArrayBuilder<System.Reflection.TypeInfo>.GetInstance(); while (true) { Debug.Assert(currentTypeInfo.IsGenericTypeDefinition || !currentTypeInfo.IsGenericType); nestedTypes.Add(currentTypeInfo); if (currentTypeInfo.DeclaringType == null) { break; } currentTypeInfo = currentTypeInfo.DeclaringType.GetTypeInfo(); } int i = nestedTypes.Count - 1; var symbol = (NamedTypeSymbol)GetTypeByReflectionType(nestedTypes[i].AsType(), includeReferences); if ((object)symbol == null) { return null; } while (--i >= 0) { int forcedArity = nestedTypes[i].GenericTypeParameters.Length - nestedTypes[i + 1].GenericTypeParameters.Length; MetadataTypeName mdName = MetadataTypeName.FromTypeName(nestedTypes[i].Name, forcedArity: forcedArity); symbol = symbol.LookupMetadataType(ref mdName); if ((object)symbol == null || symbol.IsErrorType()) { return null; } symbol = ApplyGenericArguments(symbol, genericArguments, ref typeArgumentIndex, includeReferences); if ((object)symbol == null) { return null; } } nestedTypes.Free(); Debug.Assert(typeArgumentIndex == genericArguments.Length); return symbol; } else { AssemblyIdentity assemblyId = AssemblyIdentity.FromAssemblyDefinition(typeInfo.Assembly); MetadataTypeName mdName = MetadataTypeName.FromNamespaceAndTypeName( typeInfo.Namespace ?? string.Empty, typeInfo.Name, forcedArity: typeInfo.GenericTypeArguments.Length); NamedTypeSymbol symbol = GetTopLevelTypeByMetadataName(ref mdName, assemblyId, includeReferences, isWellKnownType: false, conflicts: out var _); if ((object)symbol == null || symbol.IsErrorType()) { return null; } int typeArgumentIndex = 0; Type[] genericArguments = typeInfo.GenericTypeArguments; symbol = ApplyGenericArguments(symbol, genericArguments, ref typeArgumentIndex, includeReferences); Debug.Assert(typeArgumentIndex == genericArguments.Length); return symbol; } } private NamedTypeSymbol ApplyGenericArguments(NamedTypeSymbol symbol, Type[] typeArguments, ref int currentTypeArgument, bool includeReferences) { int remainingTypeArguments = typeArguments.Length - currentTypeArgument; // in case we are specializing a nested generic definition we might have more arguments than the current symbol: Debug.Assert(remainingTypeArguments >= symbol.Arity); if (remainingTypeArguments == 0) { return symbol; } var length = symbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; var typeArgumentSymbols = ArrayBuilder<TypeWithAnnotations>.GetInstance(length); for (int i = 0; i < length; i++) { var argSymbol = GetTypeByReflectionType(typeArguments[currentTypeArgument++], includeReferences); if ((object)argSymbol == null) { return null; } typeArgumentSymbols.Add(TypeWithAnnotations.Create(argSymbol)); } return symbol.ConstructIfGeneric(typeArgumentSymbols.ToImmutableAndFree()); } internal NamedTypeSymbol GetTopLevelTypeByMetadataName( ref MetadataTypeName metadataName, AssemblyIdentity assemblyOpt, bool includeReferences, bool isWellKnownType, out (AssemblySymbol, AssemblySymbol) conflicts, DiagnosticBag warnings = null, // this is set to collect ambiguity warning for well-known types before C# 7 bool ignoreCorLibraryDuplicatedTypes = false) { // Type from this assembly always wins. // After that we look in references, which may yield ambiguities. If `ignoreCorLibraryDuplicatedTypes` is set, // corlib does not contribute to ambiguities (corlib loses over other references). // For well-known types before C# 7, ambiguities are reported as a warning and the first candidate wins. // For other types, when `ignoreCorLibraryDuplicatedTypes` isn't set, finding a candidate in corlib resolves // ambiguities (corlib wins over other references). Debug.Assert(warnings is null || isWellKnownType); conflicts = default; NamedTypeSymbol result; // First try this assembly result = GetTopLevelTypeByMetadataName(this, ref metadataName, assemblyOpt); if (isWellKnownType && !IsValidWellKnownType(result)) { result = null; } // ignore any types of the same name that might be in referenced assemblies (prefer the current assembly): if ((object)result != null || !includeReferences) { return result; } // Then try corlib, when finding a result there means we've found the final result bool isWellKnownTypeBeforeCSharp7 = isWellKnownType && warnings is not null; bool skipCorLibrary = false; if (CorLibrary != (object)this && !CorLibrary.IsMissing && !isWellKnownTypeBeforeCSharp7 && !ignoreCorLibraryDuplicatedTypes) { NamedTypeSymbol corLibCandidate = GetTopLevelTypeByMetadataName(CorLibrary, ref metadataName, assemblyOpt); skipCorLibrary = true; if (isValidCandidate(corLibCandidate, isWellKnownType)) { return corLibCandidate; } } Debug.Assert(this is SourceAssemblySymbol, "Never include references for a non-source assembly, because they don't know about aliases."); var assemblies = ArrayBuilder<AssemblySymbol>.GetInstance(); // ignore reference aliases if searching for a type from a specific assembly: if (assemblyOpt != null) { assemblies.AddRange(DeclaringCompilation.GetBoundReferenceManager().ReferencedAssemblies); } else { DeclaringCompilation.GetUnaliasedReferencedAssemblies(assemblies); } // Lookup in references foreach (var assembly in assemblies) { Debug.Assert(!(this is SourceAssemblySymbol && assembly.IsMissing)); // Non-source assemblies can have missing references if (skipCorLibrary && assembly == (object)CorLibrary) { continue; } NamedTypeSymbol candidate = GetTopLevelTypeByMetadataName(assembly, ref metadataName, assemblyOpt); if (!isValidCandidate(candidate, isWellKnownType)) { continue; } Debug.Assert(!TypeSymbol.Equals(candidate, result, TypeCompareKind.ConsiderEverything)); if ((object)result != null) { // duplicate if (ignoreCorLibraryDuplicatedTypes) { if (IsInCorLib(candidate)) { // ignore candidate continue; } if (IsInCorLib(result)) { // drop previous result result = candidate; continue; } } if (warnings is null) { conflicts = (result.ContainingAssembly, candidate.ContainingAssembly); result = null; } else { // The predefined type '{0}' is defined in multiple assemblies in the global alias; using definition from '{1}' warnings.Add(ErrorCode.WRN_MultiplePredefTypes, NoLocation.Singleton, result, result.ContainingAssembly); } break; } result = candidate; } assemblies.Free(); return result; bool isValidCandidate(NamedTypeSymbol candidate, bool isWellKnownType) { return candidate is not null && (!isWellKnownType || IsValidWellKnownType(candidate)) && !candidate.IsHiddenByCodeAnalysisEmbeddedAttribute(); } } private bool IsInCorLib(NamedTypeSymbol type) { return (object)type.ContainingAssembly == CorLibrary; } private bool IsValidWellKnownType(NamedTypeSymbol result) { if ((object)result == null || result.TypeKind == TypeKind.Error) { return false; } Debug.Assert((object)result.ContainingType == null || IsValidWellKnownType(result.ContainingType), "Checking the containing type is the caller's responsibility."); return result.DeclaredAccessibility == Accessibility.Public || IsSymbolAccessible(result, this); } private static NamedTypeSymbol GetTopLevelTypeByMetadataName(AssemblySymbol assembly, ref MetadataTypeName metadataName, AssemblyIdentity assemblyOpt) { var result = assembly.LookupTopLevelMetadataType(ref metadataName, digThroughForwardedTypes: false); if (!IsAcceptableMatchForGetTypeByMetadataName(result)) { return null; } if (assemblyOpt != null && !assemblyOpt.Equals(assembly.Identity)) { return null; } return result; } private static bool IsAcceptableMatchForGetTypeByMetadataName(NamedTypeSymbol candidate) { return candidate.Kind != SymbolKind.ErrorType || !(candidate is MissingMetadataTypeSymbol); } /// <summary> /// Lookup member declaration in predefined CorLib type in this Assembly. Only valid if this /// assembly is the Cor Library /// </summary> internal virtual Symbol GetDeclaredSpecialTypeMember(SpecialMember member) { return null; } /// <summary> /// Lookup member declaration in predefined CorLib type used by this Assembly. /// </summary> internal virtual Symbol GetSpecialTypeMember(SpecialMember member) { return CorLibrary.GetDeclaredSpecialTypeMember(member); } internal abstract ImmutableArray<byte> PublicKey { get; } /// <summary> /// If this symbol represents a metadata assembly returns the underlying <see cref="AssemblyMetadata"/>. /// /// Otherwise, this returns <see langword="null"/>. /// </summary> public abstract AssemblyMetadata GetMetadata(); protected override ISymbol CreateISymbol() { return new PublicModel.NonSourceAssemblySymbol(this); } } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a .NET assembly, consisting of one or more modules. /// </summary> internal abstract class AssemblySymbol : Symbol, IAssemblySymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /// <summary> /// The system assembly, which provides primitive types like Object, String, etc., e.g. mscorlib.dll. /// The value is provided by ReferenceManager and must not be modified. For SourceAssemblySymbol, non-missing /// coreLibrary must match one of the referenced assemblies returned by GetReferencedAssemblySymbols() method of /// the main module. If there is no existing assembly that can be used as a source for the primitive types, /// the value is a Compilation.MissingCorLibrary. /// </summary> private AssemblySymbol _corLibrary; /// <summary> /// The system assembly, which provides primitive types like Object, String, etc., e.g. mscorlib.dll. /// The value is MissingAssemblySymbol if none of the referenced assemblies can be used as a source for the /// primitive types and the owning assembly cannot be used as the source too. Otherwise, it is one of /// the referenced assemblies returned by GetReferencedAssemblySymbols() method or the owning assembly. /// </summary> internal AssemblySymbol CorLibrary { get { return _corLibrary; } } /// <summary> /// A helper method for ReferenceManager to set the system assembly, which provides primitive /// types like Object, String, etc., e.g. mscorlib.dll. /// </summary> internal void SetCorLibrary(AssemblySymbol corLibrary) { Debug.Assert((object)_corLibrary == null); _corLibrary = corLibrary; } /// <summary> /// Simple name the assembly. /// </summary> /// <remarks> /// This is equivalent to <see cref="Identity"/>.<see cref="AssemblyIdentity.Name"/>, but may be /// much faster to retrieve for source code assemblies, since it does not require binding /// the assembly-level attributes that contain the version number and other assembly /// information. /// </remarks> public override string Name { get { return Identity.Name; } } /// <summary> /// Gets the identity of this assembly. /// </summary> public abstract AssemblyIdentity Identity { get; } AssemblyIdentity IAssemblySymbolInternal.Identity => Identity; IAssemblySymbolInternal IAssemblySymbolInternal.CorLibrary => CorLibrary; /// <summary> /// Assembly version pattern with wildcards represented by <see cref="ushort.MaxValue"/>, /// or null if the version string specified in the <see cref="AssemblyVersionAttribute"/> doesn't contain a wildcard. /// /// For example, /// AssemblyVersion("1.2.*") is represented as 1.2.65535.65535, /// AssemblyVersion("1.2.3.*") is represented as 1.2.3.65535. /// </summary> public abstract Version AssemblyVersionPattern { get; } /// <summary> /// Target architecture of the machine. /// </summary> internal Machine Machine { get { return Modules[0].Machine; } } /// <summary> /// Indicates that this PE file makes Win32 calls. See CorPEKind.pe32BitRequired for more information (http://msdn.microsoft.com/en-us/library/ms230275.aspx). /// </summary> internal bool Bit32Required { get { return Modules[0].Bit32Required; } } /// <summary> /// Gets the merged root namespace that contains all namespaces and types defined in the modules /// of this assembly. If there is just one module in this assembly, this property just returns the /// GlobalNamespace of that module. /// </summary> public abstract NamespaceSymbol GlobalNamespace { get; } /// <summary> /// Given a namespace symbol, returns the corresponding assembly specific namespace symbol /// </summary> internal NamespaceSymbol GetAssemblyNamespace(NamespaceSymbol namespaceSymbol) { if (namespaceSymbol.IsGlobalNamespace) { return this.GlobalNamespace; } NamespaceSymbol container = namespaceSymbol.ContainingNamespace; if ((object)container == null) { return this.GlobalNamespace; } if (namespaceSymbol.NamespaceKind == NamespaceKind.Assembly && namespaceSymbol.ContainingAssembly == this) { // this is already the correct assembly namespace return namespaceSymbol; } NamespaceSymbol assemblyContainer = GetAssemblyNamespace(container); if ((object)assemblyContainer == (object)container) { // Trivial case, container isn't merged. return namespaceSymbol; } if ((object)assemblyContainer == null) { return null; } return assemblyContainer.GetNestedNamespace(namespaceSymbol.Name); } /// <summary> /// Gets a read-only list of all the modules in this assembly. (There must be at least one.) The first one is the main module /// that holds the assembly manifest. /// </summary> public abstract ImmutableArray<ModuleSymbol> Modules { get; } internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitAssembly(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitAssembly(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitAssembly(this); } public sealed override SymbolKind Kind { get { return SymbolKind.Assembly; } } public sealed override AssemblySymbol ContainingAssembly { get { return null; } } // Only the compiler can create AssemblySymbols. internal AssemblySymbol() { } /// <summary> /// Does this symbol represent a missing assembly. /// </summary> internal abstract bool IsMissing { get; } public sealed override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } public sealed override bool IsStatic { get { return false; } } public sealed override bool IsVirtual { get { return false; } } public sealed override bool IsOverride { get { return false; } } public sealed override bool IsAbstract { get { return false; } } public sealed override bool IsSealed { get { return false; } } public sealed override bool IsExtern { get { return false; } } /// <summary> /// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute. /// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet. /// </summary> internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } /// <summary> /// True if the assembly contains interactive code. /// </summary> public virtual bool IsInteractive { get { return false; } } public sealed override Symbol ContainingSymbol { get { return null; } } /// <summary> /// Lookup a top level type referenced from metadata, names should be /// compared case-sensitively. /// </summary> /// <param name="emittedName"> /// Full type name with generic name mangling. /// </param> /// <param name="digThroughForwardedTypes"> /// Take forwarded types into account. /// </param> /// <remarks></remarks> internal NamedTypeSymbol LookupTopLevelMetadataType(ref MetadataTypeName emittedName, bool digThroughForwardedTypes) { return LookupTopLevelMetadataTypeWithCycleDetection(ref emittedName, visitedAssemblies: null, digThroughForwardedTypes: digThroughForwardedTypes); } /// <summary> /// Lookup a top level type referenced from metadata, names should be /// compared case-sensitively. Detect cycles during lookup. /// </summary> /// <param name="emittedName"> /// Full type name, possibly with generic name mangling. /// </param> /// <param name="visitedAssemblies"> /// List of assemblies lookup has already visited (since type forwarding can introduce cycles). /// </param> /// <param name="digThroughForwardedTypes"> /// Take forwarded types into account. /// </param> internal abstract NamedTypeSymbol LookupTopLevelMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList<AssemblySymbol> visitedAssemblies, bool digThroughForwardedTypes); /// <summary> /// Returns the type symbol for a forwarded type based its canonical CLR metadata name. /// The name should refer to a non-nested type. If type with this name is not forwarded, /// null is returned. /// </summary> public NamedTypeSymbol ResolveForwardedType(string fullyQualifiedMetadataName) { if (fullyQualifiedMetadataName == null) { throw new ArgumentNullException(nameof(fullyQualifiedMetadataName)); } var emittedName = MetadataTypeName.FromFullName(fullyQualifiedMetadataName); return TryLookupForwardedMetadataType(ref emittedName); } /// <summary> /// Look up the given metadata type, if it is forwarded. /// </summary> internal NamedTypeSymbol TryLookupForwardedMetadataType(ref MetadataTypeName emittedName) { return TryLookupForwardedMetadataTypeWithCycleDetection(ref emittedName, visitedAssemblies: null); } /// <summary> /// Look up the given metadata type, if it is forwarded. /// </summary> internal virtual NamedTypeSymbol TryLookupForwardedMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList<AssemblySymbol> visitedAssemblies) { return null; } internal ErrorTypeSymbol CreateCycleInTypeForwarderErrorTypeSymbol(ref MetadataTypeName emittedName) { DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_CycleInTypeForwarder, emittedName.FullName, this.Name); return new MissingMetadataTypeSymbol.TopLevel(this.Modules[0], ref emittedName, diagnosticInfo); } internal ErrorTypeSymbol CreateMultipleForwardingErrorTypeSymbol(ref MetadataTypeName emittedName, ModuleSymbol forwardingModule, AssemblySymbol destination1, AssemblySymbol destination2) { var diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, forwardingModule, this, emittedName.FullName, destination1, destination2); return new MissingMetadataTypeSymbol.TopLevel(forwardingModule, ref emittedName, diagnosticInfo); } internal abstract IEnumerable<NamedTypeSymbol> GetAllTopLevelForwardedTypes(); /// <summary> /// Lookup declaration for predefined CorLib type in this Assembly. /// </summary> /// <returns>The symbol for the pre-defined type or an error type if the type is not defined in the core library.</returns> internal abstract NamedTypeSymbol GetDeclaredSpecialType(SpecialType type); /// <summary> /// Register declaration of predefined CorLib type in this Assembly. /// </summary> /// <param name="corType"></param> internal virtual void RegisterDeclaredSpecialType(NamedTypeSymbol corType) { throw ExceptionUtilities.Unreachable; } /// <summary> /// Continue looking for declaration of predefined CorLib type in this Assembly /// while symbols for new type declarations are constructed. /// </summary> internal virtual bool KeepLookingForDeclaredSpecialTypes { get { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Return the native integer type corresponding to the underlying type. /// </summary> internal virtual NamedTypeSymbol GetNativeIntegerType(NamedTypeSymbol underlyingType) { throw ExceptionUtilities.Unreachable; } /// <summary> /// Figure out if the target runtime supports default interface implementation. /// </summary> internal bool RuntimeSupportsDefaultInterfaceImplementation { get => RuntimeSupportsFeature(SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces); } /// <summary> /// Figure out if the target runtime supports static abstract members in interfaces. /// </summary> internal bool RuntimeSupportsStaticAbstractMembersInInterfaces { get => RuntimeSupportsFeature(SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__VirtualStaticsInInterfaces); } private bool RuntimeSupportsFeature(SpecialMember feature) { Debug.Assert((SpecialType)SpecialMembers.GetDescriptor(feature).DeclaringTypeId == SpecialType.System_Runtime_CompilerServices_RuntimeFeature); return GetSpecialType(SpecialType.System_Runtime_CompilerServices_RuntimeFeature) is { TypeKind: TypeKind.Class, IsStatic: true } && GetSpecialTypeMember(feature) is object; } internal bool RuntimeSupportsUnmanagedSignatureCallingConvention => RuntimeSupportsFeature(SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention); /// <summary> /// True if the target runtime support covariant returns of methods declared in classes. /// </summary> internal bool RuntimeSupportsCovariantReturnsOfClasses { get { // check for the runtime feature indicator and the required attribute. return RuntimeSupportsFeature(SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses) && GetSpecialType(SpecialType.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute) is { TypeKind: TypeKind.Class }; } } /// <summary> /// Return an array of assemblies involved in canonical type resolution of /// NoPia local types defined within this assembly. In other words, all /// references used by previous compilation referencing this assembly. /// </summary> /// <returns></returns> internal abstract ImmutableArray<AssemblySymbol> GetNoPiaResolutionAssemblies(); internal abstract void SetNoPiaResolutionAssemblies(ImmutableArray<AssemblySymbol> assemblies); /// <summary> /// Return an array of assemblies referenced by this assembly, which are linked (/l-ed) by /// each compilation that is using this AssemblySymbol as a reference. /// If this AssemblySymbol is linked too, it will be in this array too. /// </summary> internal abstract ImmutableArray<AssemblySymbol> GetLinkedReferencedAssemblies(); internal abstract void SetLinkedReferencedAssemblies(ImmutableArray<AssemblySymbol> assemblies); internal abstract IEnumerable<ImmutableArray<byte>> GetInternalsVisibleToPublicKeys(string simpleName); internal abstract bool AreInternalsVisibleToThisAssembly(AssemblySymbol other); /// <summary> /// Assembly is /l-ed by compilation that is using it as a reference. /// </summary> internal abstract bool IsLinked { get; } /// <summary> /// Returns true and a string from the first GuidAttribute on the assembly, /// the string might be null or an invalid guid representation. False, /// if there is no GuidAttribute with string argument. /// </summary> internal virtual bool GetGuidString(out string guidString) { return GetGuidStringDefaultImplementation(out guidString); } /// <summary> /// Gets the set of type identifiers from this assembly. /// </summary> /// <remarks> /// These names are the simple identifiers for the type, and do not include namespaces, /// outer type names, or type parameters. /// /// This functionality can be used for features that want to quickly know if a name could be /// a type for performance reasons. For example, classification does not want to incur an /// expensive binding call cost if it knows that there is no type with the name that they /// are looking at. /// </remarks> public abstract ICollection<string> TypeNames { get; } /// <summary> /// Gets the set of namespace names from this assembly. /// </summary> public abstract ICollection<string> NamespaceNames { get; } /// <summary> /// Returns true if this assembly might contain extension methods. If this property /// returns false, there are no extension methods in this assembly. /// </summary> /// <remarks> /// This property allows the search for extension methods to be narrowed quickly. /// </remarks> public abstract bool MightContainExtensionMethods { get; } /// <summary> /// Gets the symbol for the pre-defined type from core library associated with this assembly. /// </summary> /// <returns>The symbol for the pre-defined type or an error type if the type is not defined in the core library.</returns> internal NamedTypeSymbol GetSpecialType(SpecialType type) { return CorLibrary.GetDeclaredSpecialType(type); } internal static TypeSymbol DynamicType { get { return DynamicTypeSymbol.Instance; } } /// <summary> /// The NamedTypeSymbol for the .NET System.Object type, which could have a TypeKind of /// Error if there was no COR Library in a compilation using the assembly. /// </summary> internal NamedTypeSymbol ObjectType { get { return GetSpecialType(SpecialType.System_Object); } } /// <summary> /// Get symbol for predefined type from Cor Library used by this assembly. /// </summary> /// <param name="type"></param> /// <returns></returns> internal NamedTypeSymbol GetPrimitiveType(Microsoft.Cci.PrimitiveTypeCode type) { return GetSpecialType(SpecialTypes.GetTypeFromMetadataName(type)); } /// <summary> /// Lookup a type within the assembly using the canonical CLR metadata name of the type. /// </summary> /// <param name="fullyQualifiedMetadataName">Type name.</param> /// <returns>Symbol for the type or null if type cannot be found or is ambiguous. </returns> public NamedTypeSymbol GetTypeByMetadataName(string fullyQualifiedMetadataName) { if (fullyQualifiedMetadataName == null) { throw new ArgumentNullException(nameof(fullyQualifiedMetadataName)); } return this.GetTypeByMetadataName(fullyQualifiedMetadataName, includeReferences: false, isWellKnownType: false, conflicts: out var _); } /// <summary> /// Lookup a type within the assembly using its canonical CLR metadata name. /// </summary> /// <param name="metadataName"></param> /// <param name="includeReferences"> /// If search within assembly fails, lookup in assemblies referenced by the primary module. /// For source assembly, this is equivalent to all assembly references given to compilation. /// </param> /// <param name="isWellKnownType"> /// Extra restrictions apply when searching for a well-known type. In particular, the type must be public. /// </param> /// <param name="useCLSCompliantNameArityEncoding"> /// While resolving the name, consider only types following CLS-compliant generic type names and arity encoding (ECMA-335, section 10.7.2). /// I.e. arity is inferred from the name and matching type must have the same emitted name and arity. /// </param> /// <param name="warnings"> /// A diagnostic bag to receive warnings if we should allow multiple definitions and pick one. /// </param> /// <param name="ignoreCorLibraryDuplicatedTypes"> /// In case duplicate types are found, ignore the one from corlib. This is useful for any kind of compilation at runtime /// (EE/scripting/Powershell) using a type that is being migrated to corlib. /// </param> /// <param name="conflicts"> /// In cases a type could not be found because of ambiguity, we return two of the candidates that caused the ambiguity. /// </param> /// <returns>Null if the type can't be found.</returns> internal NamedTypeSymbol GetTypeByMetadataName( string metadataName, bool includeReferences, bool isWellKnownType, out (AssemblySymbol, AssemblySymbol) conflicts, bool useCLSCompliantNameArityEncoding = false, DiagnosticBag warnings = null, bool ignoreCorLibraryDuplicatedTypes = false) { NamedTypeSymbol type; MetadataTypeName mdName; if (metadataName.IndexOf('+') >= 0) { var parts = metadataName.Split(s_nestedTypeNameSeparators); Debug.Assert(parts.Length > 0); mdName = MetadataTypeName.FromFullName(parts[0], useCLSCompliantNameArityEncoding); type = GetTopLevelTypeByMetadataName(ref mdName, assemblyOpt: null, includeReferences: includeReferences, isWellKnownType: isWellKnownType, conflicts: out conflicts, warnings: warnings, ignoreCorLibraryDuplicatedTypes: ignoreCorLibraryDuplicatedTypes); for (int i = 1; (object)type != null && !type.IsErrorType() && i < parts.Length; i++) { mdName = MetadataTypeName.FromTypeName(parts[i]); NamedTypeSymbol temp = type.LookupMetadataType(ref mdName); type = (!isWellKnownType || IsValidWellKnownType(temp)) ? temp : null; } } else { mdName = MetadataTypeName.FromFullName(metadataName, useCLSCompliantNameArityEncoding); type = GetTopLevelTypeByMetadataName(ref mdName, assemblyOpt: null, includeReferences: includeReferences, isWellKnownType: isWellKnownType, conflicts: out conflicts, warnings: warnings, ignoreCorLibraryDuplicatedTypes: ignoreCorLibraryDuplicatedTypes); } return ((object)type == null || type.IsErrorType()) ? null : type; } private static readonly char[] s_nestedTypeNameSeparators = new char[] { '+' }; /// <summary> /// Resolves <see cref="System.Type"/> to a <see cref="TypeSymbol"/> available in this assembly /// its referenced assemblies. /// </summary> /// <param name="type">The type to resolve.</param> /// <param name="includeReferences">Use referenced assemblies for resolution.</param> /// <returns>The resolved symbol if successful or null on failure.</returns> internal TypeSymbol GetTypeByReflectionType(Type type, bool includeReferences) { System.Reflection.TypeInfo typeInfo = type.GetTypeInfo(); Debug.Assert(!typeInfo.IsByRef); // not supported (we don't accept open types as submission results nor host types): Debug.Assert(!typeInfo.ContainsGenericParameters); if (typeInfo.IsArray) { TypeSymbol symbol = GetTypeByReflectionType(typeInfo.GetElementType(), includeReferences); if ((object)symbol == null) { return null; } int rank = typeInfo.GetArrayRank(); return ArrayTypeSymbol.CreateCSharpArray(this, TypeWithAnnotations.Create(symbol), rank); } else if (typeInfo.IsPointer) { TypeSymbol symbol = GetTypeByReflectionType(typeInfo.GetElementType(), includeReferences); if ((object)symbol == null) { return null; } return new PointerTypeSymbol(TypeWithAnnotations.Create(symbol)); } else if (typeInfo.DeclaringType != null) { Debug.Assert(!typeInfo.IsArray); // consolidated generic arguments (includes arguments of all declaring types): Type[] genericArguments = typeInfo.GenericTypeArguments; int typeArgumentIndex = 0; var currentTypeInfo = typeInfo.IsGenericType ? typeInfo.GetGenericTypeDefinition().GetTypeInfo() : typeInfo; var nestedTypes = ArrayBuilder<System.Reflection.TypeInfo>.GetInstance(); while (true) { Debug.Assert(currentTypeInfo.IsGenericTypeDefinition || !currentTypeInfo.IsGenericType); nestedTypes.Add(currentTypeInfo); if (currentTypeInfo.DeclaringType == null) { break; } currentTypeInfo = currentTypeInfo.DeclaringType.GetTypeInfo(); } int i = nestedTypes.Count - 1; var symbol = (NamedTypeSymbol)GetTypeByReflectionType(nestedTypes[i].AsType(), includeReferences); if ((object)symbol == null) { return null; } while (--i >= 0) { int forcedArity = nestedTypes[i].GenericTypeParameters.Length - nestedTypes[i + 1].GenericTypeParameters.Length; MetadataTypeName mdName = MetadataTypeName.FromTypeName(nestedTypes[i].Name, forcedArity: forcedArity); symbol = symbol.LookupMetadataType(ref mdName); if ((object)symbol == null || symbol.IsErrorType()) { return null; } symbol = ApplyGenericArguments(symbol, genericArguments, ref typeArgumentIndex, includeReferences); if ((object)symbol == null) { return null; } } nestedTypes.Free(); Debug.Assert(typeArgumentIndex == genericArguments.Length); return symbol; } else { AssemblyIdentity assemblyId = AssemblyIdentity.FromAssemblyDefinition(typeInfo.Assembly); MetadataTypeName mdName = MetadataTypeName.FromNamespaceAndTypeName( typeInfo.Namespace ?? string.Empty, typeInfo.Name, forcedArity: typeInfo.GenericTypeArguments.Length); NamedTypeSymbol symbol = GetTopLevelTypeByMetadataName(ref mdName, assemblyId, includeReferences, isWellKnownType: false, conflicts: out var _); if ((object)symbol == null || symbol.IsErrorType()) { return null; } int typeArgumentIndex = 0; Type[] genericArguments = typeInfo.GenericTypeArguments; symbol = ApplyGenericArguments(symbol, genericArguments, ref typeArgumentIndex, includeReferences); Debug.Assert(typeArgumentIndex == genericArguments.Length); return symbol; } } private NamedTypeSymbol ApplyGenericArguments(NamedTypeSymbol symbol, Type[] typeArguments, ref int currentTypeArgument, bool includeReferences) { int remainingTypeArguments = typeArguments.Length - currentTypeArgument; // in case we are specializing a nested generic definition we might have more arguments than the current symbol: Debug.Assert(remainingTypeArguments >= symbol.Arity); if (remainingTypeArguments == 0) { return symbol; } var length = symbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; var typeArgumentSymbols = ArrayBuilder<TypeWithAnnotations>.GetInstance(length); for (int i = 0; i < length; i++) { var argSymbol = GetTypeByReflectionType(typeArguments[currentTypeArgument++], includeReferences); if ((object)argSymbol == null) { return null; } typeArgumentSymbols.Add(TypeWithAnnotations.Create(argSymbol)); } return symbol.ConstructIfGeneric(typeArgumentSymbols.ToImmutableAndFree()); } internal NamedTypeSymbol GetTopLevelTypeByMetadataName( ref MetadataTypeName metadataName, AssemblyIdentity assemblyOpt, bool includeReferences, bool isWellKnownType, out (AssemblySymbol, AssemblySymbol) conflicts, DiagnosticBag warnings = null, // this is set to collect ambiguity warning for well-known types before C# 7 bool ignoreCorLibraryDuplicatedTypes = false) { // Type from this assembly always wins. // After that we look in references, which may yield ambiguities. If `ignoreCorLibraryDuplicatedTypes` is set, // corlib does not contribute to ambiguities (corlib loses over other references). // For well-known types before C# 7, ambiguities are reported as a warning and the first candidate wins. // For other types, when `ignoreCorLibraryDuplicatedTypes` isn't set, finding a candidate in corlib resolves // ambiguities (corlib wins over other references). Debug.Assert(warnings is null || isWellKnownType); conflicts = default; NamedTypeSymbol result; // First try this assembly result = GetTopLevelTypeByMetadataName(this, ref metadataName, assemblyOpt); if (isWellKnownType && !IsValidWellKnownType(result)) { result = null; } // ignore any types of the same name that might be in referenced assemblies (prefer the current assembly): if ((object)result != null || !includeReferences) { return result; } // Then try corlib, when finding a result there means we've found the final result bool isWellKnownTypeBeforeCSharp7 = isWellKnownType && warnings is not null; bool skipCorLibrary = false; if (CorLibrary != (object)this && !CorLibrary.IsMissing && !isWellKnownTypeBeforeCSharp7 && !ignoreCorLibraryDuplicatedTypes) { NamedTypeSymbol corLibCandidate = GetTopLevelTypeByMetadataName(CorLibrary, ref metadataName, assemblyOpt); skipCorLibrary = true; if (isValidCandidate(corLibCandidate, isWellKnownType)) { return corLibCandidate; } } Debug.Assert(this is SourceAssemblySymbol, "Never include references for a non-source assembly, because they don't know about aliases."); var assemblies = ArrayBuilder<AssemblySymbol>.GetInstance(); // ignore reference aliases if searching for a type from a specific assembly: if (assemblyOpt != null) { assemblies.AddRange(DeclaringCompilation.GetBoundReferenceManager().ReferencedAssemblies); } else { DeclaringCompilation.GetUnaliasedReferencedAssemblies(assemblies); } // Lookup in references foreach (var assembly in assemblies) { Debug.Assert(!(this is SourceAssemblySymbol && assembly.IsMissing)); // Non-source assemblies can have missing references if (skipCorLibrary && assembly == (object)CorLibrary) { continue; } NamedTypeSymbol candidate = GetTopLevelTypeByMetadataName(assembly, ref metadataName, assemblyOpt); if (!isValidCandidate(candidate, isWellKnownType)) { continue; } Debug.Assert(!TypeSymbol.Equals(candidate, result, TypeCompareKind.ConsiderEverything)); if ((object)result != null) { // duplicate if (ignoreCorLibraryDuplicatedTypes) { if (IsInCorLib(candidate)) { // ignore candidate continue; } if (IsInCorLib(result)) { // drop previous result result = candidate; continue; } } if (warnings is null) { conflicts = (result.ContainingAssembly, candidate.ContainingAssembly); result = null; } else { // The predefined type '{0}' is defined in multiple assemblies in the global alias; using definition from '{1}' warnings.Add(ErrorCode.WRN_MultiplePredefTypes, NoLocation.Singleton, result, result.ContainingAssembly); } break; } result = candidate; } assemblies.Free(); return result; bool isValidCandidate(NamedTypeSymbol candidate, bool isWellKnownType) { return candidate is not null && (!isWellKnownType || IsValidWellKnownType(candidate)) && !candidate.IsHiddenByCodeAnalysisEmbeddedAttribute(); } } private bool IsInCorLib(NamedTypeSymbol type) { return (object)type.ContainingAssembly == CorLibrary; } private bool IsValidWellKnownType(NamedTypeSymbol result) { if ((object)result == null || result.TypeKind == TypeKind.Error) { return false; } Debug.Assert((object)result.ContainingType == null || IsValidWellKnownType(result.ContainingType), "Checking the containing type is the caller's responsibility."); return result.DeclaredAccessibility == Accessibility.Public || IsSymbolAccessible(result, this); } private static NamedTypeSymbol GetTopLevelTypeByMetadataName(AssemblySymbol assembly, ref MetadataTypeName metadataName, AssemblyIdentity assemblyOpt) { var result = assembly.LookupTopLevelMetadataType(ref metadataName, digThroughForwardedTypes: false); if (!IsAcceptableMatchForGetTypeByMetadataName(result)) { return null; } if (assemblyOpt != null && !assemblyOpt.Equals(assembly.Identity)) { return null; } return result; } private static bool IsAcceptableMatchForGetTypeByMetadataName(NamedTypeSymbol candidate) { return candidate.Kind != SymbolKind.ErrorType || !(candidate is MissingMetadataTypeSymbol); } /// <summary> /// Lookup member declaration in predefined CorLib type in this Assembly. Only valid if this /// assembly is the Cor Library /// </summary> internal virtual Symbol GetDeclaredSpecialTypeMember(SpecialMember member) { return null; } /// <summary> /// Lookup member declaration in predefined CorLib type used by this Assembly. /// </summary> internal virtual Symbol GetSpecialTypeMember(SpecialMember member) { return CorLibrary.GetDeclaredSpecialTypeMember(member); } internal abstract ImmutableArray<byte> PublicKey { get; } /// <summary> /// If this symbol represents a metadata assembly returns the underlying <see cref="AssemblyMetadata"/>. /// /// Otherwise, this returns <see langword="null"/>. /// </summary> public abstract AssemblyMetadata GetMetadata(); protected override ISymbol CreateISymbol() { return new PublicModel.NonSourceAssemblySymbol(this); } } }
1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests : WellKnownAttributesTestBase { static readonly string[] s_autoPropAttributes = new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }; static readonly string[] s_backingFieldAttributes = new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Diagnostics.DebuggerBrowsableAttribute(System.Diagnostics.DebuggerBrowsableState.Never)" }; #region Function Tests [Fact, WorkItem(26464, "https://github.com/dotnet/roslyn/issues/26464")] public void TestNullInAssemblyVersionAttribute() { var source = @" [assembly: System.Reflection.AssemblyVersionAttribute(null)] class Program { }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithDeterministic(true)); comp.VerifyDiagnostics( // (2,55): error CS7034: The specified version string does not conform to the required format - major[.minor[.build[.revision]]] // [assembly: System.Reflection.AssemblyVersionAttribute(null)] Diagnostic(ErrorCode.ERR_InvalidVersionFormat, "null").WithLocation(2, 55) ); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void TestQuickAttributeChecker() { var predefined = QuickAttributeChecker.Predefined; var typeForwardedTo = SyntaxFactory.Attribute(SyntaxFactory.ParseName("TypeForwardedTo")); var typeIdentifier = SyntaxFactory.Attribute(SyntaxFactory.ParseName("TypeIdentifier")); Assert.True(predefined.IsPossibleMatch(typeForwardedTo, QuickAttributes.TypeForwardedTo)); Assert.False(predefined.IsPossibleMatch(typeForwardedTo, QuickAttributes.TypeIdentifier)); Assert.False(predefined.IsPossibleMatch(typeForwardedTo, QuickAttributes.None)); Assert.False(predefined.IsPossibleMatch(typeIdentifier, QuickAttributes.TypeForwardedTo)); Assert.True(predefined.IsPossibleMatch(typeIdentifier, QuickAttributes.TypeIdentifier)); Assert.False(predefined.IsPossibleMatch(typeIdentifier, QuickAttributes.None)); var alias1 = SyntaxFactory.Attribute(SyntaxFactory.ParseName("alias1")); var checker1 = WithAliases(predefined, "using alias1 = TypeForwardedToAttribute;"); Assert.True(checker1.IsPossibleMatch(alias1, QuickAttributes.TypeForwardedTo)); Assert.False(checker1.IsPossibleMatch(alias1, QuickAttributes.TypeIdentifier)); var checker1a = WithAliases(checker1, "using alias1 = TypeIdentifierAttribute;"); Assert.True(checker1a.IsPossibleMatch(alias1, QuickAttributes.TypeForwardedTo)); Assert.True(checker1a.IsPossibleMatch(alias1, QuickAttributes.TypeIdentifier)); var checker1b = WithAliases(checker1, "using alias2 = TypeIdentifierAttribute;"); var alias2 = SyntaxFactory.Attribute(SyntaxFactory.ParseName("alias2")); Assert.True(checker1b.IsPossibleMatch(alias1, QuickAttributes.TypeForwardedTo)); Assert.False(checker1b.IsPossibleMatch(alias1, QuickAttributes.TypeIdentifier)); Assert.False(checker1b.IsPossibleMatch(alias2, QuickAttributes.TypeForwardedTo)); Assert.True(checker1b.IsPossibleMatch(alias2, QuickAttributes.TypeIdentifier)); var checker3 = WithAliases(predefined, "using alias3 = TypeForwardedToAttribute; using alias3 = TypeIdentifierAttribute;"); var alias3 = SyntaxFactory.Attribute(SyntaxFactory.ParseName("alias3")); Assert.True(checker3.IsPossibleMatch(alias3, QuickAttributes.TypeForwardedTo)); Assert.True(checker3.IsPossibleMatch(alias3, QuickAttributes.TypeIdentifier)); QuickAttributeChecker WithAliases(QuickAttributeChecker checker, string aliases) { var nodes = Parse(aliases).GetRoot().DescendantNodes().OfType<UsingDirectiveSyntax>(); var list = new SyntaxList<UsingDirectiveSyntax>().AddRange(nodes); return checker.AddAliasesIfAny(list); } } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithMissingType_WithIrrelevantType() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' (during overload resolution of attribute constructors) albeit irrelevant // but C won't exist "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithDiagnostic() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(1)] "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics( // (3,60): error CS1503: Argument 1: cannot convert from 'int' to 'System.Type' // [assembly: System.Runtime.CompilerServices.TypeForwardedTo(1)] Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "System.Type").WithLocation(3, 60) ); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics( // (3,60): error CS1503: Argument 1: cannot convert from 'int' to 'System.Type' // [assembly: System.Runtime.CompilerServices.TypeForwardedTo(1)] Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "System.Type").WithLocation(3, 60) ); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithMissingType_WithRelevantType() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' // but C won't exist "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics( // (2,12): error CS7068: Reference to type 'C' claims it is defined in this assembly, but it is not defined in source or any added modules // [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' Diagnostic(ErrorCode.ERR_MissingTypeInSource, "RefersToLib").WithArguments("C").WithLocation(2, 12) ); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics( // (2,12): error CS7068: Reference to type 'C' claims it is defined in this assembly, but it is not defined in source or any added modules // [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' Diagnostic(ErrorCode.ERR_MissingTypeInSource, "RefersToLib").WithArguments("C").WithLocation(2, 12) ); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithStaticUsing() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" using static RefersToLibAttribute; // Binding this will cause a lookup for 'C' in 'lib'. // Such lookup requires binding 'TypeForwardedTo' attributes (and aliases), but we should not bind other usings, to avoid an infinite recursion. [assembly: System.Reflection.AssemblyTitleAttribute(""title"")] public class Ignore { public void UseStaticUsing() { Method(); } } "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } public static void Method() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithTypeForward_WithIrrelevantType() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' (during overload resolution of attribute constructors) albeit irrelevant [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] // but C is forwarded "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithTypeForward_WithRelevantType() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] // but C is forwarded "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); var newLibComp3 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp3.SourceAssembly.GetAttributes(); newLibComp3.VerifyDiagnostics(); } /// <summary> /// Looking up C explicitly after calling GetAttributes will cause <see cref="SourceAssemblySymbol.GetForwardedTypes"/> to use the cached attributes, rather that do partial binding /// </summary> [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithCheckAttributes() { var cDefinition_cs = @"public class C { }"; var derivedDefinition_cs = @"public class Derived : C { }"; var typeForward_cs = @" [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] "; var origLibComp = CreateCompilation(cDefinition_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithDerivedAndReferenceToLib = CreateCompilation(typeForward_cs + derivedDefinition_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithDerivedAndReferenceToLib.VerifyDiagnostics(); var compWithC = CreateCompilation(cDefinition_cs, assemblyName: "new"); compWithC.VerifyDiagnostics(); var newLibComp = CreateCompilation(typeForward_cs, references: new[] { compWithDerivedAndReferenceToLib.EmitToImageReference(), compWithC.EmitToImageReference() }, assemblyName: "lib"); var attribute = newLibComp.SourceAssembly.GetAttributes().Single(); // GetAttributes binds all attributes Assert.Equal("System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(C))", attribute.ToString()); var derived = (NamedTypeSymbol)newLibComp.GetMember("Derived"); var c = derived.BaseType(); // get C Assert.Equal("C", c.ToTestDisplayString()); Assert.False(c.IsErrorType()); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithTypeForward_WithRelevantType_WithAlias() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" using alias1 = System.Runtime.CompilerServices.TypeForwardedToAttribute; [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' [assembly: alias1(typeof(C))] // but C is forwarded via alias "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithExistingType_WithIrrelevantType() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' (during overload resolution of attribute constructors) albeit irrelevant public class C { } // and C exists here "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithExistingType_WithRelevantType() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' public class C : System.Attribute { } // and C exists here "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] public void TestAssemblyAttributes() { var source = CreateCompilation(@" using System; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""Roslyn.Compilers.UnitTests"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp.UnitTests"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp.Test.Utilities"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.VisualBasic"")] class C { public static void Main() {} } "); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { Symbol assembly = m.ContainingSymbol; var attrs = assembly.GetAttributes(); Assert.Equal(5, attrs.Length); attrs[0].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.UnitTests"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.UnitTests"")", attrs[0].ToString()); attrs[1].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp"")", attrs[1].ToString()); attrs[2].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp.UnitTests"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp.UnitTests"")", attrs[2].ToString()); attrs[3].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp.Test.Utilities"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp.Test.Utilities"")", attrs[3].ToString()); attrs[4].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.VisualBasic"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.VisualBasic"")", attrs[4].ToString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnStringParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { } } [Mark(b: new string[] { ""Hello"", ""World"" }, a: true)] [Mark(b: ""Hello"", true)] static class Program { }", parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (11,2): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Mark(b: new string[] { "Hello", "World" }, a: true)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"Mark(b: new string[] { ""Hello"", ""World"" }, a: true)").WithLocation(11, 2), // (12,7): error CS8323: Named argument 'b' is used out-of-position but is followed by an unnamed argument // [Mark(b: "Hello", true)] Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "b").WithArguments("b").WithLocation(12, 7) ); } [Fact] public void TestNullAsParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; class MarkAttribute : Attribute { public MarkAttribute(params object[] b) { } } [Mark(null)] static class Program { }"); comp.VerifyDiagnostics( ); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnOrderedObjectParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(a: true, b: new object[] { ""Hello"", ""World"" })] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""B.Length={attr.B.Length}, B[0]={attr.B[0]}, B[1]={attr.B[1]}""); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"B.Length=2, B[0]=Hello, B[1]=World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 0, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(b: new object[] { ""Hello"", ""World"" }, a: true)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""B.Length={attr.B.Length}, B[0]={attr.B[0]}, B[1]={attr.B[1]}""); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"B.Length=2, B[0]=Hello, B[1]=World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument2() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { A = a; B = b; } public bool A { get; } public object[] B { get; } } [Mark(b: ""Hello"", a: true)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""A={attr.A}, B.Length={attr.B.Length}, B[0]={attr.B[0]}""); } }", options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"A=True, B.Length=1, B[0]=Hello"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument3() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(true, new object[] { ""Hello"" }, new object[] { ""World"" })] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); var worldArray = (object[])attr.B[1]; Console.Write(worldArray[0]); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 0, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument4() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(a: true, new object[] { ""Hello"" }, new object[] { ""World"" })] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); var worldArray = (object[])attr.B[1]; Console.Write(worldArray[0]); } }", options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 0, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument5() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(b: null, a: true)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write(attr.B == null); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"True"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnNonParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(int a, int b) { A = a; B = b; } public int A { get; } public int B { get; } } [Mark(b: 42, a: 1)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""A={attr.A}, B={attr.B}""); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "A=1, B=42"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, 0 }, attributeData.ConstructorArgumentsSourceIndices); } [WorkItem(984896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984896")] [Fact] public void TestAssemblyAttributesErr() { string code = @" using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using M = System.Math; namespace My { using A.B; // TODO: <Insert justification for suppressing TestId> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(""Test"",""TestId"",Justification=""<Pending>"")] public unsafe partial class A : C, I { } } "; var source = CreateCompilationWithMscorlib40AndSystemCore(code); // the following should not crash source.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, source.SyntaxTrees[0], filterSpanWithinTree: null, includeEarlierStages: true); } [Fact, WorkItem(545326, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545326")] public void TestAssemblyAttributes_Bug13670() { var source = @" using System; [assembly: A(Derived.Str)] public class A: Attribute { public A(string x){} public static void Main() {} } public class Derived: Base { internal const string Str = ""temp""; public override int Goo { get { return 1; } } } public class Base { public virtual int Goo { get { return 0; } } } "; CompileAndVerify(source); } [Fact] public void TestAssemblyAttributesReflection() { var compilation = CreateCompilation(@" using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // These are not pseudo attributes, but encoded as bits in metadata [assembly: AssemblyAlgorithmId(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)] [assembly: AssemblyCultureAttribute("""")] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyFlags(AssemblyNameFlags.Retargetable)] [assembly: AssemblyKeyFile(""MyKey.snk"")] [assembly: AssemblyKeyName(""Key Name"")] [assembly: AssemblyVersion(""1.2.*"")] [assembly: AssemblyFileVersionAttribute(""4.3.2.100"")] class C { public static void Main() {} } "); var attrs = compilation.Assembly.GetAttributes(); Assert.Equal(8, attrs.Length); foreach (var a in attrs) { switch (a.AttributeClass.Name) { case "AssemblyAlgorithmIdAttribute": a.VerifyValue(0, TypedConstantKind.Enum, (int)System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5); Assert.Equal(@"System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)", a.ToString()); break; case "AssemblyCultureAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, ""); Assert.Equal(@"System.Reflection.AssemblyCultureAttribute("""")", a.ToString()); break; case "AssemblyDelaySignAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, true); Assert.Equal(@"System.Reflection.AssemblyDelaySignAttribute(true)", a.ToString()); break; case "AssemblyFlagsAttribute": a.VerifyValue(0, TypedConstantKind.Enum, (int)AssemblyNameFlags.Retargetable); Assert.Equal(@"System.Reflection.AssemblyFlagsAttribute(System.Reflection.AssemblyNameFlags.Retargetable)", a.ToString()); break; case "AssemblyKeyFileAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "MyKey.snk"); Assert.Equal(@"System.Reflection.AssemblyKeyFileAttribute(""MyKey.snk"")", a.ToString()); break; case "AssemblyKeyNameAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "Key Name"); Assert.Equal(@"System.Reflection.AssemblyKeyNameAttribute(""Key Name"")", a.ToString()); break; case "AssemblyVersionAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "1.2.*"); Assert.Equal(@"System.Reflection.AssemblyVersionAttribute(""1.2.*"")", a.ToString()); break; case "AssemblyFileVersionAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "4.3.2.100"); Assert.Equal(@"System.Reflection.AssemblyFileVersionAttribute(""4.3.2.100"")", a.ToString()); break; default: Assert.Equal("Unexpected Attr", a.AttributeClass.Name); break; } } } // Verify that resolving an attribute defined within a class on a class does not cause infinite recursion [Fact] public void TestAttributesOnClassDefinedInClass() { var compilation = CreateCompilation(@" using System; using System.Runtime.CompilerServices; [A.X()] public class A { [AttributeUsage(AttributeTargets.All, allowMultiple = true)] public class XAttribute : Attribute { } } class C { public static void Main() {} } "); var attrs = compilation.SourceModule.GlobalNamespace.GetMember("A").GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("A.XAttribute", attrs.First().AttributeClass.ToDisplayString()); } [Fact] public void TestAttributesOnClassWithConstantDefinedInClass() { var compilation = CreateCompilation(@" using System; [Attr(Goo.p)] class Goo { private const object p = null; } internal class AttrAttribute : Attribute { public AttrAttribute(object p) { } } class C { public static void Main() { } } "); var attrs = compilation.SourceModule.GlobalNamespace.GetMember("Goo").GetAttributes(); Assert.Equal(1, attrs.Length); attrs.First().VerifyValue<object>(0, TypedConstantKind.Primitive, null); } [Fact] public void TestAttributeEmit() { var compilation = CreateCompilation(@" using System; public enum e1 { a, b, c } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class XAttribute : Attribute { public XAttribute(int i) { } public XAttribute(int i, string s) { } public XAttribute(int i, string s, e1 e) { } public XAttribute(object[] o) { } public XAttribute(int[] i) { } public XAttribute(int[] i, string[] s) { } public XAttribute(int[] i, string[] s, e1[] e) { } public int pi { get; set; } public string ps { get; set; } public e1 pe { get; set; } } [X(1, ""hello"", e1.a)] [X(new int[] { 1 }, new string[] { ""hello"" }, new e1[] { e1.a, e1.b, e1.c })] [X(new object[] { 1, ""hello"", e1.a })] class C { public static void Main() {} } "); var verifier = CompileAndVerify(compilation); verifier.VerifyIL("XAttribute..ctor(int)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""System.Attribute..ctor()"" IL_0006: ret }"); } [Fact] public void TestAttributesOnClassProperty() { var compilation = CreateCompilation(@" using System; public class A { [CLSCompliant(true)] public string Prop { get { return null; } } } class C { public static void Main() {} } "); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var type = (NamedTypeSymbol)m.GlobalNamespace.GetMember("A"); var prop = type.GetMember("Prop"); var attrs = prop.GetAttributes(); Assert.Equal(1, attrs.Length); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, true); Assert.Equal("System.CLSCompliantAttribute", attrs.First().AttributeClass.ToDisplayString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(688268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688268")] [Fact] public void Bug688268() { var compilation = CreateCompilation(@" using System; using System.Runtime.InteropServices; using System.Security; public interface I { void _VtblGap1_30(); void _VtblGaP1_30(); } "); System.Action<ModuleSymbol> metadataValidator = delegate (ModuleSymbol module) { var metadata = ((PEModuleSymbol)module).Module; var typeI = (PENamedTypeSymbol)module.GlobalNamespace.GetTypeMembers("I").Single(); var methods = metadata.GetMethodsOfTypeOrThrow(typeI.Handle); Assert.Equal(2, methods.Count); var e = methods.GetEnumerator(); e.MoveNext(); var flags = metadata.GetMethodDefFlagsOrThrow(e.Current); Assert.Equal( MethodAttributes.PrivateScope | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.VtableLayoutMask | MethodAttributes.Abstract | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, flags); e.MoveNext(); flags = metadata.GetMethodDefFlagsOrThrow(e.Current); Assert.Equal( MethodAttributes.PrivateScope | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.VtableLayoutMask | MethodAttributes.Abstract, flags); }; CompileAndVerify( compilation, sourceSymbolValidator: null, symbolValidator: metadataValidator); } [Fact] public void TestAttributesOnPropertyAndGetSet() { string source = @" using System; [AObject(typeof(object), O = A.obj)] public class A { internal const object obj = null; public string RProp { [AObject(new object[] { typeof(string) })] get { return null; } } [AObject(new object[] { 1, ""two"", typeof(string), 3.1415926 })] public object WProp { [AObject(new object[] { new object[] { typeof(string) } })] set { } } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.MDTestAttributeDefLib.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var type = (NamedTypeSymbol)m.GlobalNamespace.GetMember("A"); var attrs = type.GetAttributes(); Assert.Equal("AObjectAttribute(typeof(object), O = null)", attrs.First().ToString()); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeof(object)); attrs.First().VerifyNamedArgumentValue<object>(0, "O", TypedConstantKind.Primitive, null); var prop = type.GetMember<PropertySymbol>("RProp"); attrs = prop.GetMethod.GetAttributes(); Assert.Equal("AObjectAttribute({typeof(string)})", attrs.First().ToString()); attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { typeof(string) }); prop = type.GetMember<PropertySymbol>("WProp"); attrs = prop.GetAttributes(); Assert.Equal(@"AObjectAttribute({1, ""two"", typeof(string), 3.1415926})", attrs.First().ToString()); attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { 1, "two", typeof(string), 3.1415926 }); attrs = prop.SetMethod.GetAttributes(); Assert.Equal(@"AObjectAttribute({{typeof(string)}})", attrs.First().ToString()); attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { new object[] { typeof(string) } }); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [Fact] public void TestFieldAttributeOnPropertyInCSharp7_2() { string source = @" public class A : System.Attribute { } public class Test { [field: System.Obsolete] [field: A] public int P { get; set; } [field: System.Obsolete(""obsolete"", error: true)] public int P2 { get; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (7,6): warning CS8361: Field-targeted attributes on auto-properties are not supported in language version 7.2. Please use language version 7.3 or greater. // [field: System.Obsolete] Diagnostic(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, "field:").WithArguments("7.2", "7.3").WithLocation(7, 6), // (8,6): warning CS8361: Field-targeted attributes on auto-properties are not supported in language version 7.2. Please use language version 7.3 or greater. // [field: A] Diagnostic(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, "field:").WithArguments("7.2", "7.3").WithLocation(8, 6), // (11,6): warning CS8361: Field-targeted attributes on auto-properties are not supported in language version 7.2. Please use language version 7.3 or greater. // [field: System.Obsolete("obsolete", error: true)] Diagnostic(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, "field:").WithArguments("7.2", "7.3").WithLocation(11, 6) ); } [Fact] public void TestFieldAttributesOnAutoProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { public A(int i) { } } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { public B(int i) { } } public class Test { [field: A(1)] public int P { get; set; } [field: A(2)] public int P2 { get; } [B(3)] [field: A(33)] public int P3 { get; } [property: B(4)] [field: A(44)] [field: A(444)] public int P4 { get; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var propAttributesExpected = isFromSource ? new string[0] : s_autoPropAttributes; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.GetMethod.GetAttributes())); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.SetMethod.GetAttributes())); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(1)" }), GetAttributeStrings(field1.GetAttributes())); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop2.GetMethod.GetAttributes())); Assert.Null(prop2.SetMethod); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(2)" }), GetAttributeStrings(field2.GetAttributes())); var prop3 = @class.GetMember<PropertySymbol>("P3"); Assert.Equal("B(3)", prop3.GetAttributes().Single().ToString()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop3.GetMethod.GetAttributes())); Assert.Null(prop3.SetMethod); var field3 = @class.GetMember<FieldSymbol>("<P3>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(33)" }), GetAttributeStrings(field3.GetAttributes())); var prop4 = @class.GetMember<PropertySymbol>("P4"); Assert.Equal("B(4)", prop4.GetAttributes().Single().ToString()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop3.GetMethod.GetAttributes())); Assert.Null(prop4.SetMethod); var field4 = @class.GetMember<FieldSymbol>("<P4>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(44)", "A(444)" }), GetAttributeStrings(field4.GetAttributes())); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestGeneratedTupleAndDynamicAttributesOnAutoProperty() { string source = @" public class Test { public (dynamic a, int b) P { get; set; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); if (isFromSource) { Assert.Empty(field1.GetAttributes()); } else { var dynamicAndTupleNames = new[] { "System.Runtime.CompilerServices.DynamicAttribute({false, true, false})", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})" }; AssertEx.SetEqual(s_backingFieldAttributes.Concat(dynamicAndTupleNames), GetAttributeStrings(field1.GetAttributes())); } }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_SpecialName() { string source = @" public struct Test { [field: System.Runtime.CompilerServices.SpecialName] public static int P { get; set; } public static int P2 { get; set; } [field: System.Runtime.CompilerServices.SpecialName] public static int f; } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); var attributes1 = field1.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.Runtime.CompilerServices.SpecialNameAttribute" }, GetAttributeStrings(attributes1)); } else { AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(attributes1)); } Assert.True(field1.HasSpecialName); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field2.GetAttributes())); Assert.False(field2.HasSpecialName); var field3 = @class.GetMember<FieldSymbol>("f"); var attributes3 = field3.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.Runtime.CompilerServices.SpecialNameAttribute" }, GetAttributeStrings(attributes3)); } else { Assert.Empty(GetAttributeStrings(attributes3)); } }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_NonSerialized() { string source = @" public class Test { [field: System.NonSerialized] public int P { get; set; } public int P2 { get; set; } [field: System.NonSerialized] public int f; } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); var attributes1 = field1.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.NonSerializedAttribute" }, GetAttributeStrings(attributes1)); } else { AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(attributes1)); } Assert.True(field1.IsNotSerialized); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field2.GetAttributes())); Assert.False(field2.IsNotSerialized); var field3 = @class.GetMember<FieldSymbol>("f"); var attributes3 = field3.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.NonSerializedAttribute" }, GetAttributeStrings(attributes3)); } else { Assert.Empty(GetAttributeStrings(attributes3)); } Assert.True(field3.IsNotSerialized); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset() { string source = @" public struct Test { [field: System.Runtime.InteropServices.FieldOffset(0)] public static int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,13): error CS0637: The FieldOffset attribute is not allowed on static or const fields // [field: System.Runtime.InteropServices.FieldOffset(0)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadField, "System.Runtime.InteropServices.FieldOffset").WithArguments("System.Runtime.InteropServices.FieldOffset").WithLocation(4, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset2() { string source = @" public struct Test { [field: System.Runtime.InteropServices.FieldOffset(-1)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,56): error CS0591: Invalid value for argument to 'System.Runtime.InteropServices.FieldOffset' attribute // [field: System.Runtime.InteropServices.FieldOffset(-1)] Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "-1").WithArguments("System.Runtime.InteropServices.FieldOffset").WithLocation(4, 56), // (4,13): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [field: System.Runtime.InteropServices.FieldOffset(-1)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "System.Runtime.InteropServices.FieldOffset").WithLocation(4, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset3() { string source = @" using System.Runtime.InteropServices; [StructLayout(LayoutKind.Auto)] public class Test { [field: FieldOffset(4)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [field: FieldOffset(4)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "FieldOffset").WithLocation(7, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset4() { string source = @" using System.Runtime.InteropServices; public struct Test { [field: FieldOffset(4)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [field: FieldOffset(4)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "FieldOffset").WithLocation(6, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset5() { string source = @" using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit)] public struct Test { public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,16): error CS0625: 'Test.P': instance field in types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute // public int P { get; set; } Diagnostic(ErrorCode.ERR_MissingStructOffset, "P").WithArguments("Test.P").WithLocation(7, 16) ); } [Fact] public void TestWellKnownAttributeOnProperty_FixedBuffer() { string source = @" public class Test { [field: System.Runtime.CompilerServices.FixedBuffer(typeof(int), 0)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,13): error CS8362: Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute on a property // [field: System.Runtime.CompilerServices.FixedBuffer(typeof(int), 0)] Diagnostic(ErrorCode.ERR_DoNotUseFixedBufferAttrOnProperty, "System.Runtime.CompilerServices.FixedBuffer").WithLocation(4, 13) ); } [ConditionalFact(typeof(DesktopOnly))] public void TestWellKnownAttributeOnProperty_DynamicAttribute() { string source = @" public class Test { [field: System.Runtime.CompilerServices.DynamicAttribute()] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,13): error CS1970: Do not use 'System.Runtime.CompilerServices.DynamicAttribute'. Use the 'dynamic' keyword instead. // [field: System.Runtime.CompilerServices.DynamicAttribute()] Diagnostic(ErrorCode.ERR_ExplicitDynamicAttr, "System.Runtime.CompilerServices.DynamicAttribute()").WithLocation(4, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_IsReadOnlyAttribute() { string source = @" namespace System.Runtime.CompilerServices { public class IsReadOnlyAttribute : System.Attribute { } } public class Test { [field: System.Runtime.CompilerServices.IsReadOnlyAttribute()] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage. // [field: System.Runtime.CompilerServices.IsReadOnlyAttribute()] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "System.Runtime.CompilerServices.IsReadOnlyAttribute()").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(8, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_IsByRefLikeAttribute() { string source = @" namespace System.Runtime.CompilerServices { public class IsByRefLikeAttribute : System.Attribute { } } public class Test { [field: System.Runtime.CompilerServices.IsByRefLikeAttribute()] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS8335: Do not use 'System.Runtime.CompilerServices.IsByRefLikeAttribute'. This is reserved for compiler usage. // [field: System.Runtime.CompilerServices.IsByRefLikeAttribute()] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "System.Runtime.CompilerServices.IsByRefLikeAttribute()").WithArguments("System.Runtime.CompilerServices.IsByRefLikeAttribute").WithLocation(8, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_DateTimeConstant() { string source = @" public class Test { [field: System.Runtime.CompilerServices.DateTimeConstant(123456)] public System.DateTime P { get; set; } [field: System.Runtime.CompilerServices.DateTimeConstant(123456)] public int P2 { get; set; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "System.Runtime.CompilerServices.DateTimeConstantAttribute(123456)" }), GetAttributeStrings(field1.GetAttributes())); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "System.Runtime.CompilerServices.DateTimeConstantAttribute(123456)" }), GetAttributeStrings(field2.GetAttributes())); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_DecimalConstant() { string source = @" public class Test { [field: System.Runtime.CompilerServices.DecimalConstant(0, 0, 100, 100, 100)] public decimal P { get; set; } [field: System.Runtime.CompilerServices.DecimalConstant(0, 0, 100, 100, 100)] public int P2 { get; set; } [field: System.Runtime.CompilerServices.DecimalConstant(0, 0, 100, 100, 100)] public decimal field; } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Diagnostics.DebuggerBrowsableAttribute(System.Diagnostics.DebuggerBrowsableState.Never)" }; var constantExpected = "1844674407800451891300"; string[] decimalAttributeExpected = new[] { "System.Runtime.CompilerServices.DecimalConstantAttribute(0, 0, 100, 100, 100)" }; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); if (isFromSource) { AssertEx.SetEqual(fieldAttributesExpected.Concat(decimalAttributeExpected), GetAttributeStrings(field1.GetAttributes())); } else { AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field1.GetAttributes())); Assert.Equal(constantExpected, field1.ConstantValue.ToString()); } var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(decimalAttributeExpected), GetAttributeStrings(field2.GetAttributes())); var field3 = @class.GetMember<FieldSymbol>("field"); if (isFromSource) { AssertEx.SetEqual(decimalAttributeExpected, GetAttributeStrings(field3.GetAttributes())); } else { Assert.Empty(GetAttributeStrings(field3.GetAttributes())); Assert.Equal(constantExpected, field3.ConstantValue.ToString()); } }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_TupleElementNamesAttribute() { string source = @" namespace System.Runtime.CompilerServices { public sealed class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] transformNames) { } } } public class Test { [field: System.Runtime.CompilerServices.TupleElementNamesAttribute(new[] { ""hello"" })] public int P { get; set; } } "; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (11,13): error CS8138: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [field: System.Runtime.CompilerServices.TupleElementNamesAttribute(new[] { "hello" })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, @"System.Runtime.CompilerServices.TupleElementNamesAttribute(new[] { ""hello"" })").WithLocation(11, 13) ); } [Fact] public void TestWellKnownEarlyAttributeOnProperty_Obsolete() { string source = @" public class Test { [field: System.Obsolete] public int P { get; set; } [field: System.Obsolete(""obsolete"", error: true)] public int P2 { get; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var propAttributesExpected = isFromSource ? new string[0] : s_autoPropAttributes; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "System.ObsoleteAttribute" }), GetAttributeStrings(field1.GetAttributes())); Assert.Equal(ObsoleteAttributeKind.Obsolete, field1.ObsoleteAttributeData.Kind); Assert.Null(field1.ObsoleteAttributeData.Message); Assert.False(field1.ObsoleteAttributeData.IsError); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { @"System.ObsoleteAttribute(""obsolete"", true)" }), GetAttributeStrings(field2.GetAttributes())); Assert.Equal(ObsoleteAttributeKind.Obsolete, field2.ObsoleteAttributeData.Kind); Assert.Equal("obsolete", field2.ObsoleteAttributeData.Message); Assert.True(field2.ObsoleteAttributeData.IsError); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestFieldAttributesOnProperty() { string source = @" public class A : System.Attribute { } public class Test { [field: A] public int P { get => throw null; set => throw null; } [field: A] public int P2 { get => throw null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(9, 6), // (6,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(6, 6) ); } [Fact] public void TestFieldAttributesOnPropertyAccessors() { string source = @" public class A : System.Attribute { } public class Test { public int P { [field: A] get => throw null; set => throw null; } public int P2 { [field: A] get; set; } public int P3 { [field: A] get => throw null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. // public int P { [field: A] get => throw null; set => throw null; } Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return").WithLocation(6, 21), // (7,22): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. // public int P2 { [field: A] get; set; } Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return").WithLocation(7, 22), // (8,22): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. // public int P3 { [field: A] get => throw null; } Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return").WithLocation(8, 22) ); } [Fact] public void TestMultipleFieldAttributesOnProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = false) ] public class Single : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class Multiple : System.Attribute { } public class Test { [field: Single] [field: Single] [field: Multiple] [field: Multiple] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,13): error CS0579: Duplicate 'Single' attribute // [field: Single] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Single").WithArguments("Single").WithLocation(11, 13) ); } [Fact] public void TestInheritedFieldAttributesOnOverriddenProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.All, Inherited = true) ] public class A : System.Attribute { public A(int i) { } } public class Base { [field: A(1)] [A(2)] public virtual int P { get; set; } } public class Derived : Base { public override int P { get; set; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var parent = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); bool isFromSource = parent is SourceNamedTypeSymbol; var propAttributesExpected = isFromSource ? new string[0] : s_autoPropAttributes; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = parent.GetMember<PropertySymbol>("P"); Assert.Equal("A(2)", prop1.GetAttributes().Single().ToString()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.GetMethod.GetAttributes())); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.SetMethod.GetAttributes())); var field1 = parent.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(1)" }), GetAttributeStrings(field1.GetAttributes())); var child = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var prop2 = child.GetMember<PropertySymbol>("P"); Assert.Empty(prop2.GetAttributes()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop2.GetMethod.GetAttributes())); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop2.SetMethod.GetAttributes())); var field2 = child.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field2.GetAttributes())); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestPropertyTargetedFieldAttributesOnAutoProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Property) ] public class A : System.Attribute { } public class Test { [field: A] public int P { get; set; } [field: A] public int P2 { get; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,13): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [field: A] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "property, indexer").WithLocation(10, 13), // (7,13): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [field: A] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "property, indexer").WithLocation(7, 13) ); } [Fact] public void TestClassTargetedFieldAttributesOnAutoProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Class) ] public class ClassAllowed : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Field) ] public class FieldAllowed : System.Attribute { } public class Test { [field: ClassAllowed] // error 1 [field: FieldAllowed] public int P { get; set; } [field: ClassAllowed] // error 2 [field: FieldAllowed] public int P2 { get; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,13): error CS0592: Attribute 'ClassAllowed' is not valid on this declaration type. It is only valid on 'class' declarations. // [field: ClassAllowed] // error 2 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "ClassAllowed").WithArguments("ClassAllowed", "class").WithLocation(14, 13), // (10,13): error CS0592: Attribute 'ClassAllowed' is not valid on this declaration type. It is only valid on 'class' declarations. // [field: ClassAllowed] // error 1 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "ClassAllowed").WithArguments("ClassAllowed", "class").WithLocation(10, 13) ); } [Fact] public void TestImproperlyTargetedFieldAttributesOnProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Property) ] public class A : System.Attribute { } public class Test { [field: A] public int P { get => throw null; set => throw null; } [field: A] public int P2 { get => throw null; } [field: A] public int P3 { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(10, 6), // (13,13): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [field: A] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "property, indexer").WithLocation(13, 13), // (7,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(7, 6) ); } [Fact] public void TestAttributesOnEvents() { string source = @" public class AA : System.Attribute { } public class BB : System.Attribute { } public class CC : System.Attribute { } public class DD : System.Attribute { } public class EE : System.Attribute { } public class FF : System.Attribute { } public class GG : System.Attribute { } public class HH : System.Attribute { } public class II : System.Attribute { } public class JJ : System.Attribute { } public class Test { [AA] //in event decl public event System.Action E1; [event: BB] //in event decl public event System.Action E2; [method: CC] //in both accessors public event System.Action E3; [field: DD] //on field public event System.Action E4; [EE] //in event decl public event System.Action E5 { add { } remove { } } [event: FF] //in event decl public event System.Action E6 { add { } remove { } } public event System.Action E7 { [GG] add { } remove { } } //in accessor public event System.Action E8 { [method: HH] add { } remove { } } //in accessor public event System.Action E9 { [param: II] add { } remove { } } //on parameter (after .param[1]) public event System.Action E10 { [return: JJ] add { } remove { } } //on return (after .param[0]) } "; Func<bool, Action<ModuleSymbol>> symbolValidator = isFromSource => moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var event1 = @class.GetMember<EventSymbol>("E1"); var event2 = @class.GetMember<EventSymbol>("E2"); var event3 = @class.GetMember<EventSymbol>("E3"); var event4 = @class.GetMember<EventSymbol>("E4"); var event5 = @class.GetMember<EventSymbol>("E5"); var event6 = @class.GetMember<EventSymbol>("E6"); var event7 = @class.GetMember<EventSymbol>("E7"); var event8 = @class.GetMember<EventSymbol>("E8"); var event9 = @class.GetMember<EventSymbol>("E9"); var event10 = @class.GetMember<EventSymbol>("E10"); var accessorsExpected = isFromSource ? new string[0] : new[] { "CompilerGeneratedAttribute" }; Assert.Equal("AA", GetSingleAttributeName(event1)); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event1.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event1.RemoveMethod.GetAttributes())); if (isFromSource) { AssertNoAttributes(event1.AssociatedField); Assert.Equal(0, event1.GetFieldAttributes().Length); } Assert.Equal("BB", GetSingleAttributeName(event2)); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event2.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event2.RemoveMethod.GetAttributes())); if (isFromSource) { AssertNoAttributes(event2.AssociatedField); Assert.Equal(0, event2.GetFieldAttributes().Length); } AssertNoAttributes(event3); AssertEx.SetEqual(accessorsExpected.Concat(new[] { "CC" }), GetAttributeNames(event3.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected.Concat(new[] { "CC" }), GetAttributeNames(event3.RemoveMethod.GetAttributes())); if (isFromSource) { AssertNoAttributes(event3.AssociatedField); Assert.Equal(0, event3.GetFieldAttributes().Length); } AssertNoAttributes(event4); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event4.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event4.RemoveMethod.GetAttributes())); if (isFromSource) { Assert.Equal("DD", GetSingleAttributeName(event4.AssociatedField)); Assert.Equal("DD", event4.GetFieldAttributes().Single().AttributeClass.Name); } Assert.Equal("EE", GetSingleAttributeName(event5)); AssertNoAttributes(event5.AddMethod); AssertNoAttributes(event5.RemoveMethod); Assert.Equal("FF", GetSingleAttributeName(event6)); AssertNoAttributes(event6.AddMethod); AssertNoAttributes(event6.RemoveMethod); AssertNoAttributes(event7); Assert.Equal("GG", GetSingleAttributeName(event7.AddMethod)); AssertNoAttributes(event7.RemoveMethod); AssertNoAttributes(event8); Assert.Equal("HH", GetSingleAttributeName(event8.AddMethod)); AssertNoAttributes(event8.RemoveMethod); AssertNoAttributes(event9); AssertNoAttributes(event9.AddMethod); AssertNoAttributes(event9.RemoveMethod); Assert.Equal("II", GetSingleAttributeName(event9.AddMethod.Parameters.Single())); AssertNoAttributes(event10); AssertNoAttributes(event10.AddMethod); AssertNoAttributes(event10.RemoveMethod); Assert.Equal("JJ", event10.AddMethod.GetReturnTypeAttributes().Single().AttributeClass.Name); }; CompileAndVerify(source, sourceSymbolValidator: symbolValidator(true), symbolValidator: symbolValidator(false)); } [Fact] public void TestAttributesOnEvents_NoDuplicateDiagnostics() { string source = @" public class AA : System.Attribute { } public class BB : System.Attribute { } public class CC : System.Attribute { } public class DD : System.Attribute { } public class EE : System.Attribute { } public class FF : System.Attribute { } public class GG : System.Attribute { } public class HH : System.Attribute { } public class II : System.Attribute { } public class JJ : System.Attribute { } public class Test { [AA(0)] //in event decl public event System.Action E1; [event: BB(0)] //in event decl public event System.Action E2; [method: CC(0)] //in both accessors public event System.Action E3; [field: DD(0)] //on field public event System.Action E4; [EE(0)] //in event decl public event System.Action E5 { add { } remove { } } [event: FF(0)] //in event decl public event System.Action E6 { add { } remove { } } public event System.Action E7 { [GG(0)] add { } remove { } } //in accessor public event System.Action E8 { [method: HH(0)] add { } remove { } } //in accessor public event System.Action E9 { [param: II(0)] add { } remove { } } //on parameter (after .param[1]) public event System.Action E10 { [return: JJ(0)] add { } remove { } } //on return (after .param[0]) } "; CreateCompilation(source).VerifyDiagnostics( // (15,6): error CS1729: 'AA' does not contain a constructor that takes 1 arguments // [AA(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "AA(0)").WithArguments("AA", "1"), // (17,13): error CS1729: 'BB' does not contain a constructor that takes 1 arguments // [event: BB(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "BB(0)").WithArguments("BB", "1"), // (19,14): error CS1729: 'CC' does not contain a constructor that takes 1 arguments // [method: CC(0)] //in both accessors Diagnostic(ErrorCode.ERR_BadCtorArgCount, "CC(0)").WithArguments("CC", "1"), // (21,13): error CS1729: 'DD' does not contain a constructor that takes 1 arguments // [field: DD(0)] //on field Diagnostic(ErrorCode.ERR_BadCtorArgCount, "DD(0)").WithArguments("DD", "1"), // (24,6): error CS1729: 'EE' does not contain a constructor that takes 1 arguments // [EE(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "EE(0)").WithArguments("EE", "1"), // (26,13): error CS1729: 'FF' does not contain a constructor that takes 1 arguments // [event: FF(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "FF(0)").WithArguments("FF", "1"), // (29,38): error CS1729: 'GG' does not contain a constructor that takes 1 arguments // public event System.Action E7 { [GG(0)] add { } remove { } } //in accessor Diagnostic(ErrorCode.ERR_BadCtorArgCount, "GG(0)").WithArguments("GG", "1"), // (30,46): error CS1729: 'HH' does not contain a constructor that takes 1 arguments // public event System.Action E8 { [method: HH(0)] add { } remove { } } //in accessor Diagnostic(ErrorCode.ERR_BadCtorArgCount, "HH(0)").WithArguments("HH", "1"), // (31,45): error CS1729: 'II' does not contain a constructor that takes 1 arguments // public event System.Action E9 { [param: II(0)] add { } remove { } } //on parameter (after .param[1]) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "II(0)").WithArguments("II", "1"), // (32,47): error CS1729: 'JJ' does not contain a constructor that takes 1 arguments // public event System.Action E10 { [return: JJ(0)] add { } remove { } } //on return (after .param[0]) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "JJ(0)").WithArguments("JJ", "1"), // (22,32): warning CS0067: The event 'Test.E4' is never used // public event System.Action E4; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E4").WithArguments("Test.E4"), // (18,32): warning CS0067: The event 'Test.E2' is never used // public event System.Action E2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E2").WithArguments("Test.E2"), // (20,32): warning CS0067: The event 'Test.E3' is never used // public event System.Action E3; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E3").WithArguments("Test.E3"), // (16,32): warning CS0067: The event 'Test.E1' is never used // public event System.Action E1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("Test.E1")); } [Fact] public void TestAttributesOnIndexer_NoDuplicateDiagnostics() { string source = @" public class AA : System.Attribute { } public class BB : System.Attribute { } public class CC : System.Attribute { } public class DD : System.Attribute { } public class EE : System.Attribute { } public class Test { public int this[[AA(0)]int x] { [return: BB(0)] [CC(0)] get { return x; } [param: DD(0)] [EE(0)] set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,22): error CS1729: 'AA' does not contain a constructor that takes 1 arguments // public int this[[AA(0)]int x] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "AA(0)").WithArguments("AA", "1"), // (13,10): error CS1729: 'CC' does not contain a constructor that takes 1 arguments // [CC(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "CC(0)").WithArguments("CC", "1"), // (12,18): error CS1729: 'BB' does not contain a constructor that takes 1 arguments // [return: BB(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "BB(0)").WithArguments("BB", "1"), // (16,17): error CS1729: 'DD' does not contain a constructor that takes 1 arguments // [param: DD(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "DD(0)").WithArguments("DD", "1"), // (17,10): error CS1729: 'EE' does not contain a constructor that takes 1 arguments // [EE(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "EE(0)").WithArguments("EE", "1")); } private static string GetSingleAttributeName(Symbol symbol) { return symbol.GetAttributes().Single().AttributeClass.Name; } private static void AssertNoAttributes(Symbol symbol) { Assert.Equal(0, symbol.GetAttributes().Length); } [Fact] public void TestAttributesOnDelegates() { string source = @" using System; public class TypeAttribute : System.Attribute { } public class ParamAttribute : System.Attribute { } public class ReturnTypeAttribute : System.Attribute { } public class TypeParamAttribute : System.Attribute { } class C { [TypeAttribute] [return: ReturnTypeAttribute] public delegate T Delegate<[TypeParamAttribute]T> ([ParamAttribute]T p1, [param: ParamAttribute]ref T p2, [ParamAttribute]out T p3); public delegate int Delegate2 ([ParamAttribute]int p1 = 0, [param: ParamAttribute]params int[] p2); static void Main() { typeof(Delegate<int>).GetCustomAttributes(false); } }"; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var type = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var typeAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeAttribute"); var paramAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ParamAttribute"); var returnTypeAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ReturnTypeAttribute"); var typeParamAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeParamAttribute"); // Verify delegate type attribute var delegateType = type.GetTypeMember("Delegate"); Assert.Equal(1, delegateType.GetAttributes(typeAttrType).Count()); // Verify type parameter attribute var typeParameters = delegateType.TypeParameters; Assert.Equal(1, typeParameters.Length); Assert.Equal(1, typeParameters[0].GetAttributes(typeParamAttrType).Count()); // Verify delegate methods (return type/parameters) attributes // Invoke method // 1) Has return type attributes from delegate declaration syntax // 2) Has parameter attributes from delegate declaration syntax var invokeMethod = delegateType.GetMethod("Invoke"); Assert.Equal(1, invokeMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, returnTypeAttrType, TypeCompareKind.ConsiderEverything2)).Count()); Assert.Equal(typeParameters[0], invokeMethod.ReturnType); var parameters = invokeMethod.GetParameters(); Assert.Equal(3, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal("p3", parameters[2].Name); Assert.Equal(1, parameters[2].GetAttributes(paramAttrType).Count()); // Delegate Constructor: // 1) Doesn't have any return type attributes // 2) Doesn't have any parameter attributes var ctor = delegateType.GetMethod(".ctor"); Assert.Equal(0, ctor.GetReturnTypeAttributes().Length); parameters = ctor.GetParameters(); Assert.Equal(2, parameters.Length); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.Equal(0, parameters[1].GetAttributes().Length); // BeginInvoke method: // 1) Doesn't have any return type attributes // 2) Has parameter attributes from delegate declaration parameters syntax var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke"); Assert.Equal(0, beginInvokeMethod.GetReturnTypeAttributes().Length); parameters = beginInvokeMethod.GetParameters(); Assert.Equal(5, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal("p3", parameters[2].Name); Assert.Equal(1, parameters[2].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[3].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[4].GetAttributes(paramAttrType).Count()); // EndInvoke method: // 1) Has return type attributes from delegate declaration syntax // 2) Has parameter attributes from delegate declaration syntax // only for ref/out parameters. var endInvokeMethod = (MethodSymbol)delegateType.GetMember("EndInvoke"); Assert.Equal(1, endInvokeMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, returnTypeAttrType, TypeCompareKind.ConsiderEverything2)).Count()); parameters = endInvokeMethod.GetParameters(); Assert.Equal(3, parameters.Length); Assert.Equal("p2", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p3", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[2].GetAttributes(paramAttrType).Count()); }; CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); } [Fact] public void TestAttributesOnDelegates_NoDuplicateDiagnostics() { string source = @" public class TypeAttribute : System.Attribute { } public class ParamAttribute1 : System.Attribute { } public class ParamAttribute2 : System.Attribute { } public class ParamAttribute3 : System.Attribute { } public class ParamAttribute4 : System.Attribute { } public class ParamAttribute5 : System.Attribute { } public class ReturnTypeAttribute : System.Attribute { } public class TypeParamAttribute : System.Attribute { } class C { [TypeAttribute(0)] [return: ReturnTypeAttribute(0)] public delegate T Delegate<[TypeParamAttribute(0)]T> ([ParamAttribute1(0)]T p1, [param: ParamAttribute2(0)]ref T p2, [ParamAttribute3(0)]out T p3); public delegate int Delegate2 ([ParamAttribute4(0)]int p1 = 0, [param: ParamAttribute5(0)]params int[] p2); }"; CreateCompilation(source).VerifyDiagnostics( // (13,6): error CS1729: 'TypeAttribute' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "TypeAttribute(0)").WithArguments("TypeAttribute", "1"), // (15,33): error CS1729: 'TypeParamAttribute' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "TypeParamAttribute(0)").WithArguments("TypeParamAttribute", "1"), // (15,60): error CS1729: 'ParamAttribute1' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute1(0)").WithArguments("ParamAttribute1", "1"), // (15,93): error CS1729: 'ParamAttribute2' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute2(0)").WithArguments("ParamAttribute2", "1"), // (15,123): error CS1729: 'ParamAttribute3' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute3(0)").WithArguments("ParamAttribute3", "1"), // (14,14): error CS1729: 'ReturnTypeAttribute' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ReturnTypeAttribute(0)").WithArguments("ReturnTypeAttribute", "1"), // (17,37): error CS1729: 'ParamAttribute4' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute4(0)").WithArguments("ParamAttribute4", "1"), // (17,76): error CS1729: 'ParamAttribute5' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute5(0)").WithArguments("ParamAttribute5", "1")); } [Fact] public void TestAttributesOnDelegateWithOptionalAndParams() { string source = @" using System; public class ParamAttribute : System.Attribute { } class C { public delegate int Delegate ([ParamAttribute]int p1 = 0, [param: ParamAttribute]params int[] p2); static void Main() { typeof(Delegate).GetCustomAttributes(false); } }"; Func<bool, Action<ModuleSymbol>> symbolValidator = isFromMetadata => moduleSymbol => { var type = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var paramAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ParamAttribute"); // Verify delegate type attribute var delegateType = type.GetTypeMember("Delegate"); // Verify delegate methods (return type/parameters) attributes // Invoke method has parameter attributes from delegate declaration syntax var invokeMethod = (MethodSymbol)delegateType.GetMember("Invoke"); var parameters = invokeMethod.GetParameters(); Assert.Equal(2, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); if (isFromMetadata) { // verify ParamArrayAttribute on p2 VerifyParamArrayAttribute(parameters[1]); } // Delegate Constructor: Doesn't have any parameter attributes var ctor = (MethodSymbol)delegateType.GetMember(".ctor"); parameters = ctor.GetParameters(); Assert.Equal(2, parameters.Length); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.Equal(0, parameters[1].GetAttributes().Length); // BeginInvoke method: Has parameter attributes from delegate declaration parameters syntax var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke"); parameters = beginInvokeMethod.GetParameters(); Assert.Equal(4, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[2].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[3].GetAttributes(paramAttrType).Count()); if (isFromMetadata) { // verify no ParamArrayAttribute on p2 VerifyParamArrayAttribute(parameters[1], expected: false); } }; CompileAndVerify(source, sourceSymbolValidator: symbolValidator(false), symbolValidator: symbolValidator(true)); } [Fact] public void TestAttributesOnEnumField() { string source = @" using System; using System.Collections.Generic; using System.Reflection; using CustomAttribute; using AN = CustomAttribute.AttrName; // Use AttrName without Attribute suffix [assembly: AN(UShortField = 4321)] [assembly: AN(UShortField = 1234)] // TODO: below attribute seems to be an ambiguous attribute specification // TODO: modify the test assembly to remove ambiguity // [module: AttrName(TypeField = typeof(System.IO.FileStream))] namespace AttributeTest { class Goo { public class NestedClass { // enum as object [AllInheritMultiple(System.IO.FileMode.Open, BindingFlags.DeclaredOnly | BindingFlags.Public, UIntField = 123 * Field)] internal const uint Field = 10; } [AllInheritMultiple(new char[] { 'q', 'c' }, """")] [AllInheritMultiple()] enum NestedEnum { zero, one = 1, [AllInheritMultiple(null, 256, 0f, -1, AryField = new ulong[] { 0, 1, 12345657 })] [AllInheritMultipleAttribute(typeof(Dictionary<string, int>), 255 + NestedClass.Field, -0.0001f, 3 - (short)NestedEnum.oneagain)] three = 3, oneagain = one } } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; var compilation = CreateCompilation(source, references, options: TestOptions.ReleaseDll); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var attrs = m.GetAttributes(); // Assert.Equal(1, attrs.Count); // Assert.Equal("CustomAttribute.AttrName", attrs[0].AttributeClass.ToDisplayString()); // attrs[0].VerifyValue<Type>(0, "TypeField", TypedConstantKind.Type, typeof(System.IO.FileStream)); var assembly = m.ContainingSymbol; attrs = assembly.GetAttributes(); Assert.Equal(2, attrs.Length); Assert.Equal("CustomAttribute.AttrName", attrs[0].AttributeClass.ToDisplayString()); attrs[1].VerifyNamedArgumentValue<ushort>(0, "UShortField", TypedConstantKind.Primitive, 1234); var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var top = (NamedTypeSymbol)ns.GetMember("Goo"); var type = top.GetMember<NamedTypeSymbol>("NestedClass"); var field = type.GetMember<FieldSymbol>("Field"); attrs = field.GetAttributes(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attrs[0].AttributeClass.ToDisplayString()); attrs[0].VerifyValue(0, TypedConstantKind.Enum, (int)FileMode.Open); attrs[0].VerifyValue(1, TypedConstantKind.Enum, (int)(BindingFlags.DeclaredOnly | BindingFlags.Public)); attrs[0].VerifyNamedArgumentValue<uint>(0, "UIntField", TypedConstantKind.Primitive, 1230); var nenum = top.GetMember<TypeSymbol>("NestedEnum"); attrs = nenum.GetAttributes(); Assert.Equal(2, attrs.Length); attrs[0].VerifyValue(0, TypedConstantKind.Array, new char[] { 'q', 'c' }); Assert.Equal(SyntaxKind.Attribute, attrs[0].ApplicationSyntaxReference.GetSyntax().Kind()); var syntax = (AttributeSyntax)attrs[0].ApplicationSyntaxReference.GetSyntax(); Assert.Equal(2, syntax.ArgumentList.Arguments.Count()); syntax = (AttributeSyntax)attrs[1].ApplicationSyntaxReference.GetSyntax(); Assert.Equal(0, syntax.ArgumentList.Arguments.Count()); attrs = nenum.GetMember("three").GetAttributes(); Assert.Equal(2, attrs.Length); attrs[0].VerifyValue<object>(0, TypedConstantKind.Primitive, null); attrs[0].VerifyValue<long>(1, TypedConstantKind.Primitive, 256); attrs[0].VerifyValue<float>(2, TypedConstantKind.Primitive, 0); attrs[0].VerifyValue<short>(3, TypedConstantKind.Primitive, -1); attrs[0].VerifyNamedArgumentValue<ulong[]>(0, "AryField", TypedConstantKind.Array, new ulong[] { 0, 1, 12345657 }); attrs[1].VerifyValue<object>(0, TypedConstantKind.Type, typeof(Dictionary<string, int>)); attrs[1].VerifyValue<long>(1, TypedConstantKind.Primitive, 265); attrs[1].VerifyValue<float>(2, TypedConstantKind.Primitive, -0.0001f); attrs[1].VerifyValue<short>(3, TypedConstantKind.Primitive, 2); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] public void TestAttributesOnDelegate() { string source = @" using System; using System.Collections.Generic; using CustomAttribute; namespace AttributeTest { public class Goo { [AllInheritMultiple(new object[] { 0, """", null }, 255, -127 - 1, AryProp = new object[] { new object[] { """", typeof(IList<string>) } })] public delegate void NestedSubDele([AllInheritMultiple()]string p1, [Derived(typeof(string[, ,]))]string p2); } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Goo"); var dele = (NamedTypeSymbol)type.GetTypeMember("NestedSubDele"); var attrs = dele.GetAttributes(); attrs.First().VerifyValue<object>(0, TypedConstantKind.Array, new object[] { 0, "", null }); attrs.First().VerifyValue<byte>(1, TypedConstantKind.Primitive, 255); attrs.First().VerifyValue<sbyte>(2, TypedConstantKind.Primitive, -128); attrs.First().VerifyNamedArgumentValue<object[]>(0, "AryProp", TypedConstantKind.Array, new object[] { new object[] { "", typeof(IList<string>) } }); var mem = dele.GetMember<MethodSymbol>("Invoke"); attrs = mem.Parameters[0].GetAttributes(); Assert.Equal(1, attrs.Length); attrs = mem.Parameters[1].GetAttributes(); Assert.Equal(1, attrs.Length); attrs[0].VerifyValue<object>(0, TypedConstantKind.Type, typeof(string[,,])); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [Fact] public void TestAttributesUseBaseAttributeField() { string source = @" using System; namespace AttributeTest { public interface IGoo { [CustomAttribute.Derived(new object[] { 1, null, ""Hi"" }, ObjectField = 2)] int F(int p); } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetMember<MethodSymbol>("F").GetAttributes(); Assert.Equal(@"CustomAttribute.DerivedAttribute({1, null, ""Hi""}, ObjectField = 2)", attrs.First().ToString()); attrs.First().VerifyValue<object>(0, TypedConstantKind.Array, new object[] { 1, null, "Hi" }); attrs.First().VerifyNamedArgumentValue<object>(0, "ObjectField", TypedConstantKind.Primitive, 2); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007a() { string source = @" using System; using X; using Z; namespace X { public class AttrAttribute : Attribute { } } namespace Z { public class Attr { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("X.AttrAttribute", attrs[0].AttributeClass.ToDisplayString()); CompileAndVerify(compilation).VerifyDiagnostics(); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007b() { string source = @" using System; using X; using Z; namespace X { public class AttrAttribute : Attribute { } public class Attr : Attribute { } } namespace Z { public class Attr : Attribute { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("X.AttrAttribute", attrs[0].AttributeClass.ToDisplayString()); CompileAndVerify(compilation).VerifyDiagnostics(); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007c() { string source = @" using System; using X; using Y; using Z; namespace X { public class AttrAttribute /*: Attribute*/ { } } namespace Y { public class AttrAttribute /*: Attribute*/ { } } namespace Z { public class Attr : Attribute { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("Z.Attr", attrs[0].AttributeClass.ToDisplayString()); CompileAndVerify(compilation).VerifyDiagnostics(); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007d() { string source = @" using System; using X; using Y; using Z; namespace X { public class AttrAttribute : Attribute { } } namespace Y { public class AttrAttribute : Attribute { } } namespace Z { public class Attr : Attribute { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("Z.Attr", attrs[0].AttributeClass.ToDisplayString()); var syntax = attrs.Single().ApplicationSyntaxReference.GetSyntax(); Assert.NotNull(syntax); Assert.IsType<AttributeSyntax>(syntax); CompileAndVerify(compilation).VerifyDiagnostics(); } [Fact] public void TestAttributesWithParamArrayInCtor01() { string source = @" using System; using CustomAttribute; namespace AttributeTest { [AllInheritMultiple(new char[] { ' '}, """")] public interface IGoo { } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> sourceAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "" }); Assert.True(attrs.First().AttributeConstructor.Parameters.Last().IsParams); }; Action<ModuleSymbol> mdAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "" }); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: sourceAttributeValidator, symbolValidator: mdAttributeValidator); } [Fact] public void TestAttributesWithParamArrayInCtor02() { string source = @" using System; namespace AttributeTest { class ExampleAttribute : Attribute { public int[] Numbers; public ExampleAttribute(string message, params int[] numbers) { Numbers = numbers; } } class Program { [Example(""MultipleArgumentsToParamsParameter"", 4, 5, 6)] public void MultipleArgumentsToParamsParameter() { } [Example(""NoArgumentsToParamsParameter"")] public void NoArgumentsToParamsParameter() { } [Example(""NullArgumentToParamsParameter"", null)] public void NullArgumentToParamsParameter() { } static void Main() { ExampleAttribute att = null; try { var programType = typeof(Program); var method = programType.GetMember(""MultipleArgumentsToParamsParameter"")[0]; att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0]; method = programType.GetMember(""NoArgumentsToParamsParameter"")[0]; att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0]; method = programType.GetMember(""NullArgumentToParamsParameter"")[0]; att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0]; } catch (Exception e) { Console.WriteLine(e.Message); return; } Console.WriteLine(true); } } } "; Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Program"); var attributeClass = (NamedTypeSymbol)ns.GetMember("ExampleAttribute"); var method = (MethodSymbol)type.GetMember("MultipleArgumentsToParamsParameter"); var attrs = method.GetAttributes(attributeClass); var attr = attrs.Single(); Assert.Equal(2, attr.CommonConstructorArguments.Length); attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "MultipleArgumentsToParamsParameter"); attr.VerifyValue<int[]>(1, TypedConstantKind.Array, new int[] { 4, 5, 6 }); method = (MethodSymbol)type.GetMember("NoArgumentsToParamsParameter"); attrs = method.GetAttributes(attributeClass); attr = attrs.Single(); Assert.Equal(2, attr.CommonConstructorArguments.Length); attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "NoArgumentsToParamsParameter"); attr.VerifyValue<int[]>(1, TypedConstantKind.Array, new int[] { }); method = (MethodSymbol)type.GetMember("NullArgumentToParamsParameter"); attrs = method.GetAttributes(attributeClass); attr = attrs.Single(); Assert.Equal(2, attr.CommonConstructorArguments.Length); attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "NullArgumentToParamsParameter"); attr.VerifyValue<int[]>(1, TypedConstantKind.Array, null); }; // Verify attributes from source and then load metadata to see attributes are written correctly. var compVerifier = CompileAndVerify( source, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator, expectedOutput: "True\r\n", expectedSignatures: new[] { Signature("AttributeTest.Program", "MultipleArgumentsToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"MultipleArgumentsToParamsParameter\", System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] public hidebysig instance System.Void MultipleArgumentsToParamsParameter() cil managed"), Signature("AttributeTest.Program", "NoArgumentsToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"NoArgumentsToParamsParameter\", System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] public hidebysig instance System.Void NoArgumentsToParamsParameter() cil managed"), Signature("AttributeTest.Program", "NullArgumentToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"NullArgumentToParamsParameter\", )] public hidebysig instance System.Void NullArgumentToParamsParameter() cil managed"), }); } [Fact, WorkItem(531385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531385")] public void TestAttributesWithParamArrayInCtor3() { string source = @" using System; using CustomAttribute; namespace AttributeTest { [AllInheritMultiple(new char[] { ' ' }, new string[] { ""whatever"" })] public interface IGoo { } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> sourceAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "whatever" }); Assert.True(attrs.First().AttributeConstructor.Parameters.Last().IsParams); }; Action<ModuleSymbol> mdAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "whatever" }); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: sourceAttributeValidator, symbolValidator: mdAttributeValidator); } [Fact] public void TestAttributeSpecifiedOnItself() { string source = @" using System; namespace AttributeTest { [MyAttribute(typeof(object))] public class MyAttribute : Attribute { public MyAttribute(Type t) { } public static void Main() { } } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("MyAttribute"); var attrs = type.GetAttributes(); Assert.Equal(1, attrs.Length); attrs.First().VerifyValue(0, TypedConstantKind.Type, typeof(Object)); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [Fact] public void TestAttributesWithEnumArrayInCtor() { string source = @" using System; namespace AttributeTest { public enum X { a, b }; public class Y : Attribute { public int f; public Y(X[] x) { } } [Y(A.x)] public class A { public const X[] x = null; public static void Main() { } } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Array, (object[])null); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541058")] [Fact] public void TestAttributesWithTypeof() { string source = @" using System; [MyAttribute(typeof(object))] public class MyAttribute : Attribute { public MyAttribute(Type t) { } public static void Main() { } } "; CompileAndVerify(source); } [WorkItem(541071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541071")] [Fact] public void TestAttributesWithParams() { string source = @" using System; class ExampleAttribute : Attribute { public int[] Numbers; public ExampleAttribute(string message, params int[] numbers) { Numbers = numbers; } } [Example(""wibble"", 4, 5, 6)] class Program { static void Main() { ExampleAttribute att = null; try { att = (ExampleAttribute)typeof(Program).GetCustomAttributes(typeof(ExampleAttribute), false)[0]; } catch (Exception e) { Console.WriteLine(e.Message); return; } Console.WriteLine(true); } } "; var expectedOutput = @"True"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestAttributesOnReturnType() { string source = @" using System; using CustomAttribute; namespace AttributeTest { public class Goo { int p; public int Property { [return: AllInheritMultipleAttribute()] [AllInheritMultipleAttribute()] get { return p; } [return: AllInheritMultipleAttribute()] [AllInheritMultipleAttribute()] set { p = value; } } [return: AllInheritMultipleAttribute()] [return: AllInheritMultipleAttribute()] public int Method() { return p; } [return: AllInheritMultipleAttribute()] public delegate void Delegate(); public static void Main() {} } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Goo"); var property = (PropertySymbol)type.GetMember("Property"); var getter = property.GetMethod; var attrs = getter.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); var attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var setter = property.SetMethod; attrs = setter.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var method = (MethodSymbol)type.GetMember("Method"); attrs = method.GetReturnTypeAttributes(); Assert.Equal(2, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); attr = attrs.Last(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var delegateType = type.GetTypeMember("Delegate"); var invokeMethod = (MethodSymbol)delegateType.GetMember("Invoke"); attrs = invokeMethod.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var ctor = (MethodSymbol)delegateType.GetMember(".ctor"); attrs = ctor.GetReturnTypeAttributes(); Assert.Equal(0, attrs.Length); var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke"); attrs = beginInvokeMethod.GetReturnTypeAttributes(); Assert.Equal(0, attrs.Length); var endInvokeMethod = (MethodSymbol)delegateType.GetMember("EndInvoke"); attrs = endInvokeMethod.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541397")] [Fact] public void TestAttributeWithSameNameAsTypeParameter() { string source = @" using System; namespace AttributeTest { public class TAttribute : Attribute { } public class RAttribute : TAttribute { } public class GClass<T> { [T] public enum E { } [R] internal R M<R>() { return default(R); } } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("GClass"); var enumType = (NamedTypeSymbol)type.GetTypeMember("E"); var attributeType = (NamedTypeSymbol)ns.GetMember("TAttribute"); var attributeType2 = (NamedTypeSymbol)ns.GetMember("RAttribute"); var genMethod = (MethodSymbol)type.GetMember("M"); var attrs = enumType.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs = genMethod.GetAttributes(attributeType2); Assert.Equal(1, attrs.Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541615")] [Fact] public void TestAttributeWithVarIdentifierName() { string source = @" using System; namespace AttributeTest { public class var: Attribute { } [var] class Program { public static void Main() {} } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Program"); var attributeType = (NamedTypeSymbol)ns.GetMember("var"); var attrs = type.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); var attr = attrs.First(); Assert.Equal("AttributeTest.var", attr.ToString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541505")] [Fact] public void AttributeArgumentBind_PropertyWithSameName() { var source = @"using System; namespace AttributeTest { class TestAttribute : Attribute { public TestAttribute(ProtectionLevel p){} } enum ProtectionLevel { Privacy = 0 } class TestClass { ProtectionLevel ProtectionLevel { get { return ProtectionLevel.Privacy; } } [TestAttribute(ProtectionLevel.Privacy)] public int testField; } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("TestClass"); var attributeType = (NamedTypeSymbol)ns.GetMember("TestAttribute"); var field = (FieldSymbol)type.GetMember("testField"); var attrs = field.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541709, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541709")] [Fact] public void AttributeOnSynthesizedParameterSymbol() { var source = @"using System; namespace AttributeTest { public class TestAttributeForMethod : System.Attribute { } public class TestAttributeForParam : System.Attribute { } public class TestAttributeForReturn : System.Attribute { } class TestClass { int P1 { [TestAttributeForMethod] [param: TestAttributeForParam] [return: TestAttributeForReturn] set { } } int P2 { [TestAttributeForMethod] [return: TestAttributeForReturn] get { return 0; } } public static void Main() {} } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("TestClass"); var attributeTypeForMethod = (NamedTypeSymbol)ns.GetMember("TestAttributeForMethod"); var attributeTypeForParam = (NamedTypeSymbol)ns.GetMember("TestAttributeForParam"); var attributeTypeForReturn = (NamedTypeSymbol)ns.GetMember("TestAttributeForReturn"); var property = (PropertySymbol)type.GetMember("P1"); var setter = property.SetMethod; var attrs = setter.GetAttributes(attributeTypeForMethod); Assert.Equal(1, attrs.Count()); var attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForMethod", attr.AttributeClass.ToDisplayString()); Assert.Equal(1, setter.ParameterCount); attrs = setter.Parameters[0].GetAttributes(attributeTypeForParam); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForParam", attr.AttributeClass.ToDisplayString()); attrs = setter.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, attributeTypeForReturn, TypeCompareKind.ConsiderEverything2)); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForReturn", attr.AttributeClass.ToDisplayString()); property = (PropertySymbol)type.GetMember("P2"); var getter = property.GetMethod; attrs = getter.GetAttributes(attributeTypeForMethod); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForMethod", attr.AttributeClass.ToDisplayString()); attrs = getter.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, attributeTypeForReturn, TypeCompareKind.ConsiderEverything2)); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForReturn", attr.AttributeClass.ToDisplayString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] public void TestAttributeStringForEnumTypedConstant() { var source = CreateCompilationWithMscorlib40(@" using System; namespace AttributeTest { enum X { One = 1, Two = 2, Three = 3 }; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Event, Inherited = false, AllowMultiple = true)] class A : System.Attribute { public A(X x) { } public static void Main() { } // AttributeData.ToString() should display 'X.Three' not 'X.One | X.Two' [A(X.Three)] int field; // AttributeData.ToString() should display '5' [A((X)5)] int field2; } } "); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); Assert.Equal(1, attrs.Length); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue(0, TypedConstantKind.Enum, (int)(AttributeTargets.Field | AttributeTargets.Event)); Assert.Equal(2, attr.CommonNamedArguments.Length); attr.VerifyNamedArgumentValue(0, "Inherited", TypedConstantKind.Primitive, false); attr.VerifyNamedArgumentValue(1, "AllowMultiple", TypedConstantKind.Primitive, true); Assert.Equal(@"System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Event, Inherited = false, AllowMultiple = true)", attr.ToString()); var fieldSymbol = (FieldSymbol)type.GetMember("field"); attrs = fieldSymbol.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal(@"AttributeTest.A(AttributeTest.X.Three)", attrs.First().ToString()); fieldSymbol = (FieldSymbol)type.GetMember("field2"); attrs = fieldSymbol.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal(@"AttributeTest.A(5)", attrs.First().ToString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] public void TestAttributesWithNamedConstructorArguments_01() { string source = @" using System; namespace AttributeTest { [A(y:4, z:5, X = 6)] public class A : Attribute { public int X; public A(int y, int z) { Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 4); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 5); attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6); }; string expectedOutput = @"4 5 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [Fact] public void TestAttributesWithNamedConstructorArguments_02() { string source = @" using System; namespace AttributeTest { [A(3, z:5, y:4, X = 6)] public class A : Attribute { public int X; public A(int x, int y, int z) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 3); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 4); attrs.First().VerifyValue(2, TypedConstantKind.Primitive, 5); attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6); }; string expectedOutput = @"3 4 5 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(541864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541864")] [Fact] public void Bug_8769_TestAttributesWithNamedConstructorArguments() { string source = @" using System; namespace AttributeTest { [A(y: 1, x: 2)] public class A : Attribute { public A(int x, int y) { Console.WriteLine(x); Console.WriteLine(y); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); Assert.Equal(2, attrs.First().CommonConstructorArguments.Length); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 1); Assert.Equal(0, attrs.First().CommonNamedArguments.Length); }; string expectedOutput = @"2 1 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [Fact] public void TestAttributesWithOptionalConstructorArguments_01() { string source = @" using System; namespace AttributeTest { [A(3, z:5, X = 6)] public class A : Attribute { public int X; public A(int x, int y = 4, int z = 0) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 3); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 4); attrs.First().VerifyValue(2, TypedConstantKind.Primitive, 5); attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6); }; string expectedOutput = @"3 4 5 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(541861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541861")] [Fact] public void Bug_8768_TestAttributesWithOptionalConstructorArguments() { string source = @" using System; namespace AttributeTest { [A] public class A : Attribute { public A(int x = 2) { Console.Write(x); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<int>(0, TypedConstantKind.Primitive, 2); Assert.Equal(0, attrs.First().CommonNamedArguments.Length); }; string expectedOutput = @"2"; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(541854, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541854")] [Fact] public void Bug8761_StringArrayArgument() { var source = @"using System; [A(X = new string[] { """" })] public class A : Attribute { public object[] X; static void Main() { typeof(A).GetCustomAttributes(false); } } "; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541856, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541856")] [Fact] public void Bug8763_NullInArrayInitializer() { var source = @"using System; [A(X = new object[] { null })] public class A : Attribute { public object[] X; static void Main() { typeof(A).GetCustomAttributes(false); typeof(B).GetCustomAttributes(false); } } [A(X = new object[] { typeof(int), typeof(System.Type), 1, null, ""hi"" })] public class B { public object[] X; } "; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541856, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541856")] [Fact] public void AttributeArrayTypeArgument() { var source = @"using System; [A(objArray = new string[] { ""a"", null })] public class A : Attribute { public object[] objArray; public object obj; static void Main() { typeof(A).GetCustomAttributes(false); typeof(B).GetCustomAttributes(false); typeof(C).GetCustomAttributes(false); typeof(D).GetCustomAttributes(false); typeof(E).GetCustomAttributes(false); typeof(F).GetCustomAttributes(false); typeof(G).GetCustomAttributes(false); typeof(H).GetCustomAttributes(false); typeof(I).GetCustomAttributes(false); } } [A(objArray = new object[] { ""a"", null, 3 })] public class B { } /* CS0029: Cannot implicitly convert type 'int[]' to 'object[]' [A(objArray = new int[] { 3 })] public class Error { } */ [A(objArray = null)] public class C { } [A(obj = new string[] { ""a"" })] public class D { } [A(obj = new object[] { ""a"", null, 3 })] public class E { } [A(obj = new int[] { 1 })] public class F { } [A(obj = 1)] public class G { } [A(obj = ""a"")] public class H { } [A(obj = null)] public class I { } "; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541859")] [Fact] public void Bug8766_AttributeCtorOverloadResolution() { var source = @"using System; [A(C)] public class A : Attribute { const int C = 1; A(int x) { Console.Write(""int""); } public A(long x) { Console.Write(""long""); } static void Main() { typeof(A).GetCustomAttributes(false); } } "; CompileAndVerify(source, expectedOutput: "int"); } [WorkItem(541876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541876")] [Fact] public void Bug8771_AttributeArgumentNameBinding() { var source = @"using System; public class A : Attribute { public A(int x) { Console.WriteLine(x); } } class B { const int X = 1; [A(X)] class C<[A(X)] T> { const int X = 2; } static void Main() { typeof(C<>).GetCustomAttributes(false); typeof(C<>).GetGenericArguments()[0].GetCustomAttributes(false); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol cClass = bClass.GetTypeMember("C"); NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = cClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2); var typeParameters = cClass.TypeParameters; Assert.Equal(1, typeParameters.Length); attrs = typeParameters[0].GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2); }; string expectedOutput = @"2 2 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(546380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546380")] [Fact] public void AttributeWithNestedUnboundGenericType() { var source = @"using System; using System.Collections.Generic; public class A : Attribute { public A(object o) { } } [A(typeof(B<>.C))] public class B<T> { public class C { } } public class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol cClass = bClass.GetTypeMember("C"); NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = bClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Type, cClass.AsUnboundGenericType()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [WorkItem(546380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546380")] [Fact] public void AttributeWithUnboundGenericType() { var source = @"using System; using System.Collections.Generic; public class A : Attribute { public A(object o) { } } [A(typeof(B<>))] public class B<T> { } class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = bClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Type, bClass.AsUnboundGenericType()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [WorkItem(542223, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542223")] [Fact] public void AttributeArgumentAsEnumFromMetadata() { var metadataStream1 = CSharpCompilation.Create("bar.dll", references: new[] { MscorlibRef }, syntaxTrees: new[] { Parse("public enum Bar { Baz }") }).EmitToStream(options: new EmitOptions(metadataOnly: true)); var ref1 = MetadataReference.CreateFromStream(metadataStream1); var metadataStream2 = CSharpCompilation.Create("goo.dll", references: new[] { MscorlibRef, ref1 }, syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree( "public class Ca : System.Attribute { public Ca(object o) { } } " + "[Ca(Bar.Baz)]" + "public class Goo { }") }).EmitToStream(options: new EmitOptions(metadataOnly: true)); var ref2 = MetadataReference.CreateFromStream(metadataStream2); var compilation = CSharpCompilation.Create("moo.dll", references: new[] { MscorlibRef, ref1, ref2 }); var goo = compilation.GetTypeByMetadataName("Goo"); var ca = goo.GetAttributes().First().CommonConstructorArguments.First(); Assert.Equal("Bar", ca.Type.Name); } [WorkItem(542318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542318")] [Fact] public void AttributeWithDaysOfWeekArgument() { // DELIBERATE SPEC VIOLATION: // // Object creation expressions like "new int()" are not considered constant expressions // by the specification but they are by the native compiler; we maintain compatibility // with this bug. // // Additionally, it also treats "new X()", where X is an enum type, as a // constant expression with default value 0, we maintaining compatibility with it. var source = @"using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] [A(X = new DayOfWeek())] [A(X = new bool())] [A(X = new sbyte())] [A(X = new byte())] [A(X = new short())] [A(X = new ushort())] [A(X = new int())] [A(X = new uint())] [A(X = new char())] [A(X = new float())] [A(X = new Single())] [A(X = new double())] public class A : Attribute { public object X; const DayOfWeek dayofweek = new DayOfWeek(); const bool b = new bool(); const sbyte sb = new sbyte(); const byte by = new byte(); const short s = new short(); const ushort us = new ushort(); const int i = new int(); const uint ui = new uint(); const char c = new char(); const float f = new float(); const Single si = new Single(); const double d = new double(); public static void Main() { typeof(A).GetCustomAttributes(false); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = attributeType.GetAttributes(attributeType); Assert.Equal(12, attrs.Count()); var enumerator = attrs.GetEnumerator(); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Enum, (int)new DayOfWeek()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new bool()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new sbyte()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new byte()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new short()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new ushort()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new int()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new uint()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new char()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new float()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new Single()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new double()); }; string expectedOutput = ""; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(542534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542534")] [Fact] public void AttributeOnDefiningPartialMethodDeclaration() { var source = @" using System; class A : Attribute { } partial class Program { [A] static partial void Goo(); static partial void Goo() { } static void Main() { Console.WriteLine(((Action) Goo).Method.GetCustomAttributesData().Count); } } "; CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(542534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542534")] [Fact] public void AttributeOnDefiningPartialMethodDeclaration_02() { var source1 = @" using System; class A1 : Attribute {} class B1 : Attribute {} class C1 : Attribute {} class D1 : Attribute {} class E1 : Attribute {} partial class Program { [A1] [return: B1] static partial void Goo<[C1] T, [D1] U>([E1]int x); } "; var source2 = @" using System; class A2 : Attribute {} class B2 : Attribute {} class C2 : Attribute {} class D2 : Attribute {} class E2 : Attribute {} partial class Program { [A2] [return: B2] static partial void Goo<[C2] U, [D2] T>([E2]int y) { } static void Main() {} } "; var compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var programClass = m.GlobalNamespace.GetTypeMember("Program"); var gooMethod = (MethodSymbol)programClass.GetMember("Goo"); TestAttributeOnPartialMethodHelper(m, gooMethod); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } private void TestAttributeOnPartialMethodHelper(ModuleSymbol m, MethodSymbol gooMethod) { var a1Class = m.GlobalNamespace.GetTypeMember("A1"); var a2Class = m.GlobalNamespace.GetTypeMember("A2"); var b1Class = m.GlobalNamespace.GetTypeMember("B1"); var b2Class = m.GlobalNamespace.GetTypeMember("B2"); var c1Class = m.GlobalNamespace.GetTypeMember("C1"); var c2Class = m.GlobalNamespace.GetTypeMember("C2"); var d1Class = m.GlobalNamespace.GetTypeMember("D1"); var d2Class = m.GlobalNamespace.GetTypeMember("D2"); var e1Class = m.GlobalNamespace.GetTypeMember("E1"); var e2Class = m.GlobalNamespace.GetTypeMember("E2"); Assert.Equal(1, gooMethod.GetAttributes(a1Class).Count()); Assert.Equal(1, gooMethod.GetAttributes(a2Class).Count()); Assert.Equal(1, gooMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, b1Class, TypeCompareKind.ConsiderEverything2)).Count()); Assert.Equal(1, gooMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, b2Class, TypeCompareKind.ConsiderEverything2)).Count()); var typeParam1 = gooMethod.TypeParameters[0]; Assert.Equal(1, typeParam1.GetAttributes(c1Class).Count()); Assert.Equal(1, typeParam1.GetAttributes(c2Class).Count()); var typeParam2 = gooMethod.TypeParameters[1]; Assert.Equal(1, typeParam2.GetAttributes(d1Class).Count()); Assert.Equal(1, typeParam2.GetAttributes(d2Class).Count()); var param = gooMethod.Parameters[0]; Assert.Equal(1, param.GetAttributes(e1Class).Count()); Assert.Equal(1, param.GetAttributes(e2Class).Count()); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void AttributesInMultiplePartialDeclarations_Type() { var source1 = @" using System; class A : Attribute {} [A] partial class X {}"; var source2 = @" using System; class B : Attribute {} [B] partial class X {} class C { public static void Main() { typeof(X).GetCustomAttributes(false); } }"; var compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var aClass = m.GlobalNamespace.GetTypeMember("A"); var bClass = m.GlobalNamespace.GetTypeMember("B"); var type = m.GlobalNamespace.GetTypeMember("X"); Assert.Equal(2, type.GetAttributes().Length); Assert.Equal(1, type.GetAttributes(aClass).Count()); Assert.Equal(1, type.GetAttributes(bClass).Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void AttributesInMultiplePartialDeclarations_TypeParam() { var source1 = @" using System; class A : Attribute {} partial class Gen<[A] T> {}"; var source2 = @" using System; class B : Attribute {} partial class Gen<[B] T> {} class C { public static void Main() {} }"; var compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var aClass = m.GlobalNamespace.GetTypeMember("A"); var bClass = m.GlobalNamespace.GetTypeMember("B"); var type = m.GlobalNamespace.GetTypeMember("Gen"); var typeParameter = type.TypeParameters.First(); Assert.Equal(2, typeParameter.GetAttributes().Length); Assert.Equal(1, typeParameter.GetAttributes(aClass).Count()); Assert.Equal(1, typeParameter.GetAttributes(bClass).Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } [WorkItem(542550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542550")] [Fact] public void Bug9824() { var source = @" using System; public class TAttribute : Attribute { public static void Main () {} } [T] public class GClass<T> where T : Attribute { [T] public enum E { } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("TAttribute"); NamedTypeSymbol GClass = m.GlobalNamespace.GetTypeMember("GClass").AsUnboundGenericType(); Assert.Equal(1, GClass.GetAttributes(attributeType).Count()); NamedTypeSymbol enumE = GClass.GetTypeMember("E"); Assert.Equal(1, enumE.GetAttributes(attributeType).Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(543135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543135")] [Fact] public void AttributeAndDefaultValueArguments_01() { var source = @" using System; [A] public class A : Attribute { public A(object a = default(A)) { } } [A(1)] class C { public static void Main() { typeof(C).GetCustomAttributes(false); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); NamedTypeSymbol cClass = m.GlobalNamespace.GetTypeMember("C"); var attrs = attributeType.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); attrs = cClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<int>(0, TypedConstantKind.Primitive, 1); }; string expectedOutput = ""; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(543135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543135")] [Fact] public void AttributeAndDefaultValueArguments_02() { var source = @" using System; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class A : System.Attribute { public A(object o = null) { } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class B : System.Attribute { public B(object o = default(B)) { } } [A] [A(null)] [B] [B(default(B))] class C { public static void Main() { typeof(C).GetCustomAttributes(false); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeTypeA = m.GlobalNamespace.GetTypeMember("A"); NamedTypeSymbol attributeTypeB = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol cClass = m.GlobalNamespace.GetTypeMember("C"); // Verify A attributes var attrs = cClass.GetAttributes(attributeTypeA); Assert.Equal(2, attrs.Count()); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); attr = attrs.ElementAt(1); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); // Verify B attributes attrs = cClass.GetAttributes(attributeTypeB); Assert.Equal(2, attrs.Count()); attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); attr = attrs.ElementAt(1); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); }; string expectedOutput = ""; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(529044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529044")] [Fact] public void AttributeNameLookup() { var source = @" using System; public class MyClass<T> { } public class MyClassAttribute : Attribute { } [MyClass] public class Test { public static void Main() { typeof(Test).GetCustomAttributes(false); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("MyClassAttribute"); NamedTypeSymbol testClass = m.GlobalNamespace.GetTypeMember("Test"); // Verify attributes var attrs = testClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } [WorkItem(542003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542003")] [Fact] public void Bug8956_NullArgumentToSystemTypeParam() { string source = @" using System; class A : Attribute { public A(System.Type t) {} } [A(null)] class Test { static void Main(string[] args) { typeof(Test).GetCustomAttributes(false); } } "; CompileAndVerify(source); } [Fact] public void SpecialNameAttributeFromSource() { string source = @" using System; using System.Runtime.CompilerServices; [SpecialName()] public struct S { [SpecialName] byte this[byte x] { get { return x; } } [SpecialName] public event Action<string> E; } "; var comp = CreateCompilation(source); var global = comp.SourceModule.GlobalNamespace; var typesym = global.GetMember("S") as NamedTypeSymbol; Assert.NotNull(typesym); Assert.True(typesym.HasSpecialName); var idxsym = typesym.GetMember(WellKnownMemberNames.Indexer) as PropertySymbol; Assert.NotNull(idxsym); Assert.True(idxsym.HasSpecialName); var etsym = typesym.GetMember("E") as EventSymbol; Assert.NotNull(etsym); Assert.True(etsym.HasSpecialName); } [WorkItem(546277, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546277")] [Fact] public void TestArrayTypeInAttributeArgument() { var source = @"using System; public class W {} public class Y<T> { public class F {} public class Z<U> {} } public class X : Attribute { public X(Type y) { } } [X(typeof(W[]))] public class C1 {} [X(typeof(W[,]))] public class C2 {} [X(typeof(W[,][]))] public class C3 {} [X(typeof(Y<W>[][,]))] public class C4 {} [X(typeof(Y<int>.F[,][][,,]))] public class C5 {} [X(typeof(Y<int>.Z<W>[,][]))] public class C6 {} "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol classW = m.GlobalNamespace.GetTypeMember("W"); NamedTypeSymbol classY = m.GlobalNamespace.GetTypeMember("Y"); NamedTypeSymbol classF = classY.GetTypeMember("F"); NamedTypeSymbol classZ = classY.GetTypeMember("Z"); NamedTypeSymbol classX = m.GlobalNamespace.GetTypeMember("X"); NamedTypeSymbol classC1 = m.GlobalNamespace.GetTypeMember("C1"); NamedTypeSymbol classC2 = m.GlobalNamespace.GetTypeMember("C2"); NamedTypeSymbol classC3 = m.GlobalNamespace.GetTypeMember("C3"); NamedTypeSymbol classC4 = m.GlobalNamespace.GetTypeMember("C4"); NamedTypeSymbol classC5 = m.GlobalNamespace.GetTypeMember("C5"); NamedTypeSymbol classC6 = m.GlobalNamespace.GetTypeMember("C6"); var attrs = classC1.GetAttributes(); Assert.Equal(1, attrs.Length); var typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classW)); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC2.GetAttributes(); Assert.Equal(1, attrs.Length); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classW), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC3.GetAttributes(); Assert.Equal(1, attrs.Length); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classW)); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC4.GetAttributes(); Assert.Equal(1, attrs.Length); NamedTypeSymbol classYOfW = classY.ConstructIfGeneric(ImmutableArray.Create(TypeWithAnnotations.Create(classW))); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classYOfW), rank: 2); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg)); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC5.GetAttributes(); Assert.Equal(1, attrs.Length); NamedTypeSymbol classYOfInt = classY.ConstructIfGeneric(ImmutableArray.Create(TypeWithAnnotations.Create(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)))); NamedTypeSymbol substNestedF = classYOfInt.GetTypeMember("F"); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(substNestedF), rank: 3); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg)); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC6.GetAttributes(); Assert.Equal(1, attrs.Length); NamedTypeSymbol substNestedZ = classYOfInt.GetTypeMember("Z").ConstructIfGeneric(ImmutableArray.Create(TypeWithAnnotations.Create(classW))); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(substNestedZ)); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [WorkItem(546621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546621")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void TestUnicodeAttributeArgument_Bug16353() { var source = @"using System; [Obsolete(UnicodeHighSurrogate)] class C { public const string UnicodeHighSurrogate = ""\uD800""; public const string UnicodeReplacementCharacter = ""\uFFFD""; static void Main() { string message = ((ObsoleteAttribute)typeof(C).GetCustomAttributes(false)[0]).Message; Console.WriteLine(message == UnicodeReplacementCharacter + UnicodeReplacementCharacter); } }"; CompileAndVerify(source, expectedOutput: "True"); } [WorkItem(546621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546621")] [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/41280")] public void TestUnicodeAttributeArgumentsStrings() { string HighSurrogateCharacter = "\uD800"; string LowSurrogateCharacter = "\uDC00"; string UnicodeReplacementCharacter = "\uFFFD"; string UnicodeLT0080 = "\u007F"; string UnicodeLT0800 = "\u07FF"; string UnicodeLT10000 = "\uFFFF"; string source = @" using System; public class C { public const string UnicodeSurrogate1 = ""\uD800""; public const string UnicodeSurrogate2 = ""\uD800\uD800""; public const string UnicodeSurrogate3 = ""\uD800\uDC00""; public const string UnicodeSurrogate4 = ""\uD800\u07FF\uD800""; public const string UnicodeSurrogate5 = ""\uD800\u007F\uDC00""; public const string UnicodeSurrogate6 = ""\uD800\u07FF\uDC00""; public const string UnicodeSurrogate7 = ""\uD800\uFFFF\uDC00""; public const string UnicodeSurrogate8 = ""\uD800\uD800\uDC00""; public const string UnicodeSurrogate9 = ""\uDC00\uDC00""; [Obsolete(UnicodeSurrogate1)] public int x1; [Obsolete(UnicodeSurrogate2)] public int x2; [Obsolete(UnicodeSurrogate3)] public int x3; [Obsolete(UnicodeSurrogate4)] public int x4; [Obsolete(UnicodeSurrogate5)] public int x5; [Obsolete(UnicodeSurrogate6)] public int x6; [Obsolete(UnicodeSurrogate7)] public int x7; [Obsolete(UnicodeSurrogate8)] public int x8; [Obsolete(UnicodeSurrogate9)] public int x9; } "; Action<FieldSymbol, string> VerifyAttributes = (field, value) => { var attributes = field.GetAttributes(); Assert.Equal(1, attributes.Length); attributes[0].VerifyValue(0, TypedConstantKind.Primitive, value); }; Func<bool, Action<ModuleSymbol>> validator = isFromSource => (ModuleSymbol module) => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var x1 = type.GetMember<FieldSymbol>("x1"); var x2 = type.GetMember<FieldSymbol>("x2"); var x3 = type.GetMember<FieldSymbol>("x3"); var x4 = type.GetMember<FieldSymbol>("x4"); var x5 = type.GetMember<FieldSymbol>("x5"); var x6 = type.GetMember<FieldSymbol>("x6"); var x7 = type.GetMember<FieldSymbol>("x7"); var x8 = type.GetMember<FieldSymbol>("x8"); var x9 = type.GetMember<FieldSymbol>("x9"); // public const string UnicodeSurrogate1 = ""\uD800""; VerifyAttributes(x1, isFromSource ? HighSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate2 = ""\uD800\uD800""; VerifyAttributes(x2, isFromSource ? HighSurrogateCharacter + HighSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate3 = ""\uD800\uDC00""; VerifyAttributes(x3, HighSurrogateCharacter + LowSurrogateCharacter); // public const string UnicodeSurrogate4 = ""\uD800\u07FF\uD800""; VerifyAttributes(x4, isFromSource ? HighSurrogateCharacter + UnicodeLT0800 + HighSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0800 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate5 = ""\uD800\u007F\uDC00""; VerifyAttributes(x5, isFromSource ? HighSurrogateCharacter + UnicodeLT0080 + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0080 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate6 = ""\uD800\u07FF\uDC00""; VerifyAttributes(x6, isFromSource ? HighSurrogateCharacter + UnicodeLT0800 + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0800 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate7 = ""\uD800\uFFFF\uDC00""; VerifyAttributes(x7, isFromSource ? HighSurrogateCharacter + UnicodeLT10000 + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT10000 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate8 = ""\uD800\uD800\uDC00""; VerifyAttributes(x8, isFromSource ? HighSurrogateCharacter + HighSurrogateCharacter + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + HighSurrogateCharacter + LowSurrogateCharacter); // public const string UnicodeSurrogate9 = ""\uDC00\uDC00""; VerifyAttributes(x9, isFromSource ? LowSurrogateCharacter + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter); }; CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] [WorkItem(546896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546896")] public void MissingTypeInSignature() { string lib1 = @" public enum E { A, B, C } "; string lib2 = @" public class A : System.Attribute { public A(E e) { } } public class C { [A(E.A)] public void M() { } } "; string main = @" class D : C { void N() { M(); } } "; var c1 = CreateCompilation(lib1); var r1 = c1.EmitToImageReference(); var c2 = CreateCompilation(lib2, references: new[] { r1 }); var r2 = c2.EmitToImageReference(); var cm = CreateCompilation(main, new[] { r2 }); cm.VerifyDiagnostics(); var model = cm.GetSemanticModel(cm.SyntaxTrees[0]); int index = main.IndexOf("M()", StringComparison.Ordinal); var m = (ExpressionSyntax)cm.SyntaxTrees[0].GetCompilationUnitRoot().FindToken(index).Parent.Parent; var info = model.GetSymbolInfo(m); var args = info.Symbol.GetAttributes()[0].CommonConstructorArguments; // unresolved type - parameter ignored Assert.Equal(0, args.Length); } [Fact] [WorkItem(569089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569089")] public void NullArrays() { var source = @" using System; public class A : Attribute { public A(object[] a, int[] b) { } public object[] P { get; set; } public int[] F; } [A(null, null, P = null, F = null)] class C { } "; CompileAndVerify(source, symbolValidator: (m) => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var attr = c.GetAttributes().Single(); var args = attr.ConstructorArguments.ToArray(); Assert.True(args[0].IsNull); Assert.Equal("object[]", args[0].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => args[0].Value); Assert.True(args[1].IsNull); Assert.Equal("int[]", args[1].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => args[1].Value); var named = attr.NamedArguments.ToDictionary(e => e.Key, e => e.Value); Assert.True(named["P"].IsNull); Assert.Equal("object[]", named["P"].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => named["P"].Value); Assert.True(named["F"].IsNull); Assert.Equal("int[]", named["F"].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => named["F"].Value); }); } [Fact] public void NullTypeAndString() { var source = @" using System; public class A : Attribute { public A(Type t, string s) { } } [A(null, null)] class C { } "; CompileAndVerify(source, symbolValidator: (m) => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var attr = c.GetAttributes().Single(); var args = attr.ConstructorArguments.ToArray(); Assert.Null(args[0].Value); Assert.Equal("Type", args[0].Type.Name); Assert.Throws<InvalidOperationException>(() => args[0].Values); Assert.Null(args[1].Value); Assert.Equal("String", args[1].Type.Name); Assert.Throws<InvalidOperationException>(() => args[1].Values); }); } [WorkItem(121, "https://github.com/dotnet/roslyn/issues/121")] [Fact] public void Bug_AttributeOnWrongGenericParameter() { var source = @" using System; class XAttribute : Attribute { } class C<T> { public void M<[X]U>() { } } "; CompileAndVerify(source, symbolValidator: module => { var @class = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var classTypeParameter = @class.TypeParameters.Single(); var method = @class.GetMember<MethodSymbol>("M"); var methodTypeParameter = method.TypeParameters.Single(); Assert.Empty(classTypeParameter.GetAttributes()); var attribute = methodTypeParameter.GetAttributes().Single(); Assert.Equal("XAttribute", attribute.AttributeClass.Name); }); } #endregion #region Error Tests [Fact] public void AttributeConstructorErrors1() { var compilation = CreateCompilationWithMscorlib40AndSystemCore(@" using System; static class m { public static int NotAConstant() { return 9; } } public enum e1 { a } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class XAttribute : Attribute { public XAttribute() { } public XAttribute(decimal d) { } public XAttribute(ref int i) { } public XAttribute(e1 e) { } } [XDoesNotExist()] [X(1m)] [X(1)] [X(e1.a)] [X(A.dyn)] [X(m.NotAConstant() + 2)] class A { public const dynamic dyn = null; } ", options: TestOptions.ReleaseDll); // Note that the dev11 compiler produces errors that XDoesNotExist *and* XDoesNotExistAttribute could not be found. // It does not go on to produce the other errors. compilation.VerifyDiagnostics( // (33,2): error CS0246: The type or namespace name 'XDoesNotExistAttribute' could not be found (are you missing a using directive or an assembly reference?) // [XDoesNotExist()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "XDoesNotExist").WithArguments("XDoesNotExistAttribute").WithLocation(33, 2), // (33,2): error CS0246: The type or namespace name 'XDoesNotExist' could not be found (are you missing a using directive or an assembly reference?) // [XDoesNotExist()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "XDoesNotExist").WithArguments("XDoesNotExist").WithLocation(33, 2), // (34,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type // [X(1m)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(34, 2), // (35,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type // [X(1)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(35, 2), // (37,2): error CS0121: The call is ambiguous between the following methods or properties: 'XAttribute.XAttribute(ref int)' and 'XAttribute.XAttribute(e1)' // [X(A.dyn)] Diagnostic(ErrorCode.ERR_AmbigCall, "X(A.dyn)").WithArguments("XAttribute.XAttribute(ref int)", "XAttribute.XAttribute(e1)").WithLocation(37, 2), // (38,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type // [X(m.NotAConstant() + 2)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(38, 2)); } [Fact] public void AttributeNamedArgumentErrors1() { var compilation = CreateCompilation(@" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class XAttribute : Attribute { public void F1(int i) { } private int PrivateField; public static int SharedProperty { get; set; } public int? ReadOnlyProperty { get { return null; } } public decimal BadDecimalType { get; set; } public System.DateTime BadDateType { get; set; } public Attribute[] BadArrayType { get; set; } } [X(NotFound = null)] [X(F1 = null)] [X(PrivateField = null)] [X(SharedProperty = null)] [X(ReadOnlyProperty = null)] [X(BadDecimalType = null)] [X(BadDateType = null)] [X(BadArrayType = null)] class A { } ", options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (21,4): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // [X(NotFound = null)] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound"), // (22,4): error CS0617: 'F1' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [X(F1 = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "F1").WithArguments("F1"), // (23,4): error CS0122: 'XAttribute.PrivateField' is inaccessible due to its protection level // [X(PrivateField = null)] Diagnostic(ErrorCode.ERR_BadAccess, "PrivateField").WithArguments("XAttribute.PrivateField"), // (24,4): error CS0617: 'SharedProperty' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [X(SharedProperty = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "SharedProperty").WithArguments("SharedProperty"), // (25,4): error CS0617: 'ReadOnlyProperty' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [X(ReadOnlyProperty = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "ReadOnlyProperty").WithArguments("ReadOnlyProperty"), // (26,4): error CS0655: 'BadDecimalType' is not a valid named attribute argument because it is not a valid attribute parameter type // [X(BadDecimalType = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadDecimalType").WithArguments("BadDecimalType"), // (27,4): error CS0655: 'BadDateType' is not a valid named attribute argument because it is not a valid attribute parameter type // [X(BadDateType = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadDateType").WithArguments("BadDateType"), // (28,4): error CS0655: 'BadArrayType' is not a valid named attribute argument because it is not a valid attribute parameter type // [X(BadArrayType = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadArrayType").WithArguments("BadArrayType")); } [Fact] public void AttributeNoMultipleAndInvalidTarget() { string source = @" using CustomAttribute; [Base(1)] [@BaseAttribute(""SOS"")] static class AttributeMod { [Derived('Q')] [Derived('C')] public class Goo { } [BaseAttribute(1)] [Base("""")] public class Bar { } }"; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); compilation.VerifyDiagnostics( // (4,2): error CS0579: Duplicate 'BaseAttribute' attribute // [@BaseAttribute("SOS")] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "@BaseAttribute").WithArguments("BaseAttribute").WithLocation(4, 2), // (7,6): error CS0592: Attribute 'Derived' is not valid on this declaration type. It is only valid on 'struct, method, parameter' declarations. // [Derived('Q')] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Derived").WithArguments("Derived", "struct, method, parameter").WithLocation(7, 6), // (8,6): error CS0579: Duplicate 'Derived' attribute // [Derived('C')] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Derived").WithArguments("Derived").WithLocation(8, 6), // (13,6): error CS0579: Duplicate 'Base' attribute // [Base("")] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Base").WithArguments("Base").WithLocation(13, 6)); } [Fact] public void AttributeAmbiguousSpecification() { string source = @" using System; [AttributeUsage(AttributeTargets.All)] public class X : Attribute {} [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } [X] // Error: Ambiguous class Class1 { } [XAttribute] // Refers to XAttribute class Class2 { } [@X] // Refers to X class Class3 { } [@XAttribute] // Refers to XAttribute class Class4 { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,2): error CS1614: 'X' is ambiguous between 'X' and 'XAttribute'; use either '@X' or 'XAttribute' // [X] // Error: Ambiguous Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "X").WithArguments("X", "X", "XAttribute").WithLocation(10, 2)); } [Fact] public void AttributeErrorVerbatimIdentifierInSpecification() { string source = @" using System; [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } [X] // Refers to X class Class1 { } [XAttribute] // Refers to XAttribute class Class2 { } [@X] // Error: No attribute named X class Class3 { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (13,2): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // [@X] // Error: No attribute named X Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "@X").WithArguments("X").WithLocation(13, 2)); } [Fact] public void AttributeOpenTypeInAttribute() { string source = @" using System; using System.Collections.Generic; [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { public XAttribute(Type t) { } } class G<T> { [X(typeof(T))] T t1; // Error: open type in attribute [X(typeof(List<T>))] T t2; // Error: open type in attribute } class X { [X(typeof(List<int>))] int x; // okay: X refers to XAttribute and List<int> is a closed constructed type [X(typeof(List<>))] int y; // okay: X refers to XAttribute and List<> is an unbound generic type } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (13,8): error CS0416: 'T': an attribute argument cannot use type parameters // [X(typeof(T))] T t1; // Error: open type in attribute Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(T)").WithArguments("T"), // (14,8): error CS0416: 'System.Collections.Generic.List<T>': an attribute argument cannot use type parameters // [X(typeof(List<T>))] T t2; // Error: open type in attribute Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(List<T>)").WithArguments("System.Collections.Generic.List<T>"), // (13,22): warning CS0169: The field 'G<T>.t1' is never used // [X(typeof(T))] T t1; // Error: open type in attribute Diagnostic(ErrorCode.WRN_UnreferencedField, "t1").WithArguments("G<T>.t1"), // (14,28): warning CS0169: The field 'G<T>.t2' is never used // [X(typeof(List<T>))] T t2; // Error: open type in attribute Diagnostic(ErrorCode.WRN_UnreferencedField, "t2").WithArguments("G<T>.t2"), // (19,32): warning CS0169: The field 'X.x' is never used // [X(typeof(List<int>))] int x; // okay: X refers to XAttribute and List<int> is a closed constructed type Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("X.x"), // (20,29): warning CS0169: The field 'X.y' is never used // [X(typeof(List<>))] int y; // okay: X refers to XAttribute and List<> is an unbound generic type Diagnostic(ErrorCode.WRN_UnreferencedField, "y").WithArguments("X.y") ); } [WorkItem(540924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540924")] [Fact] public void AttributeEnumsAsAttributeParameters() { string source = @" using System; class EClass { public enum EEK { a, b, c, d }; } [AttributeUsage(AttributeTargets.Class)] internal class HelpAttribute : Attribute { public HelpAttribute(EClass.EEK[] b1) { } } [HelpAttribute(new EClass.EEK[2] { EClass.EEK.b, EClass.EEK.c })] public class MainClass { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); } [WorkItem(768798, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768798")] [Fact(Skip = "768798")] public void AttributeInvalidTargetSpecifier() { string source = @" using System; // Below attribute specification generates a warning regarding invalid target specifier, // We skip binding the attribute with invalid target specifier, // no error generated for invalid use of AttributeUsage on non attribute class. [method: AttributeUsage(AttributeTargets.All)] class X { public static void Main() {} } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type")); } [WorkItem(768798, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768798")] [Fact(Skip = "768798")] public void AttributeInvalidTargetSpecifierOnInvalidAttribute() { string source = @" [method: OopsForgotToBindThis(Haha)] class X { public static void Main() {} } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(/*CS0657, CS0246*/); } [Fact] public void AttributeUsageMultipleErrors() { string source = @"using System; class A { [AttributeUsage(AttributeTargets.Method)] void M1() { } [AttributeUsage(0)] void M2() { } } [AttributeUsage(0)] class B { }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,6): error CS0592: Attribute 'AttributeUsage' is not valid on this declaration type. It is only valid on 'class' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "AttributeUsage").WithArguments("AttributeUsage", "class").WithLocation(4, 6), // (6,6): error CS0592: Attribute 'AttributeUsage' is not valid on this declaration type. It is only valid on 'class' declarations. // [AttributeUsage(0)] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "AttributeUsage").WithArguments("AttributeUsage", "class").WithLocation(6, 6), // (9,2): error CS0641: Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute Diagnostic(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, "AttributeUsage").WithArguments("AttributeUsage").WithLocation(9, 2)); } [Fact] public void CS0643ERR_DuplicateNamedAttributeArgument02() { string source = @" using System; [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] class MyAtt : Attribute { } [MyAtt] public class Test { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (3,39): error CS0643: 'AllowMultiple' duplicate named attribute argument // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_DuplicateNamedAttributeArgument, "AllowMultiple = false").WithArguments("AllowMultiple").WithLocation(3, 39), // (3,2): error CS7036: There is no argument given that corresponds to the required formal parameter 'validOn' of 'AttributeUsageAttribute.AttributeUsageAttribute(AttributeTargets)' // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AttributeUsage(AllowMultiple = true, AllowMultiple = false)").WithArguments("validOn", "System.AttributeUsageAttribute.AttributeUsageAttribute(System.AttributeTargets)").WithLocation(3, 2) ); } [WorkItem(541059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541059")] [Fact] public void AttributeUsageIsNull() { string source = @" using System; [AttributeUsage(null)] public class Att1 : Attribute { } public class Goo { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "System.AttributeTargets")); } [WorkItem(541072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541072")] [Fact] public void AttributeContainsGeneric() { string source = @" [Goo<int>] class G { } class Goo<T> { } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2), // (2,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Goo<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Goo<int>").WithArguments("generic attributes").WithLocation(2, 2)); compilation = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2)); } /// <summary> /// Bug 7620: System.Nullreference Exception throws while the value of parameter AttributeUsage Is Null /// </summary> [Fact] public void CS1502ERR_NullAttributeUsageArgument() { string source = @" using System; [AttributeUsage(null)] public class Attr : Attribute { } public class Goo { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,17): error CS1503: Argument 1: cannot convert from '<null>' to 'System.AttributeTargets' // [AttributeUsage(null)] Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "System.AttributeTargets")); } /// <summary> /// Bug 7632: Debug.Assert() Failure while Attribute Contains Generic /// </summary> [Fact] public void CS0404ERR_GenericAttributeError() { string source = @" [Goo<int>] class G { } class Goo<T> { } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2), // (2,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Goo<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Goo<int>").WithArguments("generic attributes").WithLocation(2, 2)); compilation = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2)); } [WorkItem(541423, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541423")] [Fact] public void ErrorsInMultipleSyntaxTrees() { var source1 = @"using System; [module: A] [AttributeUsage(AttributeTargets.Class)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { }"; var source2 = @"[module: B]"; var compilation = CreateCompilation(new[] { source1, source2 }); compilation.VerifyDiagnostics( // (2,10): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'class' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "class").WithLocation(2, 10), // (1,10): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(1, 10)); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void ErrorsInMultipleSyntaxTrees_TypeParam() { var source1 = @"using System; [AttributeUsage(AttributeTargets.Class)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { } class Gen<[A] T> {} "; var source2 = @"class Gen2<[B] T> {}"; var compilation = CreateCompilation(new[] { source1, source2 }); compilation.VerifyDiagnostics( // (11,12): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'class' declarations. // class Gen<[A] T> {} Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "class").WithLocation(11, 12), // (1,13): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. // class Gen2<[B] T> {} Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(1, 13)); } [WorkItem(541423, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541423")] [Fact] public void ErrorsInMultiplePartialDeclarations() { var source = @"using System; [AttributeUsage(AttributeTargets.Struct)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { } [A] partial class C { } [B] partial class C { }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,2): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'struct' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "struct").WithLocation(10, 2), // (14,2): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(14, 2)); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void ErrorsInMultiplePartialDeclarations_TypeParam() { var source = @"using System; [AttributeUsage(AttributeTargets.Struct)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { } partial class Gen<[A] T> { } partial class Gen<[B] T> { }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,20): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'struct' declarations. // partial class Gen<[A] T> Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "struct").WithLocation(11, 20), // (14,20): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. // partial class Gen<[B] T> Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(14, 20)); } [WorkItem(541505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541505")] [Fact] public void AttributeArgumentError_CS0120() { var source = @"using System; class A : Attribute { public A(ProtectionLevel p){} } enum ProtectionLevel { Privacy = 0 } class F { int ProtectionLevel; [A(ProtectionLevel.Privacy)] public int test; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (16,6): error CS0120: An object reference is required for the non-static field, method, or property 'F.ProtectionLevel' // [A(ProtectionLevel.Privacy)] Diagnostic(ErrorCode.ERR_ObjectRequired, "ProtectionLevel").WithArguments("F.ProtectionLevel"), // (14,7): warning CS0169: The field 'F.ProtectionLevel' is never used // int ProtectionLevel; Diagnostic(ErrorCode.WRN_UnreferencedField, "ProtectionLevel").WithArguments("F.ProtectionLevel"), // (17,14): warning CS0649: Field 'F.test' is never assigned to, and will always have its default value 0 // public int test; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "test").WithArguments("F.test", "0") ); } [Fact, WorkItem(541427, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541427")] public void AttributeTargetsString() { var source = @" using System; [AttributeUsage(AttributeTargets.All & ~AttributeTargets.Class)] class A : Attribute { } [A] class C { } "; CreateCompilation(source).VerifyDiagnostics( // (3,2): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'assembly, module, struct, enum, constructor, method, property, indexer, field, event, interface, parameter, delegate, return, type parameter' declarations. // [A] class C { } Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "assembly, module, struct, enum, constructor, method, property, indexer, field, event, interface, parameter, delegate, return, type parameter") ); } [Fact] public void AttributeTargetsAssemblyModule() { var source = @" using System; [module: Attr()] [AttributeUsage(AttributeTargets.Assembly)] class Attr: Attribute { public Attr(){} }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (3,10): error CS0592: Attribute 'Attr' is not valid on this declaration type. It is only valid on 'assembly' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Attr").WithArguments("Attr", "assembly")); } [WorkItem(541259, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541259")] [Fact] public void CS0182_NonConstantArrayCreationAttributeArgument() { var source = @"using System; [A(new int[1] {Program.f})] // error [A(new int[1])] // error [A(new int[1,1])] // error [A(new int[1 - 1])] // OK create an empty array [A(new A[0])] // error class Program { static public int f = 10; public static void Main() { typeof(Program).GetCustomAttributes(false); } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class A : Attribute { public A(object x) { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (3,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[1] {Program.f})] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "Program.f"), // (4,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[1])] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[1]"), // (5,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[1,1])] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[1,1]"), // (7,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new A[0])] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new A[0]")); } [WorkItem(541753, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541753")] [Fact] public void CS0182_NestedArrays() { var source = @" using System; [A(new int[][] { new int[] { 1 } })] class Program { static void Main() { typeof(Program).GetCustomAttributes(false); } } class A : Attribute { public A(object x) { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[][] { new int[] { 1 } })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[][] { new int[] { 1 } }").WithLocation(4, 4)); } [WorkItem(541849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541849")] [Fact] public void CS0182_MultidimensionalArrays() { var source = @"using System; class MyAttribute : Attribute { public MyAttribute(params int[][,] x) { } } [My] class Program { static void Main() { typeof(Program).GetCustomAttributes(false); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (8,2): error CS0181: Attribute constructor parameter 'x' has type 'int[][*,*]', which is not a valid attribute parameter type // [My] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("x", "int[][*,*]").WithLocation(8, 2)); } [WorkItem(541858, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541858")] [Fact] public void AttributeDefaultValueArgument() { var source = @"using System; namespace AttributeTest { [A(3, X = 6)] public class A : Attribute { public int X; public A(int x, int y = 4, object a = default(A)) { } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541858, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541858")] [Fact] public void CS0416_GenericAttributeDefaultValueArgument() { var source = @"using System; public class A : Attribute { public object X; static void Main() { typeof(C<int>.E).GetCustomAttributes(false); } } public class C<T> { [A(X = default(E))] public enum E { } [A(X = typeof(E2))] public enum E2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (14,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = default(E))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(14, 12), // (17,12): error CS0416: 'C<T>.E2': an attribute argument cannot use type parameters // [A(X = typeof(E2))] Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(E2)").WithArguments("C<T>.E2").WithLocation(17, 12)); } [WorkItem(541615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541615")] [Fact] public void CS0246_VarAttributeIdentifier() { var source = @" [var()] class Program { public static void Main() {} } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (2,2): error CS0246: The type or namespace name 'varAttribute' could not be found (are you missing a using directive or an assembly reference?) // [var()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "var").WithArguments("varAttribute").WithLocation(2, 2), // (2,2): error CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?) // [var()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "var").WithArguments("var").WithLocation(2, 2)); } [Fact] public void TestAttributesWithInvalidArgumentsOrder() { string source = @" using System; namespace AttributeTest { [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] [A(3, z: 5, X = 6, y: 1)] [A(3, z: 5, 1)] [A(3, 1, X = 6, z: 5)] [A(X = 6, 0)] [A(X = 6, x: 0)] public class A : Attribute { public int X; public A(int x, int y = 4, int z = 0) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } public class B { } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics( // (7,27): error CS1016: Named attribute argument expected // [A(3, z: 5, X = 6, y: 1)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "1").WithLocation(7, 27), // (8,17): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // [A(3, z: 5, 1)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "1").WithArguments("7.2").WithLocation(8, 17), // (8,11): error CS8321: Named argument 'z' is used out-of-position but is followed by an unnamed argument // [A(3, z: 5, 1)] Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "z").WithArguments("z").WithLocation(8, 11), // (9,24): error CS1016: Named attribute argument expected // [A(3, 1, X = 6, z: 5)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "5").WithLocation(9, 24), // (10,15): error CS1016: Named attribute argument expected // [A(X = 6, 0)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "0").WithLocation(10, 15), // (11,18): error CS1016: Named attribute argument expected // [A(X = 6, x: 0)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "0").WithLocation(11, 18) ); } [WorkItem(541877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541877")] [Fact] public void Bug8772_TestDelegateAttributeNameBinding() { string source = @" using System; class A : Attribute { public A(int x) { Console.WriteLine(x); } } class C { [A(Invoke)] delegate void F1(); delegate T F2<[A(Invoke)]T> (); const int Invoke = 1; static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,8): error CS1503: Argument 1: cannot convert from 'method group' to 'int' // [A(Invoke)] Diagnostic(ErrorCode.ERR_BadArgType, "Invoke").WithArguments("1", "method group", "int").WithLocation(11, 8), // (14,22): error CS1503: Argument 1: cannot convert from 'method group' to 'int' // delegate T F2<[A(Invoke)]T> (); Diagnostic(ErrorCode.ERR_BadArgType, "Invoke").WithArguments("1", "method group", "int").WithLocation(14, 22)); } [Fact] public void AmbiguousAttributeErrors_01() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_01 { using ValidWithSuffix; using ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS1614: 'Description' is ambiguous between 'ValidWithoutSuffix.Description' and 'ValidWithSuffix.DescriptionAttribute'; use either '@Description' or 'DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "Description").WithArguments("Description", "ValidWithoutSuffix.Description", "ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_02() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_02 { using ValidWithSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'ValidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute", "ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_03() { string source = @" namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_03 { using ValidWithoutSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); } [Fact] public void AmbiguousAttributeErrors_04() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_04 { using ValidWithSuffix; using ValidWithoutSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (36,6): error CS0104: 'Description' is an ambiguous reference between 'ValidWithSuffix_And_ValidWithoutSuffix.Description' and 'ValidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "ValidWithSuffix_And_ValidWithoutSuffix.Description", "ValidWithoutSuffix.Description"), // (39,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'ValidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute", "ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_05() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace TestNamespace_05 { using InvalidWithSuffix; using InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS0616: 'InvalidWithoutSuffix.Description' is not an attribute class // [Description(null)] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Description").WithArguments("InvalidWithoutSuffix.Description"), // (26,6): error CS0616: 'InvalidWithSuffix.DescriptionAttribute' is not an attribute class // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DescriptionAttribute").WithArguments("InvalidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_06() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithSuffix_And_InvalidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_06 { using InvalidWithSuffix; using InvalidWithSuffix_And_InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute"), // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_07() { string source = @" namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace InvalidWithSuffix_And_InvalidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_07 { using InvalidWithoutSuffix; using InvalidWithSuffix_And_InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (30,6): error CS0616: 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' is not an attribute class // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DescriptionAttribute").WithArguments("InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute"), // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_And_InvalidWithoutSuffix.Description' and 'InvalidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_And_InvalidWithoutSuffix.Description", "InvalidWithoutSuffix.Description")); } [Fact] public void AmbiguousAttributeErrors_08() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace InvalidWithSuffix_And_InvalidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_08 { using InvalidWithSuffix; using InvalidWithoutSuffix; using InvalidWithSuffix_And_InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (36,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_And_InvalidWithoutSuffix.Description' and 'InvalidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_And_InvalidWithoutSuffix.Description", "InvalidWithoutSuffix.Description"), // (39,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_09() { string source = @" namespace InvalidWithoutSuffix_But_ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace InvalidWithSuffix_But_ValidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_09 { using InvalidWithoutSuffix_But_ValidWithSuffix; using InvalidWithSuffix_But_ValidWithoutSuffix; [Description(null)] public class Test { public static void Main() {} } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (31,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_But_ValidWithoutSuffix.Description' and 'InvalidWithoutSuffix_But_ValidWithSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_But_ValidWithoutSuffix.Description", "InvalidWithoutSuffix_But_ValidWithSuffix.Description"), // (34,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix_But_ValidWithoutSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix_But_ValidWithoutSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_10() { string source = @" namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace TestNamespace_10 { using ValidWithoutSuffix; using InvalidWithoutSuffix; [Description(null)] public class Test { public static void Main() {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithoutSuffix.Description' and 'ValidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithoutSuffix.Description", "ValidWithoutSuffix.Description")); } [Fact] public void AmbiguousAttributeErrors_11() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace TestNamespace_11 { using ValidWithSuffix; using InvalidWithSuffix; [Description(null)] public class Test { public static void Main() {} } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix.DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute"), // (26,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_12() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithoutSuffix_But_ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_12 { using InvalidWithoutSuffix_But_ValidWithSuffix; using InvalidWithSuffix; [Description(null)] public class Test { public static void Main() {} } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute"), // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AliasAttributeName() { var source = @"using A = A1; using AAttribute = A2; class A1 : System.Attribute { } class A2 : System.Attribute { } [A]class C { }"; CreateCompilation(source).VerifyDiagnostics( // (5,2): error CS1614: 'A' is ambiguous between 'A2' and 'A1'; use either '@A' or 'AAttribute' Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "A").WithArguments("A", "A1", "A2").WithLocation(5, 2)); } [WorkItem(542279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542279")] [Fact] public void MethodSignatureAttributes() { var text = @"class A : System.Attribute { public A(object o) { } } class B { } class C { [return: A(new B())] static object F( [A(new B())] object x, [param: A(new B())] object y) { return null; } }"; CreateCompilation(text).VerifyDiagnostics( // (8,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(8, 16), // (10,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(10, 12), // (11,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(11, 19)); } [Fact] public void AttributeDiagnosticsForEachArgument01() { var source = @"using System; public class A : Attribute { public A(object[] a) {} } [A(new object[] { default(E), default(E) })] class C<T, U> { public enum E {} }"; CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 19), // (7,31): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 31) ); } [Fact] public void AttributeDiagnosticsForEachArgument02() { var source = @"using System; public class A : Attribute { public A(object[] a, object[] b) {} } [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] class C<T, U> { public enum E {} }"; // Note that we suppress further errors once we have reported a bad attribute argument. CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 19), // (7,31): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 31), // (7,60): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 60), // (7,72): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 72) ); } [Fact] public void AttributeArgumentDecimalTypeConstant() { var source = @"using System; [A(X = new decimal())] public class A : Attribute { public object X; const decimal y = new decimal(); }"; CreateCompilation(source).VerifyDiagnostics( // (2,8): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = new decimal())] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new decimal()").WithLocation(2, 8)); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void DuplicateAttributeOnTypeParameterOfPartialClass() { string source = @" class A : System.Attribute { } partial class C<T> { } partial class C<[A][A] T> { } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (4,2): error CS0579: Duplicate 'A' attribute Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"A").WithArguments("A")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void MethodParameterScope() { string source = @" using System; class A : Attribute { public A(int x) { Console.WriteLine(x); } } class C { [A(qq)] // CS0103 - no 'qq' in scope C(int qq) { } [A(rr)] // CS0103 - no 'rr' in scope void M(int rr) { } int P { [A(value)]set { } } // CS0103 - no 'value' in scope static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,8): error CS0103: The name 'qq' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "qq").WithArguments("qq"), // (14,8): error CS0103: The name 'rr' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "rr").WithArguments("rr"), // (17,16): error CS0103: The name 'value' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "value").WithArguments("value")); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var attrArgSyntaxes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AttributeArgumentSyntax>(); Assert.Equal(3, attrArgSyntaxes.Count()); foreach (var argSyntax in attrArgSyntaxes) { var info = semanticModel.GetSymbolInfo(argSyntax.Expression); Assert.Null(info.Symbol); Assert.Equal(0, info.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, info.CandidateReason); } } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void MethodTypeParameterScope() { string source = @" using System; class A : Attribute { public A(int x) { Console.WriteLine(x); } } class C { [A(typeof(T))] // CS0246 - no 'T' in scope void M<T>() { } static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,15): error CS0246: The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "T").WithArguments("T")); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var attrArgSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().Single(); var typeofSyntax = (TypeOfExpressionSyntax)attrArgSyntax.Expression; var typeofArgSyntax = typeofSyntax.Type; Assert.Equal("T", typeofArgSyntax.ToString()); var info = semanticModel.GetSymbolInfo(typeofArgSyntax); Assert.Null(info.Symbol); Assert.Equal(0, info.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, info.CandidateReason); } [WorkItem(542625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542625")] [Fact] public void DuplicateAttributeOnPartialMethod() { string source = @" class A : System.Attribute { } class B : System.Attribute { } partial class C { [return: B] [A] static partial void Goo(); [return: B] [A] static partial void Goo() { } } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // error CS0579: Duplicate 'A' attribute Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"A").WithArguments("A"), // error CS0579: Duplicate 'B' attribute Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"B").WithArguments("B")); } [WorkItem(542625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542625")] [Fact] public void DuplicateAttributeOnTypeParameterOfPartialMethod() { string source = @" class A : System.Attribute { } partial class C { static partial void Goo<[A] T>(); static partial void Goo<[A] T>() { } // partial method without implementation, but another method with same name static partial void Goo2<[A] T>(); static void Goo2<[A] T>() { } // partial method without implementation, but another member with same name static partial void Goo3<[A] T>(); private int Goo3; // partial method without implementation static partial void Goo4<[A][A] T>(); // partial methods differing by signature static partial void Goo5<[A] T>(int x); static partial void Goo5<[A] T>(); // partial method without defining declaration static partial void Goo6<[A][A] T>() { } } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (25,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Goo6<T>()' // static partial void Goo6<[A][A] T>() { } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Goo6").WithArguments("C.Goo6<T>()").WithLocation(25, 25), // (11,17): error CS0111: Type 'C' already defines a member called 'Goo2' with the same parameter types // static void Goo2<[A] T>() { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Goo2").WithArguments("Goo2", "C").WithLocation(11, 17), // (15,17): error CS0102: The type 'C' already contains a definition for 'Goo3' // private int Goo3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Goo3").WithArguments("C", "Goo3").WithLocation(15, 17), // (18,34): error CS0579: Duplicate 'A' attribute // static partial void Goo4<[A][A] T>(); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(18, 34), // (25,34): error CS0579: Duplicate 'A' attribute // static partial void Goo6<[A][A] T>() { } Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(25, 34), // (7,30): error CS0579: Duplicate 'A' attribute // static partial void Goo<[A] T>() { } Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(7, 30), // (15,17): warning CS0169: The field 'C.Goo3' is never used // private int Goo3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Goo3").WithArguments("C.Goo3").WithLocation(15, 17)); } [WorkItem(542625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542625")] [Fact] public void DuplicateAttributeOnParameterOfPartialMethod() { string source = @" class A : System.Attribute { } partial class C { static partial void Goo([param: A]int y); static partial void Goo([A] int y) { } // partial method without implementation, but another method with same name static partial void Goo2([A] int y); static void Goo2([A] int y) { } // partial method without implementation, but another member with same name static partial void Goo3([A] int y); private int Goo3; // partial method without implementation static partial void Goo4([A][param: A] int y); // partial methods differing by signature static partial void Goo5([A] int y); static partial void Goo5([A] int y, int z); // partial method without defining declaration static partial void Goo6([A][A] int y) { } } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (25,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Goo6(int)' // static partial void Goo6([A][A] int y) { } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Goo6").WithArguments("C.Goo6(int)").WithLocation(25, 25), // (11,17): error CS0111: Type 'C' already defines a member called 'Goo2' with the same parameter types // static void Goo2([A] int y) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Goo2").WithArguments("Goo2", "C").WithLocation(11, 17), // (15,17): error CS0102: The type 'C' already contains a definition for 'Goo3' // private int Goo3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Goo3").WithArguments("C", "Goo3").WithLocation(15, 17), // (18,41): error CS0579: Duplicate 'A' attribute // static partial void Goo4([A][param: A] int y); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(18, 41), // (25,34): error CS0579: Duplicate 'A' attribute // static partial void Goo6([A][A] int y) { } Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(25, 34), // (6,37): error CS0579: Duplicate 'A' attribute // static partial void Goo([param: A]int y); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(6, 37), // (15,17): warning CS0169: The field 'C.Goo3' is never used // private int Goo3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Goo3").WithArguments("C.Goo3").WithLocation(15, 17)); } [Fact] public void PartialMethodOverloads() { string source = @" class A : System.Attribute { } partial class C { static partial void F([A] int y); static partial void F(int y, [A]int z); } "; CompileAndVerify(source); } [WorkItem(543456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543456")] [Fact] public void StructLayoutFieldsAreUsed() { var source = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] struct S { int a, b, c; }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542662")] [Fact] public void FalseDuplicateOnPartial() { var source = @" using System; class A : Attribute { } partial class Program { static partial void Goo(int x); [A] static partial void Goo(int x) { } static partial void Goo(); [A] static partial void Goo() { } static void Main() { Console.WriteLine(((Action) Goo).Method.GetCustomAttributesData().Count); } } "; CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(542652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542652")] [Fact] public void Bug9958() { var source = @" class A : System.Attribute { } partial class C { static partial void Goo<T,[A] S>(); static partial void Goo<[A]>() { } }"; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (7,32): error CS1001: Identifier expected // static partial void Goo<[A]>() { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ">"), // (7,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Goo<>()' // static partial void Goo<[A]>() { } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Goo").WithArguments("C.Goo<>()")); } [WorkItem(542909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542909")] [Fact] public void OverriddenPropertyMissingAccessor() { var source = @"using System; class A : Attribute { public virtual int P { get; set; } } class B1 : A { public override int P { get { return base.P; } } } class B2 : A { public override int P { set { } } } [A(P=0)] [B1(P=1)] [B2(P = 2)] class C { }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542899")] [Fact] public void TwoSyntaxTrees() { var source = @" using System.Reflection; [assembly: AssemblyTitle(""EnterpriseLibraryExtensions"")] "; var source2 = @" using Microsoft.Practices.EnterpriseLibrary.Configuration.Design; using EnterpriseLibraryExtensions; [assembly: ConfigurationDesignManager(typeof(ExtensionDesignManager))] "; var compilation = CreateCompilation(new string[] { source, source2 }); compilation.GetDiagnostics(); } [WorkItem(543785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543785")] [Fact] public void OpenGenericTypesUsedAsAttributeArgs() { var source = @" class Gen<T> { [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; }"; var compilation = CreateCompilation(source); Assert.NotEmpty(compilation.GetDiagnostics()); compilation.VerifyDiagnostics( // (4,6): error CS0246: The type or namespace name 'TypeAttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "TypeAttribute").WithArguments("TypeAttributeAttribute").WithLocation(4, 6), // (4,6): error CS0246: The type or namespace name 'TypeAttribute' could not be found (are you missing a using directive or an assembly reference?) // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "TypeAttribute").WithArguments("TypeAttribute").WithLocation(4, 6), // (4,27): error CS0246: The type or namespace name 'L1' could not be found (are you missing a using directive or an assembly reference?) // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "L1").WithArguments("L1").WithLocation(4, 27), // (4,55): warning CS0649: Field 'Gen<T>.Fld6' is never assigned to, and will always have its default value // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Fld6").WithArguments("Gen<T>.Fld6", "").WithLocation(4, 55)); } [WorkItem(543914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543914")] [Fact] public void OpenGenericTypeInAttribute() { var source = @" class Gen<T> {} class Gen2<T>: System.Attribute {} [Gen] [Gen2] public class Test { public static int Main() { return 1; } }"; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,16): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class Gen2<T>: System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(3, 16), // (5,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(6, 2)); } [Fact] public void OpenGenericTypeInAttributeWithGenericAttributeFeature() { var source = @" class Gen<T> {} class Gen2<T> : System.Attribute {} class Gen3<T> : System.Attribute { Gen3(T parameter) { } } [Gen] [Gen2] [Gen2()] [Gen2<U>] [Gen2<System.Collections.Generic.List<U>>] [Gen3(1)] public class Test<U> { public static int Main() { return 1; } }"; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics( // (6,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(6, 2), // (7,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(7, 2), // (8,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2()] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(8, 2), // (9,2): error CS8958: 'U': an attribute type argument cannot use type parameters // [Gen2<U>] Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Gen2<U>").WithArguments("U").WithLocation(9, 2), // (10,2): error CS8958: 'System.Collections.Generic.List<U>': an attribute type argument cannot use type parameters // [Gen2<System.Collections.Generic.List<U>>] Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Gen2<System.Collections.Generic.List<U>>").WithArguments("System.Collections.Generic.List<U>").WithLocation(10, 2), // (10,2): error CS0579: Duplicate 'Gen2<>' attribute // [Gen2<System.Collections.Generic.List<U>>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Gen2<System.Collections.Generic.List<U>>").WithArguments("Gen2<>").WithLocation(10, 2), // (11,2): error CS0305: Using the generic type 'Gen3<T>' requires 1 type arguments // [Gen3(1)] Diagnostic(ErrorCode.ERR_BadArity, "Gen3").WithArguments("Gen3<T>", "type", "1").WithLocation(11, 2)); } [Fact] public void GenericAttributeTypeFromILSource() { var ilSource = @" .class public Gen<T> { } .class public Gen2<T> extends [mscorlib] System.Attribute { } "; var csharpSource = @" [Gen] [Gen2] public class Test { public static int Main() { return 1; } }"; var comp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(2, 2), // (3,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(3, 2)); comp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (2,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(2, 2), // (3,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(3, 2)); } [WorkItem(544230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544230")] [Fact] public void Warnings_Unassigned_Unreferenced_AttributeTypeFields() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class B : Attribute { public Type PublicField; // CS0649 private Type PrivateField; // CS0169 protected Type ProtectedField; // CS0649 internal Type InternalField; // CS0649 }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,17): warning CS0649: Field 'B.PublicField' is never assigned to, and will always have its default value null // public Type PublicField; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "PublicField").WithArguments("B.PublicField", "null"), // (8,18): warning CS0169: The field 'B.PrivateField' is never used // private Type PrivateField; // CS0169 Diagnostic(ErrorCode.WRN_UnreferencedField, "PrivateField").WithArguments("B.PrivateField"), // (9,20): warning CS0649: Field 'B.ProtectedField' is never assigned to, and will always have its default value null // protected Type ProtectedField; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ProtectedField").WithArguments("B.ProtectedField", "null"), // (10,19): warning CS0649: Field 'B.InternalField' is never assigned to, and will always have its default value null // internal Type InternalField; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "InternalField").WithArguments("B.InternalField", "null")); } [WorkItem(544230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544230")] [Fact] public void No_Warnings_For_Assigned_AttributeTypeFields() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class A : Attribute { public Type PublicField; // No CS0649 private Type PrivateField; // No CS0649 protected Type ProtectedField; // No CS0649 internal Type InternalField; // No CS0649 [A(PublicField = typeof(int))] [A(PrivateField = typeof(int))] [A(ProtectedField = typeof(int))] [A(InternalField = typeof(int))] static void Main() { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,8): error CS0617: 'PrivateField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [A(PrivateField = typeof(int))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "PrivateField").WithArguments("PrivateField"), // (14,8): error CS0617: 'ProtectedField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [A(ProtectedField = typeof(int))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "ProtectedField").WithArguments("ProtectedField"), // (15,8): error CS0617: 'InternalField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [A(InternalField = typeof(int))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "InternalField").WithArguments("InternalField")); } [WorkItem(544351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544351")] [Fact] public void CS0182_ERR_BadAttributeArgument_Bug_12638() { var source = @" using System; [A(X = new Array[] { new[] { 1 } })] class A : Attribute { public object X; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,8): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = new Array[] { new[] { 1 } })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new Array[] { new[] { 1 } }").WithLocation(4, 8)); } [WorkItem(544348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544348")] [Fact] public void CS0182_ERR_BadAttributeArgument_WithConversions() { var source = @"using System; [A((int)(object)""ABC"")] class A : Attribute { public A(int x) { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A((int)(object)"ABC")] Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"(int)(object)""ABC""").WithLocation(3, 4)); } [WorkItem(544348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544348")] [Fact] public void CS0182_ERR_BadAttributeArgument_WithConversions_02() { var source = @"using System; [A((object[])(object)( new [] { 1 }))] class A : Attribute { public A(object[] x) { } } [B((object[])(object)(new string[] { ""a"", null }))] class B : Attribute { public B(object[] x) { } } "; CreateCompilation(source).VerifyDiagnostics( // (3,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A((object[])(object)( new [] { 1 }))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "(object[])(object)( new [] { 1 })").WithLocation(3, 4), // (9,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [B((object[])(object)(new string[] { "a", null }))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"(object[])(object)(new string[] { ""a"", null })").WithLocation(9, 4)); } [WorkItem(529392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529392")] [Fact] public void CS0182_ERR_BadAttributeArgument_OpenType_ConstantValue() { // SPEC ERROR: C# language specification does not explicitly disallow constant values of open types. For e.g. // public class C<T> // { // public enum E { V } // } // // [SomeAttr(C<T>.E.V)] // case (a): Constant value of open type. // [SomeAttr(C<int>.E.V)] // case (b): Constant value of constructed type. // Both expressions 'C<T>.E.V' and 'C<int>.E.V' satisfy the requirements for a valid attribute-argument-expression: // (a) Its type is a valid attribute parameter type as per section 17.1.3 of the specification. // (b) It has a compile time constant value. // However, native compiler disallows both the above cases. // We disallow case (a) as it cannot be serialized correctly, but allow case (b) to compile. var source = @" using System; class A : Attribute { public object X; } class C<T> { [A(X = C<T>.E.V)] public enum E { V } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = C<T>.E.V)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C<T>.E.V").WithLocation(11, 12)); } [WorkItem(529392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529392")] [Fact] public void AttributeArgument_ConstructedType_ConstantValue() { // See comments for test CS0182_ERR_BadAttributeArgument_OpenType_ConstantValue var source = @" using System; class A : Attribute { public object X; public static void Main() { typeof(C<>.E).GetCustomAttributes(false); } } public class C<T> { [A(X = C<int>.E.V)] public enum E { V } }"; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(544512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544512")] [Fact] public void LambdaInAttributeArg() { string source = @" public delegate void D(); public class myAttr : System.Attribute { public D d { get { return () => { }; } set { } } } [myAttr(d = () => { })] class X { public static int Main() { return 1; } } "; CreateCompilation(source).VerifyDiagnostics( // (14,9): error CS0655: 'd' is not a valid named attribute argument because it is not a valid attribute parameter type // [myAttr(d = () => { })] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "d").WithArguments("d").WithLocation(14, 9)); } [WorkItem(544590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544590")] [Fact] public void LambdaInAttributeArg2() { string source = @" using System; [AttributeUsage(AttributeTargets.All)] public class Goo : Attribute { public Goo(int sName) { } } public class Class1 { [field: Goo(((System.Func<int>)(() => 5))())] public event EventHandler Click; public static void Main() { } } "; CreateCompilation(source).VerifyDiagnostics( // (11,17): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [field: Goo(((System.Func<int>)(() => 5))())] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "((System.Func<int>)(() => 5))()"), // (12,31): warning CS0067: The event 'Class1.Click' is never used // public event EventHandler Click; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Click").WithArguments("Class1.Click")); } [WorkItem(545030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545030")] [Fact] public void UserDefinedAttribute_Bug13264() { string source = @" namespace System.Runtime.InteropServices { [DllImport] // Error class DllImportAttribute {} } namespace System { [Object] // Warning public class Object : System.Attribute {} } "; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (4,6): error CS0616: 'System.Runtime.InteropServices.DllImportAttribute' is not an attribute class // [DllImport] // Error Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DllImport").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), // (9,6): warning CS0436: The type 'System.Object' in '' conflicts with the imported type 'object' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // [Object] // Warning Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Object").WithArguments("", "System.Object", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "object")); } [WorkItem(545241, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545241")] [Fact] public void ConditionalAttributeOnAttribute() { string source = @" using System; using System.Diagnostics; [Conditional(""A"")] class Attr1 : Attribute { } class Attr2 : Attribute { } class Attr3 : Attr1 { } [Attr1, Attr2, Attr3] class Test { } "; Action<ModuleSymbol> sourceValidator = module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var attrs = type.GetAttributes(); Assert.Equal(3, attrs.Length); }; Action<ModuleSymbol> metadataValidator = module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var attrs = type.GetAttributes(); Assert.Equal(1, attrs.Length); // only one is not conditional Assert.Equal("Attr2", attrs.Single().AttributeClass.Name); }; CompileAndVerify(source, sourceSymbolValidator: sourceValidator, symbolValidator: metadataValidator); } [WorkItem(545499, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545499")] [Fact] public void IncompleteMethodParamAttribute() { string source = @" using System; public class MyAttribute2 : Attribute { public Type[] Types; } public class Test { public void goo([MyAttribute2(Types = new Type[ "; var compilation = CreateCompilation(source); Assert.NotEmpty(compilation.GetDiagnostics()); } [Fact, WorkItem(545556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545556")] public void NameLookupInDelegateParameterAttribute() { var source = @" using System; class A : Attribute { new const int Equals = 1; delegate void F([A(Equals)] int x); public A(int x) { } } "; CreateCompilation(source).VerifyDiagnostics( // (7,24): error CS1503: Argument 1: cannot convert from 'method group' to 'int' // delegate void F([A(Equals)] int x); Diagnostic(ErrorCode.ERR_BadArgType, "Equals").WithArguments("1", "method group", "int")); } [Fact, WorkItem(546234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546234")] public void AmbiguousClassNamespaceLookup() { // One from source, one from PE var source = @" using System; [System] class System : Attribute { } "; var compilation = CreateCompilationWithMscorlib40(source); compilation.VerifyDiagnostics( // (2,7): warning CS0437: The type 'System' in '' conflicts with the imported namespace 'System' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // using System; Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "System").WithArguments("", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System"), // (2,7): error CS0138: A 'using namespace' directive can only be applied to namespaces; 'System' is a type not a namespace. Consider a 'using static' directive instead // using System; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "System").WithArguments("System").WithLocation(2, 7), // (4,16): error CS0246: The type or namespace name 'Attribute' could not be found (are you missing a using directive or an assembly reference?) // class System : Attribute Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Attribute").WithArguments("Attribute"), // (3,2): error CS0616: 'System' is not an attribute class // [System] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "System").WithArguments("System"), // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); source = @" [assembly: X] namespace X { } "; var source2 = @" using System; public class X: Attribute { } "; var comp1 = CreateCompilationWithMscorlib40(source2, assemblyName: "Temp0").ToMetadataReference(); CreateCompilationWithMscorlib40(source, references: new[] { comp1 }).VerifyDiagnostics( // (2,12): error CS0616: 'X' is not an attribute class // [assembly: X] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X")); // Multiple from PE, none from Source source2 = @" using System; public class X { } "; var source3 = @" namespace X { } "; var source4 = @" [X] class Y { } "; comp1 = CreateCompilationWithMscorlib40(source2, assemblyName: "Temp1").ToMetadataReference(); var comp2 = CreateEmptyCompilation(source3, assemblyName: "Temp2").ToMetadataReference(); var comp3 = CreateCompilationWithMscorlib40(source4, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (2,2): error CS0434: The namespace 'X' in 'Temp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with the type 'X' in 'Temp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // [X] Diagnostic(ErrorCode.ERR_SameFullNameNsAgg, "X").WithArguments("Temp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "X", "Temp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "X")); // Multiple from PE, one from Source: Failure var source5 = @" [X] class X { } "; comp3 = CreateCompilationWithMscorlib40(source5, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (2,2): error CS0616: 'X' is not an attribute class // [X] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X")); // Multiple from PE, one from Source: Success source5 = @" using System; [X] class X: Attribute { } "; CompileAndVerifyWithMscorlib40(source5, references: new[] { comp1, comp2 }); // Multiple from PE, multiple from Source var source6 = @" [X] class X { } namespace X { } "; comp3 = CreateCompilationWithMscorlib40(source6, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (3,7): error CS0101: The namespace '<global namespace>' already contains a definition for 'X' // class X Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "X").WithArguments("X", "<global namespace>")); // Multiple from PE, one from Source with alias var source7 = @" using System; using X = Goo; [X] class Goo: Attribute { } "; comp3 = CreateCompilationWithMscorlib40(source7, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (4,2): error CS0576: Namespace '<global namespace>' contains a definition conflicting with alias 'X' // [X] Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "X").WithArguments("X", "<global namespace>"), // (4,2): error CS0616: 'X' is not an attribute class // [X] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X")); } [Fact] public void AmbiguousClassNamespaceLookup_Container() { var source1 = @"using System; public class A : Attribute { } namespace N1 { public class B : Attribute { } public class C : Attribute { } }"; var comp = CreateCompilation(source1, assemblyName: "A"); var ref1 = comp.EmitToImageReference(); var source2 = @"using System; using N1; using N2; namespace N1 { class A : Attribute { } class B : Attribute { } } namespace N2 { class C : Attribute { } } [A] [B] [C] class D { }"; comp = CreateCompilation(source2, references: new[] { ref1 }, assemblyName: "B"); comp.VerifyDiagnostics( // (14,2): warning CS0436: The type 'B' in '' conflicts with the imported type 'B' in 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // [B] Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "B").WithArguments("", "N1.B", "A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "N1.B").WithLocation(14, 2), // (15,2): error CS0104: 'C' is an ambiguous reference between 'N2.C' and 'N1.C' // [C] Diagnostic(ErrorCode.ERR_AmbigContext, "C").WithArguments("C", "N2.C", "N1.C").WithLocation(15, 2)); } [Fact] public void AmbiguousClassNamespaceLookup_Generic() { var source1 = @"public class A { } public class B<T> { } public class C<T, U> { }"; var comp = CreateCompilation(source1); var ref1 = comp.EmitToImageReference(); var source2 = @"class A<U> { } class B<U> { } class C<U> { } [A] [B] [C] class D { }"; comp = CreateCompilation(source2, references: new[] { ref1 }); comp.VerifyDiagnostics( // (4,2): error CS0616: 'A' is not an attribute class // [A] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "A").WithArguments("A").WithLocation(4, 2), // (5,2): error CS0616: 'B<U>' is not an attribute class // [B] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "B").WithArguments("B<U>").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'C<U>' requires 1 type arguments // [C] Diagnostic(ErrorCode.ERR_BadArity, "C").WithArguments("C<U>", "type", "1").WithLocation(6, 2)); } [WorkItem(546283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546283")] [Fact] public void ApplyIndexerNameAttributeTwice() { var source = @"using System.Runtime.CompilerServices; public class IA { [IndexerName(""ItemX"")] [IndexerName(""ItemY"")] public virtual int this[int index] { get { return 1;} set {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,3): error CS0579: Duplicate 'IndexerName' attribute // [IndexerName("ItemY")] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "IndexerName").WithArguments("IndexerName").WithLocation(6, 3)); var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("IA").GetMember<PropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal("ItemX", indexer.MetadataName); //First one wins. } [WorkItem(530524, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530524")] [Fact] public void PEMethodSymbolExtensionAttribute1() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .class public E { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void M(object o) { o.M(); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal(0, assembly.GetAttributes().Length); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E"); Assert.Equal(0, type.GetAttributes().Length); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); Assert.True(method.TestIsExtensionBitSet); Assert.True(method.TestIsExtensionBitTrue); Assert.True(method.IsExtensionMethod); } [WorkItem(530524, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530524")] [Fact] public void PEMethodSymbolExtensionAttribute2() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { } .class public E { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void M(object o) { o.M(); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics(); // we now recognize the extension method even without the assembly-level attribute var assembly = compilation.Assembly; Assert.Equal(0, assembly.GetAttributes().Length); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E"); Assert.Equal(0, type.GetAttributes().Length); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); Assert.True(method.TestIsExtensionBitSet); Assert.True(method.TestIsExtensionBitTrue); Assert.True(method.IsExtensionMethod); } [WorkItem(530524, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530524")] [Fact] public void PEMethodSymbolExtensionAttribute3() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .class public E { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(object o) { ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void M(object o) { o.M(); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics( // (5,11): error CS1061: 'object' does not contain a definition for 'M' and no extension method 'M' accepting a // first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o.M(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("object", "M")); var assembly = compilation.Assembly; Assert.Equal(0, assembly.GetAttributes().Length); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E"); Assert.Equal(0, type.GetAttributes().Length); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); Assert.True(method.TestIsExtensionBitSet); Assert.False(method.TestIsExtensionBitTrue); Assert.False(method.IsExtensionMethod); } [WorkItem(530310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530310")] [Fact] public void PEParameterSymbolParamArrayAttribute() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(int32 x, int32[] y) { .param [2] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void Main(string[] args) { A.M(1, 2, 3); A.M(1, 2, 3, 4); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics(); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); var yParam = method.Parameters[1]; Assert.True(yParam.IsParams); Assert.Equal(0, yParam.GetAttributes().Length); } [WorkItem(546490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546490")] [Fact] public void Bug15984() { var source1 = @" .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern FSharp.Core {} .assembly '<<GeneratedFileName>>' { } .class public abstract auto ansi sealed Library1.Goo extends [mscorlib]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .method public static int32 inc(int32 x) cil managed { // Code size 5 (0x5) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: add IL_0004: ret } // end of method Goo::inc } // end of class Library1.Goo "; var reference1 = CompileIL(source1, prependDefaultHeader: false); var compilation = CreateCompilation("", new[] { reference1 }); var type = compilation.GetTypeByMetadataName("Library1.Goo"); Assert.Equal(0, type.GetAttributes()[0].ConstructorArguments.Count()); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void GenericAttributeType() { var source = @" using System; [A<>] // 1, 2 [A<int>] // 3, 4 [B] // 5 [B<>] // 6, 7 [B<int>] // 8, 9 [C] // 10 [C<>] // 11, 12 [C<int>] // 13, 14 [C<,>] // 15, 16 [C<int, int>] // 17, 18 class Test { } public class A : Attribute { } public class B<T> : Attribute // 19 { } public class C<T, U> : Attribute // 20 { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<>] // 1, 2 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<>").WithArguments("A", "type").WithLocation(4, 2), // (4,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [A<>] // 1, 2 Diagnostic(ErrorCode.ERR_FeatureInPreview, "A<>").WithArguments("generic attributes").WithLocation(4, 2), // (5,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<int>] // 3, 4 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<int>").WithArguments("A", "type").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [A<int>] // 3, 4 Diagnostic(ErrorCode.ERR_FeatureInPreview, "A<int>").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'B<T>' requires 1 type arguments // [B] // 5 Diagnostic(ErrorCode.ERR_BadArity, "B").WithArguments("B<T>", "type", "1").WithLocation(6, 2), // (7,2): error CS7003: Unexpected use of an unbound generic name // [B<>] // 6, 7 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "B<>").WithLocation(7, 2), // (7,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [B<>] // 6, 7 Diagnostic(ErrorCode.ERR_FeatureInPreview, "B<>").WithArguments("generic attributes").WithLocation(7, 2), // (8,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [B<int>] // 8, 9 Diagnostic(ErrorCode.ERR_FeatureInPreview, "B<int>").WithArguments("generic attributes").WithLocation(8, 2), // (8,2): error CS0579: Duplicate 'B<>' attribute // [B<int>] // 8, 9 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "B<int>").WithArguments("B<>").WithLocation(8, 2), // (9,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C] // 10 Diagnostic(ErrorCode.ERR_BadArity, "C").WithArguments("C<T, U>", "type", "2").WithLocation(9, 2), // (10,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<>] // 11, 12 Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("C<T, U>", "type", "2").WithLocation(10, 2), // (10,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<>] // 11, 12 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<>").WithArguments("generic attributes").WithLocation(10, 2), // (11,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<int>] // 13, 14 Diagnostic(ErrorCode.ERR_BadArity, "C<int>").WithArguments("C<T, U>", "type", "2").WithLocation(11, 2), // (11,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<int>] // 13, 14 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<int>").WithArguments("generic attributes").WithLocation(11, 2), // (12,2): error CS7003: Unexpected use of an unbound generic name // [C<,>] // 15, 16 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<,>").WithLocation(12, 2), // (12,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<,>] // 15, 16 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<,>").WithArguments("generic attributes").WithLocation(12, 2), // (13,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<int, int>] // 17, 18 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<int, int>").WithArguments("generic attributes").WithLocation(13, 2), // (13,2): error CS0579: Duplicate 'C<,>' attribute // [C<int, int>] // 17, 18 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<int, int>").WithArguments("C<,>").WithLocation(13, 2), // (22,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class B<T> : Attribute // 19 Diagnostic(ErrorCode.ERR_FeatureInPreview, "Attribute").WithArguments("generic attributes").WithLocation(22, 21), // (26,24): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T, U> : Attribute // 20 Diagnostic(ErrorCode.ERR_FeatureInPreview, "Attribute").WithArguments("generic attributes").WithLocation(26, 24)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<>] // 1, 2 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<>").WithArguments("A", "type").WithLocation(4, 2), // (5,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<int>] // 3, 4 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<int>").WithArguments("A", "type").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'B<T>' requires 1 type arguments // [B] // 5 Diagnostic(ErrorCode.ERR_BadArity, "B").WithArguments("B<T>", "type", "1").WithLocation(6, 2), // (7,2): error CS7003: Unexpected use of an unbound generic name // [B<>] // 6, 7 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "B<>").WithLocation(7, 2), // (8,2): error CS0579: Duplicate 'B<>' attribute // [B<int>] // 8, 9 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "B<int>").WithArguments("B<>").WithLocation(8, 2), // (9,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C] // 10 Diagnostic(ErrorCode.ERR_BadArity, "C").WithArguments("C<T, U>", "type", "2").WithLocation(9, 2), // (10,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<>] // 11, 12 Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("C<T, U>", "type", "2").WithLocation(10, 2), // (11,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<int>] // 13, 14 Diagnostic(ErrorCode.ERR_BadArity, "C<int>").WithArguments("C<T, U>", "type", "2").WithLocation(11, 2), // (12,2): error CS7003: Unexpected use of an unbound generic name // [C<,>] // 15, 16 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<,>").WithLocation(12, 2), // (13,2): error CS0579: Duplicate 'C<,>' attribute // [C<int, int>] // 17, 18 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<int, int>").WithArguments("C<,>").WithLocation(13, 2)); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void AliasedGenericAttributeType_Source() { var source = @" using System; using Alias = C<int>; [Alias] [Alias<>] [Alias<int>] class Test { } public class C<T> : Attribute { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T> : Attribute Diagnostic(ErrorCode.ERR_FeatureInPreview, "Attribute").WithArguments("generic attributes").WithLocation(12, 21), // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(6, 2), // (7,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(7, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<>").WithArguments("generic attributes").WithLocation(6, 2), // (7,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<int>").WithArguments("generic attributes").WithLocation(7, 2)); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(6, 2), // (7,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(7, 2)); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void AliasedGenericAttributeType_Metadata() { var il = @" .class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } "; var source = @" using Alias = C<int>; [Alias] [Alias<>] [Alias<int>] class Test { } "; // NOTE: Dev11 does not give an error for "[Alias]" - it just silently drops the // attribute at emit-time. var comp = CreateCompilationWithILAndMscorlib40(source, il, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias").WithArguments("generic attributes").WithLocation(4, 2), // (5,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<>").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(6, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<int>").WithArguments("generic attributes").WithLocation(6, 2)); // NOTE: Dev11 does not give an error for "[Alias]" - it just silently drops the // attribute at emit-time. comp = CreateCompilationWithILAndMscorlib40(source, il, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(5, 2), // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(6, 2)); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void AliasedGenericAttributeType_Nested() { var source = @" using InnerAlias = Outer<int>.Inner; using OuterAlias = Outer<int>; [InnerAlias] class Test { [OuterAlias.Inner] static void Main() { } } public class Outer<T> { public class Inner { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,2): error CS0616: 'Outer<int>.Inner' is not an attribute class // [InnerAlias] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "InnerAlias").WithArguments("Outer<int>.Inner").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [InnerAlias] Diagnostic(ErrorCode.ERR_FeatureInPreview, "InnerAlias").WithArguments("generic attributes").WithLocation(5, 2), // (8,17): error CS0616: 'Outer<int>.Inner' is not an attribute class // [OuterAlias.Inner] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Inner").WithArguments("Outer<int>.Inner").WithLocation(8, 17), // (8,6): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [OuterAlias.Inner] Diagnostic(ErrorCode.ERR_FeatureInPreview, "OuterAlias.Inner").WithArguments("generic attributes").WithLocation(8, 6)); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS0616: 'Outer<int>.Inner' is not an attribute class // [InnerAlias] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "InnerAlias").WithArguments("Outer<int>.Inner").WithLocation(5, 2), // (8,17): error CS0616: 'Outer<int>.Inner' is not an attribute class // [OuterAlias.Inner] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Inner").WithArguments("Outer<int>.Inner").WithLocation(8, 17)); } [Fact] public void NestedWithGenericAttributeFeature() { var source = @" [Outer<int>.Inner] class Test { [Outer<int>.Inner] static void Main() { } } public class Outer<T> { public class Inner : System.Attribute { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void AliasedGenericAttributeType_NestedWithGenericAttributeFeature_IsAttribute() { var source = @" using InnerAlias = Outer<int>.Inner; using OuterAlias = Outer<int>; [InnerAlias] class Test { [OuterAlias.Inner] static void Main() { } } public class Outer<T> { public class Inner : System.Attribute { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [WorkItem(687816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/687816")] [Fact] public void VerbatimAliasVersusNonVerbatimAlias() { var source = @" using Action = A.ActionAttribute; using ActionAttribute = A.ActionAttribute; namespace A { class ActionAttribute : System.Attribute { } } class Program { [Action] static void Main(string[] args) { } } "; CreateCompilation(source).VerifyDiagnostics( // (12,6): error CS1614: 'Action' is ambiguous between 'A.ActionAttribute' and 'A.ActionAttribute'; use either '@Action' or 'ActionAttribute' // [Action] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "Action").WithArguments("Action", "A.ActionAttribute", "A.ActionAttribute")); } [WorkItem(687816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/687816")] [Fact] public void DeclarationVersusNonVerbatimAlias() { var source = @" using Action = A.ActionAttribute; using A; namespace A { class ActionAttribute : System.Attribute { } } class Program { [Action] static void Main(string[] args) { } } "; CreateCompilation(source).VerifyDiagnostics( // (12,6): error CS1614: 'Action' is ambiguous between 'A.ActionAttribute' and 'A.ActionAttribute'; use either '@Action' or 'ActionAttribute' // [Action] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "Action").WithArguments("Action", "A.ActionAttribute", "A.ActionAttribute")); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)] public void Repro728865() { var source = @" using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using Microsoft.Yeti; namespace PFxIntegration { public class ProducerConsumerScenario { static void Main(string[] args) { Type program = typeof(ProducerConsumerScenario); MethodInfo methodInfo = program.GetMethod(""ProducerConsumer""); Object[] myAttributes = methodInfo.GetCustomAttributes(false); ; if (myAttributes.Length > 0) { Console.WriteLine(""\r\nThe attributes for the method - {0} - are: \r\n"", methodInfo); for (int j = 0; j < myAttributes.Length; j++) Console.WriteLine(""The type of the attribute is {0}"", myAttributes[j]); } } public enum CollectionType { Default, Queue, Stack, Bag } public ProducerConsumerScenario() { } [CartesianRowData( new int[] { 5, 100, 100000 }, new CollectionType[] { CollectionType.Default, CollectionType.Queue, CollectionType.Stack, CollectionType.Bag })] public void ProducerConsumer(int inputSize, CollectionType collectionType) { Console.WriteLine(""Hello""); } } } namespace Microsoft.Yeti { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class CartesianRowDataAttribute : Attribute { public CartesianRowDataAttribute() { } public CartesianRowDataAttribute(params object[] data) { IEnumerable<object>[] asEnum = new IEnumerable<object>[data.Length]; for (int i = 0; i < data.Length; ++i) { WrapEnum((IEnumerable)data[i]); } } static void WrapEnum(IEnumerable x) { foreach (object a in x) { Console.WriteLine("" - "" + a + "" -""); } } } // class } // namespace "; CompileAndVerify(source, expectedOutput: @" - 5 - - 100 - - 100000 - - Default - - Queue - - Stack - - Bag - The attributes for the method - Void ProducerConsumer(Int32, CollectionType) - are: The type of the attribute is Microsoft.Yeti.CartesianRowDataAttribute "); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void StringArrayArgument1() { var source = @" using System; public class Test { [ArrayOnlyAttribute(new string[] { ""A"" })] //error [ObjectOnlyAttribute(new string[] { ""A"" })] [ArrayOrObjectAttribute(new string[] { ""A"" })] //error, even though the object ctor would work void M1() { } [ArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ArrayOrObjectAttribute(null)] //array void M2() { } [ArrayOnlyAttribute(new object[] { ""A"" })] [ObjectOnlyAttribute(new object[] { ""A"" })] [ArrayOrObjectAttribute(new object[] { ""A"" })] //array void M3() { } } public class ArrayOnlyAttribute : Attribute { public ArrayOnlyAttribute(object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ArrayOrObjectAttribute : Attribute { public ArrayOrObjectAttribute(object[] array) { } public ArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ArrayOnlyAttribute(new string[] { "A" })] //error Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ArrayOnlyAttribute(new string[] { ""A"" })"), // (8,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ArrayOrObjectAttribute(new string[] { "A" })] //error, even though the object ctor would work Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ArrayOrObjectAttribute(new string[] { ""A"" })")); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var attrs1 = method1.GetAttributes(); var value1 = new string[] { "A" }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); var attrs3 = method3.GetAttributes(); var value3 = new object[] { "A" }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void StringArrayArgument2() { var source = @" using System; public class Test { [ParamArrayOnlyAttribute(new string[] { ""A"" })] //error [ObjectOnlyAttribute(new string[] { ""A"" })] [ParamArrayOrObjectAttribute(new string[] { ""A"" })] //error, even though the object ctor would work void M1() { } [ParamArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ParamArrayOrObjectAttribute(null)] //array void M2() { } [ParamArrayOnlyAttribute(new object[] { ""A"" })] [ObjectOnlyAttribute(new object[] { ""A"" })] [ParamArrayOrObjectAttribute(new object[] { ""A"" })] //array void M3() { } [ParamArrayOnlyAttribute(""A"")] [ObjectOnlyAttribute(""A"")] [ParamArrayOrObjectAttribute(""A"")] //object void M4() { } } public class ParamArrayOnlyAttribute : Attribute { public ParamArrayOnlyAttribute(params object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ParamArrayOrObjectAttribute : Attribute { public ParamArrayOrObjectAttribute(params object[] array) { } public ParamArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ParamArrayOnlyAttribute(new string[] { "A" })] //error Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ParamArrayOnlyAttribute(new string[] { ""A"" })"), // (8,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ParamArrayOrObjectAttribute(new string[] { "A" })] //error, even though the object ctor would work Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ParamArrayOrObjectAttribute(new string[] { ""A"" })")); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); // As in the test above (i.e. not affected by params modifier). var attrs1 = method1.GetAttributes(); var value1 = new string[] { "A" }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); // As in the test above (i.e. not affected by params modifier). var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); // As in the test above (i.e. not affected by params modifier). var attrs3 = method3.GetAttributes(); var value3 = new object[] { "A" }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); attrs4[0].VerifyValue(0, TypedConstantKind.Array, new object[] { "A" }); attrs4[1].VerifyValue(0, TypedConstantKind.Primitive, "A"); attrs4[2].VerifyValue(0, TypedConstantKind.Primitive, "A"); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void StringArrayArgument3() { var source = @" using System; public class Test { [StringOnlyAttribute(new string[] { ""A"" })] [ObjectOnlyAttribute(new string[] { ""A"" })] //error [StringOrObjectAttribute(new string[] { ""A"" })] //string void M1() { } [StringOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [StringOrObjectAttribute(null)] //string void M2() { } //[StringOnlyAttribute(new object[] { ""A"" })] //overload resolution failure [ObjectOnlyAttribute(new object[] { ""A"" })] [StringOrObjectAttribute(new object[] { ""A"" })] //object void M3() { } [StringOnlyAttribute(""A"")] [ObjectOnlyAttribute(""A"")] [StringOrObjectAttribute(""A"")] //string void M4() { } } public class StringOnlyAttribute : Attribute { public StringOnlyAttribute(params string[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(params object[] array) { } } public class StringOrObjectAttribute : Attribute { public StringOrObjectAttribute(params string[] array) { } public StringOrObjectAttribute(params object[] array) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ObjectOnlyAttribute(new string[] { "A" })] //error Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ObjectOnlyAttribute(new string[] { ""A"" })")); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); var attrs1 = method1.GetAttributes(); var value1 = new string[] { "A" }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (string[])null); var attrs3 = method3.GetAttributes(); var value3 = new object[] { "A" }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); var value4 = new object[] { "A" }; attrs4[0].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[1].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[2].VerifyValue(0, TypedConstantKind.Array, value4); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void IntArrayArgument1() { var source = @" using System; public class Test { //[ArrayOnlyAttribute(new int[] { 1 })] //overload resolution failure [ObjectOnlyAttribute(new int[] { 1 })] [ArrayOrObjectAttribute(new int[] { 1 })] //object void M1() { } [ArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ArrayOrObjectAttribute(null)] //array void M2() { } [ArrayOnlyAttribute(new object[] { 1 })] [ObjectOnlyAttribute(new object[] { 1 })] [ArrayOrObjectAttribute(new object[] { 1 })] //array void M3() { } } public class ArrayOnlyAttribute : Attribute { public ArrayOnlyAttribute(object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ArrayOrObjectAttribute : Attribute { public ArrayOrObjectAttribute(object[] array) { } public ArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var attrs1 = method1.GetAttributes(); var value1 = new int[] { 1 }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); var attrs3 = method3.GetAttributes(); var value3 = new object[] { 1 }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void IntArrayArgument2() { var source = @" using System; public class Test { //[ParamArrayOnlyAttribute(new int[] { 1 })] //overload resolution failure [ObjectOnlyAttribute(new int[] { 1 })] [ParamArrayOrObjectAttribute(new int[] { 1 })] //object void M1() { } [ParamArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ParamArrayOrObjectAttribute(null)] //array void M2() { } [ParamArrayOnlyAttribute(new object[] { 1 })] [ObjectOnlyAttribute(new object[] { 1 })] [ParamArrayOrObjectAttribute(new object[] { 1 })] //array void M3() { } [ParamArrayOnlyAttribute(1)] [ObjectOnlyAttribute(1)] [ParamArrayOrObjectAttribute(1)] //object void M4() { } } public class ParamArrayOnlyAttribute : Attribute { public ParamArrayOnlyAttribute(params object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ParamArrayOrObjectAttribute : Attribute { public ParamArrayOrObjectAttribute(params object[] array) { } public ParamArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); // As in the test above (i.e. not affected by params modifier). var attrs1 = method1.GetAttributes(); var value1 = new int[] { 1 }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); // As in the test above (i.e. not affected by params modifier). var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); // As in the test above (i.e. not affected by params modifier). var attrs3 = method3.GetAttributes(); var value3 = new object[] { 1 }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); attrs4[0].VerifyValue(0, TypedConstantKind.Array, new object[] { 1 }); attrs4[1].VerifyValue(0, TypedConstantKind.Primitive, 1); attrs4[2].VerifyValue(0, TypedConstantKind.Primitive, 1); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void IntArrayArgument3() { var source = @" using System; public class Test { [IntOnlyAttribute(new int[] { 1 })] [ObjectOnlyAttribute(new int[] { 1 })] [IntOrObjectAttribute(new int[] { 1 })] //int void M1() { } [IntOnlyAttribute(null)] [ObjectOnlyAttribute(null)] //[IntOrObjectAttribute(null)] //ambiguous void M2() { } //[IntOnlyAttribute(new object[] { 1 })] //overload resolution failure [ObjectOnlyAttribute(new object[] { 1 })] [IntOrObjectAttribute(new object[] { 1 })] //object void M3() { } [IntOnlyAttribute(1)] [ObjectOnlyAttribute(1)] [IntOrObjectAttribute(1)] //int void M4() { } } public class IntOnlyAttribute : Attribute { public IntOnlyAttribute(params int[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(params object[] array) { } } public class IntOrObjectAttribute : Attribute { public IntOrObjectAttribute(params int[] array) { } public IntOrObjectAttribute(params object[] array) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); var attrs1 = method1.GetAttributes(); var value1 = new int[] { 1 }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, new object[] { value1 }); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); var value2 = (object[])null; attrs2[0].VerifyValue(0, TypedConstantKind.Array, value2); attrs2[1].VerifyValue(0, TypedConstantKind.Array, value2); var attrs3 = method3.GetAttributes(); var value3 = new object[] { 1 }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); var value4 = new object[] { 1 }; attrs4[0].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[1].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[2].VerifyValue(0, TypedConstantKind.Array, value4); } [WorkItem(739630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739630")] [Fact] public void NullVersusEmptyArray() { var source = @" using System; public class ArrayAttribute : Attribute { public int[] field; public ArrayAttribute(int[] param) { } } public class Test { [Array(null)] void M0() { } [Array(new int[] { })] void M1() { } [Array(null, field=null)] void M2() { } [Array(new int[] { }, field = null)] void M3() { } [Array(null, field = new int[] { })] void M4() { } [Array(new int[] { }, field = new int[] { })] void M5() { } static void Main() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var methods = Enumerable.Range(0, 6).Select(i => type.GetMember<MethodSymbol>("M" + i)); var attrs = methods.Select(m => m.GetAttributes().Single()).ToArray(); var nullArray = (int[])null; var emptyArray = new int[0]; const string fieldName = "field"; attrs[0].VerifyValue(0, TypedConstantKind.Array, nullArray); attrs[1].VerifyValue(0, TypedConstantKind.Array, emptyArray); attrs[2].VerifyValue(0, TypedConstantKind.Array, nullArray); attrs[2].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, nullArray); attrs[3].VerifyValue(0, TypedConstantKind.Array, emptyArray); attrs[3].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, nullArray); attrs[4].VerifyValue(0, TypedConstantKind.Array, nullArray); attrs[4].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, emptyArray); attrs[5].VerifyValue(0, TypedConstantKind.Array, emptyArray); attrs[5].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, emptyArray); } [Fact] [WorkItem(530266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530266")] public void UnboundGenericTypeInTypedConstant() { var source = @" using System; public class TestAttribute : Attribute { public TestAttribute(Type x){} } [TestAttribute(typeof(Target<>))] class Target<T> {}"; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Target"); var typeInAttribute = (INamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().Value; Assert.True(typeInAttribute.IsUnboundGenericType); Assert.True(((NamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().ValueInternal).IsUnboundGenericType); Assert.Equal("Target<>", typeInAttribute.ToTestDisplayString()); var comp2 = CreateCompilation("", new[] { comp.EmitToImageReference() }); type = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("Target"); Assert.IsAssignableFrom<PENamedTypeSymbol>(type); typeInAttribute = (INamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().Value; Assert.True(typeInAttribute.IsUnboundGenericType); Assert.True(((NamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().ValueInternal).IsUnboundGenericType); Assert.Equal("Target<>", typeInAttribute.ToTestDisplayString()); } [Fact, WorkItem(1020038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020038")] public void Bug1020038() { var source1 = @" public class CTest {} "; var compilation1 = CreateCompilation(source1, assemblyName: "Bug1020038"); var source2 = @" class CAttr : System.Attribute { public CAttr(System.Type x){} } [CAttr(typeof(CTest))] class Test {} "; var compilation2 = CreateCompilation(source2, new[] { new CSharpCompilationReference(compilation1) }); CompileAndVerify(compilation2, symbolValidator: (m) => { Assert.Equal(2, m.ReferencedAssemblies.Length); Assert.Equal("Bug1020038", m.ReferencedAssemblies[1].Name); }); var source3 = @" class CAttr : System.Attribute { public CAttr(System.Type x){} } [CAttr(typeof(System.Func<System.Action<CTest>>))] class Test {} "; var compilation3 = CreateCompilation(source3, new[] { new CSharpCompilationReference(compilation1) }); CompileAndVerify(compilation3, symbolValidator: (m) => { Assert.Equal(2, m.ReferencedAssemblies.Length); Assert.Equal("Bug1020038", m.ReferencedAssemblies[1].Name); }); } [Fact, WorkItem(937575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937575"), WorkItem(121, "CodePlex")] public void Bug937575() { var source = @" using System; class XAttribute : Attribute { } class C<T> { public void M<[X]U>() { } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugDll); CompileAndVerify(compilation, symbolValidator: (m) => { var cc = m.GlobalNamespace.GetTypeMember("C"); var mm = cc.GetMember<MethodSymbol>("M"); Assert.True(cc.TypeParameters.Single().GetAttributes().IsEmpty); Assert.Equal("XAttribute", mm.TypeParameters.Single().GetAttributes().Single().ToString()); }); } [WorkItem(1144603, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1144603")] [Fact] public void EmitMetadataOnlyInPresenceOfErrors() { var source1 = @" public sealed class DiagnosticAnalyzerAttribute : System.Attribute { public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) {} } public static class LanguageNames { public const xyz CSharp = ""C#""; } "; var compilation1 = CreateCompilationWithMscorlib40(source1, options: TestOptions.DebugDll); compilation1.VerifyDiagnostics( // (10,18): error CS0246: The type or namespace name 'xyz' could not be found (are you missing a using directive or an assembly reference?) // public const xyz CSharp = "C#"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "xyz").WithArguments("xyz").WithLocation(10, 18)); var source2 = @" [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpCompilerDiagnosticAnalyzer {} "; var compilation2 = CreateCompilationWithMscorlib40(source2, new[] { new CSharpCompilationReference(compilation1) }, options: TestOptions.DebugDll, assemblyName: "Test.dll"); Assert.Same(compilation1.Assembly, compilation2.SourceModule.ReferencedAssemblySymbols[1]); compilation2.VerifyDiagnostics(); var emitResult2 = compilation2.Emit(peStream: new MemoryStream(), options: new EmitOptions(metadataOnly: true)); Assert.False(emitResult2.Success); emitResult2.Diagnostics.Verify( // error CS7038: Failed to emit module 'Test.dll': Module has invalid attributes. Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("Test.dll", "Module has invalid attributes.").WithLocation(1, 1)); // Use different mscorlib to test retargeting scenario var compilation3 = CreateCompilationWithMscorlib45(source2, new[] { new CSharpCompilationReference(compilation1) }, options: TestOptions.DebugDll); Assert.NotSame(compilation1.Assembly, compilation3.SourceModule.ReferencedAssemblySymbols[1]); compilation3.VerifyDiagnostics( // (2,35): error CS0246: The type or namespace name 'xyz' could not be found (are you missing a using directive or an assembly reference?) // [DiagnosticAnalyzer(LanguageNames.CSharp)] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CSharp").WithArguments("xyz").WithLocation(2, 35)); var emitResult3 = compilation3.Emit(peStream: new MemoryStream(), options: new EmitOptions(metadataOnly: true)); Assert.False(emitResult3.Success); emitResult3.Diagnostics.Verify( // (2,35): error CS0246: The type or namespace name 'xyz' could not be found (are you missing a using directive or an assembly reference?) // [DiagnosticAnalyzer(LanguageNames.CSharp)] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CSharp").WithArguments("xyz").WithLocation(2, 35)); } [Fact, WorkItem(30833, "https://github.com/dotnet/roslyn/issues/30833")] public void AttributeWithTaskDelegateParameter() { string code = @" using System; using System.Threading.Tasks; namespace a { class Class1 { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] class CommandAttribute : Attribute { public delegate Task FxCommand(); public CommandAttribute(FxCommand Fx) { this.Fx = Fx; } public FxCommand Fx { get; set; } } [Command(UserInfo)] public static async Task UserInfo() { await Task.CompletedTask; } } } "; CreateCompilationWithMscorlib46(code).VerifyDiagnostics( // (22,4): error CS0181: Attribute constructor parameter 'Fx' has type 'Class1.CommandAttribute.FxCommand', which is not a valid attribute parameter type // [Command(UserInfo)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Command").WithArguments("Fx", "a.Class1.CommandAttribute.FxCommand").WithLocation(22, 4)); } [Fact, WorkItem(33388, "https://github.com/dotnet/roslyn/issues/33388")] public void AttributeCrashRepro_33388() { string source = @" using System; public static class C { public static int M(object obj) => 42; public static int M(C2 c2) => 42; } public class RecAttribute : Attribute { public RecAttribute(int i) { this.i = i; } private int i; } [Rec(C.M(null))] public class C2 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (20,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Rec(C.M(null))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(null)").WithLocation(20, 6)); } [Fact] [WorkItem(47308, "https://github.com/dotnet/roslyn/issues/47308")] public void ObsoleteAttribute_Delegate() { string source = @" using System; public class C { [Obsolete] public void M() { } void M2() { Action a = M; a = new Action(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,20): warning CS0612: 'C.M()' is obsolete // Action a = M; Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M").WithArguments("C.M()").WithLocation(12, 20), // (13,24): warning CS0612: 'C.M()' is obsolete // a = new Action(M); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M").WithArguments("C.M()").WithLocation(13, 24) ); } [Fact] [WorkItem(47308, "https://github.com/dotnet/roslyn/issues/47308")] public void ObsoleteAttributeWithUnsafeError() { string source = @" using System; unsafe delegate byte* D(); class C { [Obsolete(null, true)] unsafe static byte* F() => default; unsafe static D M1() => new D(F); static D M2() => new D(F); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (7,35): warning CS0612: 'C.F()' is obsolete // unsafe static D M1() => new D(F); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "F").WithArguments("C.F()").WithLocation(7, 35), // (8,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // static D M2() => new D(F); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "F").WithLocation(8, 28) ); } [Fact] [WorkItem(47308, "https://github.com/dotnet/roslyn/issues/47308")] public void UnmanagedAttributeWithUnsafeError() { string source = @" using System.Runtime.InteropServices; unsafe delegate byte* D(); class C { [UnmanagedCallersOnly] unsafe static byte* F() => default; unsafe static D M1() => new D(F); static D M2() => new D(F); } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class UnmanagedCallersOnlyAttribute : Attribute { public UnmanagedCallersOnlyAttribute() { } public Type[] CallConvs; public string EntryPoint; } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (8,35): error CS8902: 'C.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // unsafe static D M1() => new D(F); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("C.F()").WithLocation(8, 35), // (9,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // static D M2() => new D(F); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "F").WithLocation(9, 28) ); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage() { var lib_cs = @" public class A<T> : System.Attribute {} public class A : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_2() { var source = @" class A<T> : System.Attribute {} class A : System.Attribute {} [A] public class C { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,14): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class A<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 14) ); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_3() { var lib_cs = @" public class AAttribute<T> : System.Attribute {} public class AAttribute : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_4() { var lib_cs = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} public class A : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_5() { var lib_cs = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} public class AAttribute : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void MetadataForUsingGenericAttribute() { var source = @" public class A<T> : System.Attribute {} public class C { [A<int>] public void M() { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate); static void validate(ModuleSymbol module) { var m = (MethodSymbol)module.ContainingAssembly.GlobalNamespace.GetMember("C.M"); var attribute = m.GetAttributes().Single(); Assert.Equal("A<System.Int32>", attribute.AttributeClass.ToTestDisplayString()); Assert.Equal("A<System.Int32>..ctor()", attribute.AttributeConstructor.ToTestDisplayString()); } } [Fact] public void AmbiguityWithGenericAttribute() { var source = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} [A<int>] public class C { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,30): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class AAttribute<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 30), // (3,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class A<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(3, 21), // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [A<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "A<int>").WithArguments("generic attributes").WithLocation(5, 2)); } [Fact, WorkItem(54772, "https://github.com/dotnet/roslyn/issues/54772")] public void ResolveAmbiguityWithGenericAttribute() { var source = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} [@A<int>] [AAttribute<int>] public class C { }"; // This behavior is incorrect. No ambiguity errors should be reported in the above program. var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [@A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "@A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,30): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class AAttribute<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 30), // (3,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class A<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(3, 21), // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [@A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "@A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [@A<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "@A<int>").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [AAttribute<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "AAttribute<int>").WithArguments("generic attributes").WithLocation(6, 2)); } [Fact] public void InheritGenericAttribute() { var source1 = @" public class C<T> : System.Attribute { } public class D : C<int> { } "; var source2 = @" [D] public class Program { } "; var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T> : System.Attribute { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 21)); var comp1 = CreateCompilation(source1); var comp2 = CreateCompilation(source2, references: new[] { comp1.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); comp2 = CreateCompilation(source2, references: new[] { comp1.EmitToImageReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); } [Fact] public void InheritGenericAttributeInMetadata() { var il = @" .class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } .class public auto ansi beforefieldinit D extends class C`1<int32> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class C`1<int32>::.ctor() ret } } "; var source = @" [D] public class Program { } "; // Note that this behavior predates the "generic attributes" feature in C# 10. // If a type deriving from a generic attribute is found in metadata, it's permitted to be used as an attribute in C# 9 and below. var comp = CreateCompilationWithIL(source, il, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); comp = CreateCompilationWithIL(source, il); comp.VerifyDiagnostics(); } [Fact] public void InheritAttribute_BaseInsideGeneric() { var source1 = @" public class C<T> { public class Inner : System.Attribute { } } public class D : C<int>.Inner { } "; var source2 = @" [D] public class Program { } "; var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,26): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class Inner : System.Attribute { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(4, 26)); var comp1 = CreateCompilation(source1); var comp2 = CreateCompilation(source2, references: new[] { comp1.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); comp2 = CreateCompilation(source2, references: new[] { comp1.EmitToImageReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); } [Fact] public void GenericAttribute_Constraints() { var source = @" public class C<T> : System.Attribute where T : struct { } [C<object>] // 1 public class C1 { } [C<int>] public class C2 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,4): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'C<T>' // [C<object>] // 1 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "object").WithArguments("C<T>", "T", "object").WithLocation(4, 4)); } [Fact] public void GenericAttribute_ErrorTypeArg() { var source = @" public class C<T> : System.Attribute { } [C<ERROR>] [C<System>] [C<>] public class Program { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T> : System.Attribute { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 21), // (4,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<ERROR>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<ERROR>").WithArguments("generic attributes").WithLocation(4, 2), // (4,4): error CS0246: The type or namespace name 'ERROR' could not be found (are you missing a using directive or an assembly reference?) // [C<ERROR>] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ERROR").WithArguments("ERROR").WithLocation(4, 4), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<System>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<System>").WithArguments("generic attributes").WithLocation(5, 2), // (5,2): error CS0579: Duplicate 'C<>' attribute // [C<System>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<System>").WithArguments("C<>").WithLocation(5, 2), // (5,4): error CS0118: 'System' is a namespace but is used like a type // [C<System>] Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "type").WithLocation(5, 4), // (6,2): error CS7003: Unexpected use of an unbound generic name // [C<>] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>").WithLocation(6, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<>").WithArguments("generic attributes").WithLocation(6, 2), // (6,2): error CS0579: Duplicate 'C<>' attribute // [C<>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<>").WithArguments("C<>").WithLocation(6, 2)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,4): error CS0246: The type or namespace name 'ERROR' could not be found (are you missing a using directive or an assembly reference?) // [C<ERROR>] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ERROR").WithArguments("ERROR").WithLocation(4, 4), // (5,2): error CS0579: Duplicate 'C<>' attribute // [C<System>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<System>").WithArguments("C<>").WithLocation(5, 2), // (5,4): error CS0118: 'System' is a namespace but is used like a type // [C<System>] Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "type").WithLocation(5, 4), // (6,2): error CS7003: Unexpected use of an unbound generic name // [C<>] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>").WithLocation(6, 2), // (6,2): error CS0579: Duplicate 'C<>' attribute // [C<>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<>").WithArguments("C<>").WithLocation(6, 2)); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttribute_Reflection_CoreClr() { var source = @" using System; public class Attr<T> : Attribute { } [Attr<int>] public class Program { public static void Main() { var attr = Attribute.GetCustomAttribute(typeof(Program), typeof(Attr<int>)); Console.Write(attr); } } "; var verifier = CompileAndVerify(source, expectedOutput: "Attr`1[System.Int32]"); verifier.VerifyDiagnostics(); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttribute_AllowMultiple_False() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public class Attr<T> : Attribute { } [Attr<int>] [Attr<object>] // 1 [Attr<int>] // 2 public class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,2): error CS0579: Duplicate 'Attr<>' attribute // [Attr<object>] // 1 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Attr<object>").WithArguments("Attr<>").WithLocation(8, 2), // (9,2): error CS0579: Duplicate 'Attr<>' attribute // [Attr<int>] // 2 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Attr<int>").WithArguments("Attr<>").WithLocation(9, 2)); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttribute_AllowMultiple_True() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class Attr<T> : Attribute { } [Attr<int>] [Attr<object>] [Attr<int>] public class Program { static void Main() { var attrs = Attribute.GetCustomAttributes(typeof(Program)); foreach (var attr in attrs) { Console.Write(attr); Console.Write(' '); } } } "; var verifier = CompileAndVerify(source, expectedOutput: "Attr`1[System.Int32] Attr`1[System.Object] Attr`1[System.Int32]"); verifier.VerifyDiagnostics(); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttributeInvalidMultipleFromMetadata() { // This IL includes an attribute with `AllowMultiple = false` (the default). // Then the class `D` includes two copies of the attribute. var il = @" .class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Attribute { // [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 ff 7f 00 00 01 00 54 02 0d 41 6c 6c 6f 77 4d 75 6c 74 69 70 6c 65 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } .class public auto ansi beforefieldinit D { .custom instance void class C`1<int32>::.ctor() = ( 01 00 00 00 ) .custom instance void class C`1<int32>::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } "; var source = @" using System; class Program { static void Main() { var attrs = Attribute.GetCustomAttributes(typeof(D)); foreach (var attr in attrs) { Console.Write(attr); Console.Write(' '); } } } "; var comp = CreateCompilationWithIL(source, il, options: TestOptions.DebugExe); var verifier = CompileAndVerify( comp, expectedOutput: "C`1[System.Int32] C`1[System.Int32]"); verifier.VerifyDiagnostics(); } [Fact] [WorkItem(54778, "https://github.com/dotnet/roslyn/issues/54778")] [WorkItem(54804, "https://github.com/dotnet/roslyn/issues/54804")] public void GenericAttribute_AttributeDependentTypes() { var source = @" #nullable enable using System; using System.Collections.Generic; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class Attr<T> : Attribute { } [Attr<dynamic>] // 1 [Attr<List<dynamic>>] // 2 [Attr<nint>] // 3 [Attr<List<nint>>] // 4 [Attr<string?>] // 5 [Attr<List<string?>>] // 6 [Attr<(int a, int b)>] // 7 [Attr<List<(int a, int b)>>] // 8 [Attr<(int a, string? b)>] // 9 [Attr<ValueTuple<int, int>>] // ok class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,2): error CS8960: Type 'dynamic' cannot be used in this context because it cannot be represented in metadata. // [Attr<dynamic>] // 1 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<dynamic>").WithArguments("dynamic").WithLocation(10, 2), // (11,2): error CS8960: Type 'List<dynamic>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<dynamic>>] // 2 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<dynamic>>").WithArguments("List<dynamic>").WithLocation(11, 2), // (12,2): error CS8960: Type 'nint' cannot be used in this context because it cannot be represented in metadata. // [Attr<nint>] // 3 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<nint>").WithArguments("nint").WithLocation(12, 2), // (13,2): error CS8960: Type 'List<nint>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<nint>>] // 4 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<nint>>").WithArguments("List<nint>").WithLocation(13, 2), // (14,2): error CS8960: Type 'string?' cannot be used in this context because it cannot be represented in metadata. // [Attr<string?>] // 5 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<string?>").WithArguments("string?").WithLocation(14, 2), // (15,2): error CS8960: Type 'List<string?>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<string?>>] // 6 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<string?>>").WithArguments("List<string?>").WithLocation(15, 2), // (16,2): error CS8960: Type '(int a, int b)' cannot be used in this context because it cannot be represented in metadata. // [Attr<(int a, int b)>] // 7 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<(int a, int b)>").WithArguments("(int a, int b)").WithLocation(16, 2), // (17,2): error CS8960: Type 'List<(int a, int b)>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<(int a, int b)>>] // 8 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<(int a, int b)>>").WithArguments("List<(int a, int b)>").WithLocation(17, 2), // (18,2): error CS8960: Type '(int a, string? b)' cannot be used in this context because it cannot be represented in metadata. // [Attr<(int a, string? b)>] // 9 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<(int a, string? b)>").WithArguments("(int a, string? b)").WithLocation(18, 2)); } [Fact] public void GenericAttributeRestrictedTypeArgument() { var source = @" using System; class Attr<T> : Attribute { } [Attr<int*>] // 1 class C1 { } [Attr<delegate*<int, void>>] // 2 class C2 { } [Attr<TypedReference>] // 3 class C3 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,7): error CS0306: The type 'int*' may not be used as a type argument // [Attr<int*>] // 1 Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(5, 7), // (8,7): error CS0306: The type 'delegate*<int, void>' may not be used as a type argument // [Attr<delegate*<int, void>>] // 2 Diagnostic(ErrorCode.ERR_BadTypeArgument, "delegate*<int, void>").WithArguments("delegate*<int, void>").WithLocation(8, 7), // (11,7): error CS0306: The type 'TypedReference' may not be used as a type argument // [Attr<TypedReference>] // 3 Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference").WithArguments("System.TypedReference").WithLocation(11, 7)); } [Fact] public void GenericAttribute_AbstractStatic_01() { var source = @" using System; class Attr1<T> : Attribute { } class Attr2Base : Attribute { public virtual void M() { } } class Attr2<T> : Attr2Base where T : I1 { public override void M() { T.M(); } } interface I1 { static abstract void M(); } interface I2 : I1 { } class C : I1 { public static void M() { Console.Write(""C.M""); } } [Attr1<C>] [Attr2<C>] class C1 { public static void Main() { var attr2 = (Attr2Base)Attribute.GetCustomAttribute(typeof(C), typeof(Attr2Base)); attr2.M(); } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp); comp.VerifyEmitDiagnostics(); } [Fact] public void GenericAttributeOnLambda() { var source = @" using System; class Attr<T> : Attribute { } class C { void M() { Func<string, string> x = [Attr<int>] (string x) => x; x(""a""); } } "; var verifier = CompileAndVerify(source, symbolValidator: validateMetadata, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifier.VerifyDiagnostics(); void validateMetadata(ModuleSymbol module) { var lambda = module.GlobalNamespace.GetMember<MethodSymbol>("C.<>c.<M>b__0_0"); var attrs = lambda.GetAttributes(); Assert.Equal(new[] { "Attr<System.Int32>" }, GetAttributeStrings(attrs)); } } [Fact] public void GenericAttributeSimilarToWellKnownAttribute() { var source = @" using System; class ObsoleteAttribute<T> : Attribute { } class C { [Obsolete<int>] void M0() { } void M1() => M0(); [Obsolete] void M2() { } void M3() => M2(); // 1 } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,18): warning CS0612: 'C.M2()' is obsolete // void M3() => M2(); // 1 Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M2()").WithArguments("C.M2()").WithLocation(15, 18)); } [Fact] public void GenericAttributesConsumeFromVB() { var csSource = @" using System; public class Attr<T> : Attribute { } [Attr<int>] public class C { } "; var comp = CreateCompilation(csSource); var vbSource = @" Public Class D Inherits C End Class "; var comp2 = CreateVisualBasicCompilation(vbSource, referencedAssemblies: TargetFrameworkUtil.GetReferences(TargetFramework.Standard).Concat(comp.EmitToImageReference())); var d = comp2.GetMember<INamedTypeSymbol>("D"); var attrs = d.BaseType.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("Attr(Of System.Int32)", attrs[0].AttributeClass.ToTestDisplayString()); } [Fact] public void GenericAttribute_AbstractStatic_02() { var source = @" using System; class Attr1<T> : Attribute { } class Attr2<T> : Attribute where T : I1 { } interface I1 { static abstract void M(); } interface I2 : I1 { } class C : I1 { public static void M() { } } [Attr1<I1>] [Attr2<I1>] class C1 { } [Attr1<I2>] [Attr2<I2>] class C2 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static abstract void M(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M").WithLocation(8, 26), // (13,11): error CS8929: 'C.M()' cannot implement interface member 'I1.M()' in type 'C' because the target runtime doesn't support static abstract members in interfaces. // class C : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("C.M()", "I1.M()", "C").WithLocation(13, 11), // (19,8): error CS8920: The interface 'I1' cannot be used as type parameter 'T' in the generic type or method 'Attr2<T>'. The constraint interface 'I1' or its base interface has static abstract members. // [Attr2<I1>] Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "I1").WithArguments("Attr2<T>", "I1", "T", "I1").WithLocation(19, 8), // (23,8): error CS8920: The interface 'I2' cannot be used as type parameter 'T' in the generic type or method 'Attr2<T>'. The constraint interface 'I1' or its base interface has static abstract members. // [Attr2<I2>] Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "I2").WithArguments("Attr2<T>", "I1", "T", "I2").WithLocation(23, 8)); } [Fact] public void GenericAttributeProperty_01() { var source = @" using System; using System.Reflection; class Attr<T> : Attribute { public T Prop { get; set; } } [Attr<string>(Prop = ""a"")] class Program { static void Main() { var attrs = CustomAttributeData.GetCustomAttributes(typeof(Program)); foreach (var attr in attrs) { foreach (var arg in attr.NamedArguments) { Console.Write(arg.MemberName); Console.Write("" = ""); Console.Write(arg.TypedValue.Value); } } } } "; var verifier = CompileAndVerify(source, sourceSymbolValidator: verify, symbolValidator: verify, expectedOutput: "Prop = a"); void verify(ModuleSymbol module) { var program = module.GlobalNamespace.GetMember<TypeSymbol>("Program"); var attrs = program.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>(Prop = \"a\")" }, GetAttributeStrings(attrs)); } } [Fact] public void GenericAttributeProperty_02() { var source = @" using System; class Attr<T1> : Attribute { public object Prop { get; set; } } class Outer<T2> { [Attr<object>(Prop = default(T2))] // 1 class Program1 { } [Attr<T2>(Prop = default(T2))] // 2, 3 class Program2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,26): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<object>(Prop = default(T2))] // 1 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(7, 26), // (10,6): error CS8967: 'T2': an attribute type argument cannot use type parameters // [Attr<T2>(Prop = default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Attr<T2>").WithArguments("T2").WithLocation(10, 6), // (10,22): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<T2>(Prop = default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(10, 22)); } [ConditionalFact(typeof(CoreClrOnly)), WorkItem(55190, "https://github.com/dotnet/roslyn/issues/55190")] public void GenericAttributeParameter_01() { var source = @" using System; using System.Reflection; class Attr<T> : Attribute { public Attr(T param) { } } [Attr<string>(""a"")] class Holder { } class Program { static void Main() { try { var attrs = CustomAttributeData.GetCustomAttributes(typeof(Holder)); foreach (var attr in attrs) { foreach (var arg in attr.ConstructorArguments) { Console.Write(arg.Value); } } } catch (Exception e) { Console.Write(e.GetType().Name); } } } "; // The expected output here will change once we consume a runtime // which has a fix for https://github.com/dotnet/runtime/issues/56492 var verifier = CompileAndVerify(source, sourceSymbolValidator: verify, symbolValidator: verifyMetadata, expectedOutput: "CustomAttributeFormatException"); verifier.VerifyTypeIL("Holder", @" .class private auto ansi beforefieldinit Holder extends [netstandard]System.Object { .custom instance void class Attr`1<string>::.ctor(!0) = ( 01 00 01 61 00 00 ) // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2058 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method Holder::.ctor } // end of class Holder "); void verify(ModuleSymbol module) { var holder = module.GlobalNamespace.GetMember<TypeSymbol>("Holder"); var attrs = holder.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>(\"a\")" }, GetAttributeStrings(attrs)); } void verifyMetadata(ModuleSymbol module) { // https://github.com/dotnet/roslyn/issues/55190 // The compiler should be able to read this attribute argument from metadata. // Once this is fixed, we should be able to use exactly the same 'verify' method for both source and metadata. var holder = module.GlobalNamespace.GetMember<TypeSymbol>("Holder"); var attrs = holder.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>" }, GetAttributeStrings(attrs)); } } [Fact] public void GenericAttributeParameter_02() { var source = @" using System; class Attr<T> : Attribute { public Attr(object param) { } } class Outer<T2> { [Attr<object>(default(T2))] // 1 class Program1 { } [Attr<T2>(default(T2))] // 2, 3 class Program2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<object>(default(T2))] // 1 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(7, 19), // (10,6): error CS8967: 'T2': an attribute type argument cannot use type parameters // [Attr<T2>(default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Attr<T2>").WithArguments("T2").WithLocation(10, 6), // (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<T2>(default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(10, 15)); } [Fact] public void GenericAttributeOnAssembly() { var source = @" using System; [assembly: Attr<string>] [assembly: Attr<int>] [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class Attr<T> : Attribute { } "; var verifier = CompileAndVerify(source, symbolValidator: verify, sourceSymbolValidator: verifySource); verifier.VerifyDiagnostics(); void verify(ModuleSymbol module) { var attrs = module.ContainingAssembly.GetAttributes(); Assert.Equal(new[] { "System.Runtime.CompilerServices.CompilationRelaxationsAttribute(8)", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)", "System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)", "Attr<System.String>", "Attr<System.Int32>" }, GetAttributeStrings(attrs)); } void verifySource(ModuleSymbol module) { var attrs = module.ContainingAssembly.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>", "Attr<System.Int32>" }, GetAttributeStrings(attrs)); } } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttributeReflection_OpenGeneric() { var source = @" using System; class Attr<T> : Attribute { } class Attr2<T> : Attribute { } [Attr<string>] [Attr2<int>] class Holder { } class Program { static void Main() { try { var attr = Attribute.GetCustomAttribute(typeof(Holder), typeof(Attr<>)); Console.Write(attr?.ToString() ?? ""not found""); } catch (Exception e) { Console.Write(e.GetType().Name); } } } "; var verifier = CompileAndVerify(source, expectedOutput: "not found"); verifier.VerifyDiagnostics(); } [Fact] public void GenericAttributeNested() { var source = @" using System; class Attr<T> : Attribute { } [Attr<Attr<string>>] class C { } "; var verifier = CompileAndVerify(source, symbolValidator: verify, sourceSymbolValidator: verify); verifier.VerifyDiagnostics(); void verify(ModuleSymbol module) { var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var attrs = c.GetAttributes(); Assert.Equal(new[] { "Attr<Attr<System.String>>" }, GetAttributeStrings(attrs)); } } #endregion } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests : WellKnownAttributesTestBase { static readonly string[] s_autoPropAttributes = new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }; static readonly string[] s_backingFieldAttributes = new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Diagnostics.DebuggerBrowsableAttribute(System.Diagnostics.DebuggerBrowsableState.Never)" }; #region Function Tests [Fact, WorkItem(26464, "https://github.com/dotnet/roslyn/issues/26464")] public void TestNullInAssemblyVersionAttribute() { var source = @" [assembly: System.Reflection.AssemblyVersionAttribute(null)] class Program { }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithDeterministic(true)); comp.VerifyDiagnostics( // (2,55): error CS7034: The specified version string does not conform to the required format - major[.minor[.build[.revision]]] // [assembly: System.Reflection.AssemblyVersionAttribute(null)] Diagnostic(ErrorCode.ERR_InvalidVersionFormat, "null").WithLocation(2, 55) ); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void TestQuickAttributeChecker() { var predefined = QuickAttributeChecker.Predefined; var typeForwardedTo = SyntaxFactory.Attribute(SyntaxFactory.ParseName("TypeForwardedTo")); var typeIdentifier = SyntaxFactory.Attribute(SyntaxFactory.ParseName("TypeIdentifier")); Assert.True(predefined.IsPossibleMatch(typeForwardedTo, QuickAttributes.TypeForwardedTo)); Assert.False(predefined.IsPossibleMatch(typeForwardedTo, QuickAttributes.TypeIdentifier)); Assert.False(predefined.IsPossibleMatch(typeForwardedTo, QuickAttributes.None)); Assert.False(predefined.IsPossibleMatch(typeIdentifier, QuickAttributes.TypeForwardedTo)); Assert.True(predefined.IsPossibleMatch(typeIdentifier, QuickAttributes.TypeIdentifier)); Assert.False(predefined.IsPossibleMatch(typeIdentifier, QuickAttributes.None)); var alias1 = SyntaxFactory.Attribute(SyntaxFactory.ParseName("alias1")); var checker1 = WithAliases(predefined, "using alias1 = TypeForwardedToAttribute;"); Assert.True(checker1.IsPossibleMatch(alias1, QuickAttributes.TypeForwardedTo)); Assert.False(checker1.IsPossibleMatch(alias1, QuickAttributes.TypeIdentifier)); var checker1a = WithAliases(checker1, "using alias1 = TypeIdentifierAttribute;"); Assert.True(checker1a.IsPossibleMatch(alias1, QuickAttributes.TypeForwardedTo)); Assert.True(checker1a.IsPossibleMatch(alias1, QuickAttributes.TypeIdentifier)); var checker1b = WithAliases(checker1, "using alias2 = TypeIdentifierAttribute;"); var alias2 = SyntaxFactory.Attribute(SyntaxFactory.ParseName("alias2")); Assert.True(checker1b.IsPossibleMatch(alias1, QuickAttributes.TypeForwardedTo)); Assert.False(checker1b.IsPossibleMatch(alias1, QuickAttributes.TypeIdentifier)); Assert.False(checker1b.IsPossibleMatch(alias2, QuickAttributes.TypeForwardedTo)); Assert.True(checker1b.IsPossibleMatch(alias2, QuickAttributes.TypeIdentifier)); var checker3 = WithAliases(predefined, "using alias3 = TypeForwardedToAttribute; using alias3 = TypeIdentifierAttribute;"); var alias3 = SyntaxFactory.Attribute(SyntaxFactory.ParseName("alias3")); Assert.True(checker3.IsPossibleMatch(alias3, QuickAttributes.TypeForwardedTo)); Assert.True(checker3.IsPossibleMatch(alias3, QuickAttributes.TypeIdentifier)); QuickAttributeChecker WithAliases(QuickAttributeChecker checker, string aliases) { var nodes = Parse(aliases).GetRoot().DescendantNodes().OfType<UsingDirectiveSyntax>(); var list = new SyntaxList<UsingDirectiveSyntax>().AddRange(nodes); return checker.AddAliasesIfAny(list); } } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithMissingType_WithIrrelevantType() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' (during overload resolution of attribute constructors) albeit irrelevant // but C won't exist "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithDiagnostic() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(1)] "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics( // (3,60): error CS1503: Argument 1: cannot convert from 'int' to 'System.Type' // [assembly: System.Runtime.CompilerServices.TypeForwardedTo(1)] Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "System.Type").WithLocation(3, 60) ); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics( // (3,60): error CS1503: Argument 1: cannot convert from 'int' to 'System.Type' // [assembly: System.Runtime.CompilerServices.TypeForwardedTo(1)] Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "System.Type").WithLocation(3, 60) ); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithMissingType_WithRelevantType() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' // but C won't exist "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics( // (2,12): error CS7068: Reference to type 'C' claims it is defined in this assembly, but it is not defined in source or any added modules // [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' Diagnostic(ErrorCode.ERR_MissingTypeInSource, "RefersToLib").WithArguments("C").WithLocation(2, 12) ); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics( // (2,12): error CS7068: Reference to type 'C' claims it is defined in this assembly, but it is not defined in source or any added modules // [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' Diagnostic(ErrorCode.ERR_MissingTypeInSource, "RefersToLib").WithArguments("C").WithLocation(2, 12) ); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithStaticUsing() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" using static RefersToLibAttribute; // Binding this will cause a lookup for 'C' in 'lib'. // Such lookup requires binding 'TypeForwardedTo' attributes (and aliases), but we should not bind other usings, to avoid an infinite recursion. [assembly: System.Reflection.AssemblyTitleAttribute(""title"")] public class Ignore { public void UseStaticUsing() { Method(); } } "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } public static void Method() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithTypeForward_WithIrrelevantType() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' (during overload resolution of attribute constructors) albeit irrelevant [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] // but C is forwarded "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithTypeForward_WithRelevantType() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] // but C is forwarded "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); var newLibComp3 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp3.SourceAssembly.GetAttributes(); newLibComp3.VerifyDiagnostics(); } /// <summary> /// Looking up C explicitly after calling GetAttributes will cause <see cref="SourceAssemblySymbol.GetForwardedTypes"/> to use the cached attributes, rather that do partial binding /// </summary> [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithCheckAttributes() { var cDefinition_cs = @"public class C { }"; var derivedDefinition_cs = @"public class Derived : C { }"; var typeForward_cs = @" [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] "; var origLibComp = CreateCompilation(cDefinition_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithDerivedAndReferenceToLib = CreateCompilation(typeForward_cs + derivedDefinition_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithDerivedAndReferenceToLib.VerifyDiagnostics(); var compWithC = CreateCompilation(cDefinition_cs, assemblyName: "new"); compWithC.VerifyDiagnostics(); var newLibComp = CreateCompilation(typeForward_cs, references: new[] { compWithDerivedAndReferenceToLib.EmitToImageReference(), compWithC.EmitToImageReference() }, assemblyName: "lib"); var attribute = newLibComp.SourceAssembly.GetAttributes().Single(); // GetAttributes binds all attributes Assert.Equal("System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(C))", attribute.ToString()); var derived = (NamedTypeSymbol)newLibComp.GetMember("Derived"); var c = derived.BaseType(); // get C Assert.Equal("C", c.ToTestDisplayString()); Assert.False(c.IsErrorType()); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithTypeForward_WithRelevantType_WithAlias() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" using alias1 = System.Runtime.CompilerServices.TypeForwardedToAttribute; [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' [assembly: alias1(typeof(C))] // but C is forwarded via alias "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithExistingType_WithIrrelevantType() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' (during overload resolution of attribute constructors) albeit irrelevant public class C { } // and C exists here "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithExistingType_WithRelevantType() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' public class C : System.Attribute { } // and C exists here "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] public void TestAssemblyAttributes() { var source = CreateCompilation(@" using System; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""Roslyn.Compilers.UnitTests"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp.UnitTests"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp.Test.Utilities"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.VisualBasic"")] class C { public static void Main() {} } "); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { Symbol assembly = m.ContainingSymbol; var attrs = assembly.GetAttributes(); Assert.Equal(5, attrs.Length); attrs[0].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.UnitTests"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.UnitTests"")", attrs[0].ToString()); attrs[1].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp"")", attrs[1].ToString()); attrs[2].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp.UnitTests"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp.UnitTests"")", attrs[2].ToString()); attrs[3].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp.Test.Utilities"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp.Test.Utilities"")", attrs[3].ToString()); attrs[4].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.VisualBasic"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.VisualBasic"")", attrs[4].ToString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnStringParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { } } [Mark(b: new string[] { ""Hello"", ""World"" }, a: true)] [Mark(b: ""Hello"", true)] static class Program { }", parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (11,2): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Mark(b: new string[] { "Hello", "World" }, a: true)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"Mark(b: new string[] { ""Hello"", ""World"" }, a: true)").WithLocation(11, 2), // (12,7): error CS8323: Named argument 'b' is used out-of-position but is followed by an unnamed argument // [Mark(b: "Hello", true)] Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "b").WithArguments("b").WithLocation(12, 7) ); } [Fact] public void TestNullAsParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; class MarkAttribute : Attribute { public MarkAttribute(params object[] b) { } } [Mark(null)] static class Program { }"); comp.VerifyDiagnostics( ); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnOrderedObjectParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(a: true, b: new object[] { ""Hello"", ""World"" })] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""B.Length={attr.B.Length}, B[0]={attr.B[0]}, B[1]={attr.B[1]}""); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"B.Length=2, B[0]=Hello, B[1]=World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 0, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(b: new object[] { ""Hello"", ""World"" }, a: true)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""B.Length={attr.B.Length}, B[0]={attr.B[0]}, B[1]={attr.B[1]}""); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"B.Length=2, B[0]=Hello, B[1]=World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument2() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { A = a; B = b; } public bool A { get; } public object[] B { get; } } [Mark(b: ""Hello"", a: true)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""A={attr.A}, B.Length={attr.B.Length}, B[0]={attr.B[0]}""); } }", options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"A=True, B.Length=1, B[0]=Hello"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument3() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(true, new object[] { ""Hello"" }, new object[] { ""World"" })] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); var worldArray = (object[])attr.B[1]; Console.Write(worldArray[0]); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 0, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument4() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(a: true, new object[] { ""Hello"" }, new object[] { ""World"" })] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); var worldArray = (object[])attr.B[1]; Console.Write(worldArray[0]); } }", options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 0, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument5() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(b: null, a: true)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write(attr.B == null); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"True"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnNonParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(int a, int b) { A = a; B = b; } public int A { get; } public int B { get; } } [Mark(b: 42, a: 1)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""A={attr.A}, B={attr.B}""); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "A=1, B=42"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, 0 }, attributeData.ConstructorArgumentsSourceIndices); } [WorkItem(984896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984896")] [Fact] public void TestAssemblyAttributesErr() { string code = @" using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using M = System.Math; namespace My { using A.B; // TODO: <Insert justification for suppressing TestId> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(""Test"",""TestId"",Justification=""<Pending>"")] public unsafe partial class A : C, I { } } "; var source = CreateCompilationWithMscorlib40AndSystemCore(code); // the following should not crash source.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, source.SyntaxTrees[0], filterSpanWithinTree: null, includeEarlierStages: true); } [Fact, WorkItem(545326, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545326")] public void TestAssemblyAttributes_Bug13670() { var source = @" using System; [assembly: A(Derived.Str)] public class A: Attribute { public A(string x){} public static void Main() {} } public class Derived: Base { internal const string Str = ""temp""; public override int Goo { get { return 1; } } } public class Base { public virtual int Goo { get { return 0; } } } "; CompileAndVerify(source); } [Fact] public void TestAssemblyAttributesReflection() { var compilation = CreateCompilation(@" using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // These are not pseudo attributes, but encoded as bits in metadata [assembly: AssemblyAlgorithmId(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)] [assembly: AssemblyCultureAttribute("""")] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyFlags(AssemblyNameFlags.Retargetable)] [assembly: AssemblyKeyFile(""MyKey.snk"")] [assembly: AssemblyKeyName(""Key Name"")] [assembly: AssemblyVersion(""1.2.*"")] [assembly: AssemblyFileVersionAttribute(""4.3.2.100"")] class C { public static void Main() {} } "); var attrs = compilation.Assembly.GetAttributes(); Assert.Equal(8, attrs.Length); foreach (var a in attrs) { switch (a.AttributeClass.Name) { case "AssemblyAlgorithmIdAttribute": a.VerifyValue(0, TypedConstantKind.Enum, (int)System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5); Assert.Equal(@"System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)", a.ToString()); break; case "AssemblyCultureAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, ""); Assert.Equal(@"System.Reflection.AssemblyCultureAttribute("""")", a.ToString()); break; case "AssemblyDelaySignAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, true); Assert.Equal(@"System.Reflection.AssemblyDelaySignAttribute(true)", a.ToString()); break; case "AssemblyFlagsAttribute": a.VerifyValue(0, TypedConstantKind.Enum, (int)AssemblyNameFlags.Retargetable); Assert.Equal(@"System.Reflection.AssemblyFlagsAttribute(System.Reflection.AssemblyNameFlags.Retargetable)", a.ToString()); break; case "AssemblyKeyFileAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "MyKey.snk"); Assert.Equal(@"System.Reflection.AssemblyKeyFileAttribute(""MyKey.snk"")", a.ToString()); break; case "AssemblyKeyNameAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "Key Name"); Assert.Equal(@"System.Reflection.AssemblyKeyNameAttribute(""Key Name"")", a.ToString()); break; case "AssemblyVersionAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "1.2.*"); Assert.Equal(@"System.Reflection.AssemblyVersionAttribute(""1.2.*"")", a.ToString()); break; case "AssemblyFileVersionAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "4.3.2.100"); Assert.Equal(@"System.Reflection.AssemblyFileVersionAttribute(""4.3.2.100"")", a.ToString()); break; default: Assert.Equal("Unexpected Attr", a.AttributeClass.Name); break; } } } // Verify that resolving an attribute defined within a class on a class does not cause infinite recursion [Fact] public void TestAttributesOnClassDefinedInClass() { var compilation = CreateCompilation(@" using System; using System.Runtime.CompilerServices; [A.X()] public class A { [AttributeUsage(AttributeTargets.All, allowMultiple = true)] public class XAttribute : Attribute { } } class C { public static void Main() {} } "); var attrs = compilation.SourceModule.GlobalNamespace.GetMember("A").GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("A.XAttribute", attrs.First().AttributeClass.ToDisplayString()); } [Fact] public void TestAttributesOnClassWithConstantDefinedInClass() { var compilation = CreateCompilation(@" using System; [Attr(Goo.p)] class Goo { private const object p = null; } internal class AttrAttribute : Attribute { public AttrAttribute(object p) { } } class C { public static void Main() { } } "); var attrs = compilation.SourceModule.GlobalNamespace.GetMember("Goo").GetAttributes(); Assert.Equal(1, attrs.Length); attrs.First().VerifyValue<object>(0, TypedConstantKind.Primitive, null); } [Fact] public void TestAttributeEmit() { var compilation = CreateCompilation(@" using System; public enum e1 { a, b, c } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class XAttribute : Attribute { public XAttribute(int i) { } public XAttribute(int i, string s) { } public XAttribute(int i, string s, e1 e) { } public XAttribute(object[] o) { } public XAttribute(int[] i) { } public XAttribute(int[] i, string[] s) { } public XAttribute(int[] i, string[] s, e1[] e) { } public int pi { get; set; } public string ps { get; set; } public e1 pe { get; set; } } [X(1, ""hello"", e1.a)] [X(new int[] { 1 }, new string[] { ""hello"" }, new e1[] { e1.a, e1.b, e1.c })] [X(new object[] { 1, ""hello"", e1.a })] class C { public static void Main() {} } "); var verifier = CompileAndVerify(compilation); verifier.VerifyIL("XAttribute..ctor(int)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""System.Attribute..ctor()"" IL_0006: ret }"); } [Fact] public void TestAttributesOnClassProperty() { var compilation = CreateCompilation(@" using System; public class A { [CLSCompliant(true)] public string Prop { get { return null; } } } class C { public static void Main() {} } "); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var type = (NamedTypeSymbol)m.GlobalNamespace.GetMember("A"); var prop = type.GetMember("Prop"); var attrs = prop.GetAttributes(); Assert.Equal(1, attrs.Length); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, true); Assert.Equal("System.CLSCompliantAttribute", attrs.First().AttributeClass.ToDisplayString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(688268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688268")] [Fact] public void Bug688268() { var compilation = CreateCompilation(@" using System; using System.Runtime.InteropServices; using System.Security; public interface I { void _VtblGap1_30(); void _VtblGaP1_30(); } "); System.Action<ModuleSymbol> metadataValidator = delegate (ModuleSymbol module) { var metadata = ((PEModuleSymbol)module).Module; var typeI = (PENamedTypeSymbol)module.GlobalNamespace.GetTypeMembers("I").Single(); var methods = metadata.GetMethodsOfTypeOrThrow(typeI.Handle); Assert.Equal(2, methods.Count); var e = methods.GetEnumerator(); e.MoveNext(); var flags = metadata.GetMethodDefFlagsOrThrow(e.Current); Assert.Equal( MethodAttributes.PrivateScope | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.VtableLayoutMask | MethodAttributes.Abstract | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, flags); e.MoveNext(); flags = metadata.GetMethodDefFlagsOrThrow(e.Current); Assert.Equal( MethodAttributes.PrivateScope | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.VtableLayoutMask | MethodAttributes.Abstract, flags); }; CompileAndVerify( compilation, sourceSymbolValidator: null, symbolValidator: metadataValidator); } [Fact] public void TestAttributesOnPropertyAndGetSet() { string source = @" using System; [AObject(typeof(object), O = A.obj)] public class A { internal const object obj = null; public string RProp { [AObject(new object[] { typeof(string) })] get { return null; } } [AObject(new object[] { 1, ""two"", typeof(string), 3.1415926 })] public object WProp { [AObject(new object[] { new object[] { typeof(string) } })] set { } } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.MDTestAttributeDefLib.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var type = (NamedTypeSymbol)m.GlobalNamespace.GetMember("A"); var attrs = type.GetAttributes(); Assert.Equal("AObjectAttribute(typeof(object), O = null)", attrs.First().ToString()); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeof(object)); attrs.First().VerifyNamedArgumentValue<object>(0, "O", TypedConstantKind.Primitive, null); var prop = type.GetMember<PropertySymbol>("RProp"); attrs = prop.GetMethod.GetAttributes(); Assert.Equal("AObjectAttribute({typeof(string)})", attrs.First().ToString()); attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { typeof(string) }); prop = type.GetMember<PropertySymbol>("WProp"); attrs = prop.GetAttributes(); Assert.Equal(@"AObjectAttribute({1, ""two"", typeof(string), 3.1415926})", attrs.First().ToString()); attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { 1, "two", typeof(string), 3.1415926 }); attrs = prop.SetMethod.GetAttributes(); Assert.Equal(@"AObjectAttribute({{typeof(string)}})", attrs.First().ToString()); attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { new object[] { typeof(string) } }); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [Fact] public void TestFieldAttributeOnPropertyInCSharp7_2() { string source = @" public class A : System.Attribute { } public class Test { [field: System.Obsolete] [field: A] public int P { get; set; } [field: System.Obsolete(""obsolete"", error: true)] public int P2 { get; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (7,6): warning CS8361: Field-targeted attributes on auto-properties are not supported in language version 7.2. Please use language version 7.3 or greater. // [field: System.Obsolete] Diagnostic(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, "field:").WithArguments("7.2", "7.3").WithLocation(7, 6), // (8,6): warning CS8361: Field-targeted attributes on auto-properties are not supported in language version 7.2. Please use language version 7.3 or greater. // [field: A] Diagnostic(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, "field:").WithArguments("7.2", "7.3").WithLocation(8, 6), // (11,6): warning CS8361: Field-targeted attributes on auto-properties are not supported in language version 7.2. Please use language version 7.3 or greater. // [field: System.Obsolete("obsolete", error: true)] Diagnostic(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, "field:").WithArguments("7.2", "7.3").WithLocation(11, 6) ); } [Fact] public void TestFieldAttributesOnAutoProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { public A(int i) { } } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { public B(int i) { } } public class Test { [field: A(1)] public int P { get; set; } [field: A(2)] public int P2 { get; } [B(3)] [field: A(33)] public int P3 { get; } [property: B(4)] [field: A(44)] [field: A(444)] public int P4 { get; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var propAttributesExpected = isFromSource ? new string[0] : s_autoPropAttributes; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.GetMethod.GetAttributes())); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.SetMethod.GetAttributes())); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(1)" }), GetAttributeStrings(field1.GetAttributes())); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop2.GetMethod.GetAttributes())); Assert.Null(prop2.SetMethod); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(2)" }), GetAttributeStrings(field2.GetAttributes())); var prop3 = @class.GetMember<PropertySymbol>("P3"); Assert.Equal("B(3)", prop3.GetAttributes().Single().ToString()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop3.GetMethod.GetAttributes())); Assert.Null(prop3.SetMethod); var field3 = @class.GetMember<FieldSymbol>("<P3>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(33)" }), GetAttributeStrings(field3.GetAttributes())); var prop4 = @class.GetMember<PropertySymbol>("P4"); Assert.Equal("B(4)", prop4.GetAttributes().Single().ToString()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop3.GetMethod.GetAttributes())); Assert.Null(prop4.SetMethod); var field4 = @class.GetMember<FieldSymbol>("<P4>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(44)", "A(444)" }), GetAttributeStrings(field4.GetAttributes())); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestGeneratedTupleAndDynamicAttributesOnAutoProperty() { string source = @" public class Test { public (dynamic a, int b) P { get; set; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); if (isFromSource) { Assert.Empty(field1.GetAttributes()); } else { var dynamicAndTupleNames = new[] { "System.Runtime.CompilerServices.DynamicAttribute({false, true, false})", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})" }; AssertEx.SetEqual(s_backingFieldAttributes.Concat(dynamicAndTupleNames), GetAttributeStrings(field1.GetAttributes())); } }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_SpecialName() { string source = @" public struct Test { [field: System.Runtime.CompilerServices.SpecialName] public static int P { get; set; } public static int P2 { get; set; } [field: System.Runtime.CompilerServices.SpecialName] public static int f; } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); var attributes1 = field1.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.Runtime.CompilerServices.SpecialNameAttribute" }, GetAttributeStrings(attributes1)); } else { AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(attributes1)); } Assert.True(field1.HasSpecialName); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field2.GetAttributes())); Assert.False(field2.HasSpecialName); var field3 = @class.GetMember<FieldSymbol>("f"); var attributes3 = field3.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.Runtime.CompilerServices.SpecialNameAttribute" }, GetAttributeStrings(attributes3)); } else { Assert.Empty(GetAttributeStrings(attributes3)); } }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_NonSerialized() { string source = @" public class Test { [field: System.NonSerialized] public int P { get; set; } public int P2 { get; set; } [field: System.NonSerialized] public int f; } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); var attributes1 = field1.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.NonSerializedAttribute" }, GetAttributeStrings(attributes1)); } else { AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(attributes1)); } Assert.True(field1.IsNotSerialized); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field2.GetAttributes())); Assert.False(field2.IsNotSerialized); var field3 = @class.GetMember<FieldSymbol>("f"); var attributes3 = field3.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.NonSerializedAttribute" }, GetAttributeStrings(attributes3)); } else { Assert.Empty(GetAttributeStrings(attributes3)); } Assert.True(field3.IsNotSerialized); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset() { string source = @" public struct Test { [field: System.Runtime.InteropServices.FieldOffset(0)] public static int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,13): error CS0637: The FieldOffset attribute is not allowed on static or const fields // [field: System.Runtime.InteropServices.FieldOffset(0)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadField, "System.Runtime.InteropServices.FieldOffset").WithArguments("System.Runtime.InteropServices.FieldOffset").WithLocation(4, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset2() { string source = @" public struct Test { [field: System.Runtime.InteropServices.FieldOffset(-1)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,56): error CS0591: Invalid value for argument to 'System.Runtime.InteropServices.FieldOffset' attribute // [field: System.Runtime.InteropServices.FieldOffset(-1)] Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "-1").WithArguments("System.Runtime.InteropServices.FieldOffset").WithLocation(4, 56), // (4,13): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [field: System.Runtime.InteropServices.FieldOffset(-1)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "System.Runtime.InteropServices.FieldOffset").WithLocation(4, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset3() { string source = @" using System.Runtime.InteropServices; [StructLayout(LayoutKind.Auto)] public class Test { [field: FieldOffset(4)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [field: FieldOffset(4)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "FieldOffset").WithLocation(7, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset4() { string source = @" using System.Runtime.InteropServices; public struct Test { [field: FieldOffset(4)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [field: FieldOffset(4)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "FieldOffset").WithLocation(6, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset5() { string source = @" using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit)] public struct Test { public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,16): error CS0625: 'Test.P': instance field in types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute // public int P { get; set; } Diagnostic(ErrorCode.ERR_MissingStructOffset, "P").WithArguments("Test.P").WithLocation(7, 16) ); } [Fact] public void TestWellKnownAttributeOnProperty_FixedBuffer() { string source = @" public class Test { [field: System.Runtime.CompilerServices.FixedBuffer(typeof(int), 0)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,13): error CS8362: Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute on a property // [field: System.Runtime.CompilerServices.FixedBuffer(typeof(int), 0)] Diagnostic(ErrorCode.ERR_DoNotUseFixedBufferAttrOnProperty, "System.Runtime.CompilerServices.FixedBuffer").WithLocation(4, 13) ); } [ConditionalFact(typeof(DesktopOnly))] public void TestWellKnownAttributeOnProperty_DynamicAttribute() { string source = @" public class Test { [field: System.Runtime.CompilerServices.DynamicAttribute()] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,13): error CS1970: Do not use 'System.Runtime.CompilerServices.DynamicAttribute'. Use the 'dynamic' keyword instead. // [field: System.Runtime.CompilerServices.DynamicAttribute()] Diagnostic(ErrorCode.ERR_ExplicitDynamicAttr, "System.Runtime.CompilerServices.DynamicAttribute()").WithLocation(4, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_IsReadOnlyAttribute() { string source = @" namespace System.Runtime.CompilerServices { public class IsReadOnlyAttribute : System.Attribute { } } public class Test { [field: System.Runtime.CompilerServices.IsReadOnlyAttribute()] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage. // [field: System.Runtime.CompilerServices.IsReadOnlyAttribute()] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "System.Runtime.CompilerServices.IsReadOnlyAttribute()").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(8, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_IsByRefLikeAttribute() { string source = @" namespace System.Runtime.CompilerServices { public class IsByRefLikeAttribute : System.Attribute { } } public class Test { [field: System.Runtime.CompilerServices.IsByRefLikeAttribute()] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS8335: Do not use 'System.Runtime.CompilerServices.IsByRefLikeAttribute'. This is reserved for compiler usage. // [field: System.Runtime.CompilerServices.IsByRefLikeAttribute()] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "System.Runtime.CompilerServices.IsByRefLikeAttribute()").WithArguments("System.Runtime.CompilerServices.IsByRefLikeAttribute").WithLocation(8, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_DateTimeConstant() { string source = @" public class Test { [field: System.Runtime.CompilerServices.DateTimeConstant(123456)] public System.DateTime P { get; set; } [field: System.Runtime.CompilerServices.DateTimeConstant(123456)] public int P2 { get; set; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "System.Runtime.CompilerServices.DateTimeConstantAttribute(123456)" }), GetAttributeStrings(field1.GetAttributes())); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "System.Runtime.CompilerServices.DateTimeConstantAttribute(123456)" }), GetAttributeStrings(field2.GetAttributes())); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_DecimalConstant() { string source = @" public class Test { [field: System.Runtime.CompilerServices.DecimalConstant(0, 0, 100, 100, 100)] public decimal P { get; set; } [field: System.Runtime.CompilerServices.DecimalConstant(0, 0, 100, 100, 100)] public int P2 { get; set; } [field: System.Runtime.CompilerServices.DecimalConstant(0, 0, 100, 100, 100)] public decimal field; } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Diagnostics.DebuggerBrowsableAttribute(System.Diagnostics.DebuggerBrowsableState.Never)" }; var constantExpected = "1844674407800451891300"; string[] decimalAttributeExpected = new[] { "System.Runtime.CompilerServices.DecimalConstantAttribute(0, 0, 100, 100, 100)" }; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); if (isFromSource) { AssertEx.SetEqual(fieldAttributesExpected.Concat(decimalAttributeExpected), GetAttributeStrings(field1.GetAttributes())); } else { AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field1.GetAttributes())); Assert.Equal(constantExpected, field1.ConstantValue.ToString()); } var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(decimalAttributeExpected), GetAttributeStrings(field2.GetAttributes())); var field3 = @class.GetMember<FieldSymbol>("field"); if (isFromSource) { AssertEx.SetEqual(decimalAttributeExpected, GetAttributeStrings(field3.GetAttributes())); } else { Assert.Empty(GetAttributeStrings(field3.GetAttributes())); Assert.Equal(constantExpected, field3.ConstantValue.ToString()); } }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_TupleElementNamesAttribute() { string source = @" namespace System.Runtime.CompilerServices { public sealed class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] transformNames) { } } } public class Test { [field: System.Runtime.CompilerServices.TupleElementNamesAttribute(new[] { ""hello"" })] public int P { get; set; } } "; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (11,13): error CS8138: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [field: System.Runtime.CompilerServices.TupleElementNamesAttribute(new[] { "hello" })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, @"System.Runtime.CompilerServices.TupleElementNamesAttribute(new[] { ""hello"" })").WithLocation(11, 13) ); } [Fact] public void TestWellKnownEarlyAttributeOnProperty_Obsolete() { string source = @" public class Test { [field: System.Obsolete] public int P { get; set; } [field: System.Obsolete(""obsolete"", error: true)] public int P2 { get; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var propAttributesExpected = isFromSource ? new string[0] : s_autoPropAttributes; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "System.ObsoleteAttribute" }), GetAttributeStrings(field1.GetAttributes())); Assert.Equal(ObsoleteAttributeKind.Obsolete, field1.ObsoleteAttributeData.Kind); Assert.Null(field1.ObsoleteAttributeData.Message); Assert.False(field1.ObsoleteAttributeData.IsError); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { @"System.ObsoleteAttribute(""obsolete"", true)" }), GetAttributeStrings(field2.GetAttributes())); Assert.Equal(ObsoleteAttributeKind.Obsolete, field2.ObsoleteAttributeData.Kind); Assert.Equal("obsolete", field2.ObsoleteAttributeData.Message); Assert.True(field2.ObsoleteAttributeData.IsError); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestFieldAttributesOnProperty() { string source = @" public class A : System.Attribute { } public class Test { [field: A] public int P { get => throw null; set => throw null; } [field: A] public int P2 { get => throw null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(9, 6), // (6,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(6, 6) ); } [Fact] public void TestFieldAttributesOnPropertyAccessors() { string source = @" public class A : System.Attribute { } public class Test { public int P { [field: A] get => throw null; set => throw null; } public int P2 { [field: A] get; set; } public int P3 { [field: A] get => throw null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. // public int P { [field: A] get => throw null; set => throw null; } Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return").WithLocation(6, 21), // (7,22): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. // public int P2 { [field: A] get; set; } Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return").WithLocation(7, 22), // (8,22): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. // public int P3 { [field: A] get => throw null; } Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return").WithLocation(8, 22) ); } [Fact] public void TestMultipleFieldAttributesOnProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = false) ] public class Single : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class Multiple : System.Attribute { } public class Test { [field: Single] [field: Single] [field: Multiple] [field: Multiple] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,13): error CS0579: Duplicate 'Single' attribute // [field: Single] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Single").WithArguments("Single").WithLocation(11, 13) ); } [Fact] public void TestInheritedFieldAttributesOnOverriddenProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.All, Inherited = true) ] public class A : System.Attribute { public A(int i) { } } public class Base { [field: A(1)] [A(2)] public virtual int P { get; set; } } public class Derived : Base { public override int P { get; set; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var parent = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); bool isFromSource = parent is SourceNamedTypeSymbol; var propAttributesExpected = isFromSource ? new string[0] : s_autoPropAttributes; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = parent.GetMember<PropertySymbol>("P"); Assert.Equal("A(2)", prop1.GetAttributes().Single().ToString()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.GetMethod.GetAttributes())); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.SetMethod.GetAttributes())); var field1 = parent.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(1)" }), GetAttributeStrings(field1.GetAttributes())); var child = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var prop2 = child.GetMember<PropertySymbol>("P"); Assert.Empty(prop2.GetAttributes()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop2.GetMethod.GetAttributes())); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop2.SetMethod.GetAttributes())); var field2 = child.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field2.GetAttributes())); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestPropertyTargetedFieldAttributesOnAutoProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Property) ] public class A : System.Attribute { } public class Test { [field: A] public int P { get; set; } [field: A] public int P2 { get; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,13): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [field: A] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "property, indexer").WithLocation(10, 13), // (7,13): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [field: A] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "property, indexer").WithLocation(7, 13) ); } [Fact] public void TestClassTargetedFieldAttributesOnAutoProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Class) ] public class ClassAllowed : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Field) ] public class FieldAllowed : System.Attribute { } public class Test { [field: ClassAllowed] // error 1 [field: FieldAllowed] public int P { get; set; } [field: ClassAllowed] // error 2 [field: FieldAllowed] public int P2 { get; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,13): error CS0592: Attribute 'ClassAllowed' is not valid on this declaration type. It is only valid on 'class' declarations. // [field: ClassAllowed] // error 2 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "ClassAllowed").WithArguments("ClassAllowed", "class").WithLocation(14, 13), // (10,13): error CS0592: Attribute 'ClassAllowed' is not valid on this declaration type. It is only valid on 'class' declarations. // [field: ClassAllowed] // error 1 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "ClassAllowed").WithArguments("ClassAllowed", "class").WithLocation(10, 13) ); } [Fact] public void TestImproperlyTargetedFieldAttributesOnProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Property) ] public class A : System.Attribute { } public class Test { [field: A] public int P { get => throw null; set => throw null; } [field: A] public int P2 { get => throw null; } [field: A] public int P3 { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(10, 6), // (13,13): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [field: A] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "property, indexer").WithLocation(13, 13), // (7,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(7, 6) ); } [Fact] public void TestAttributesOnEvents() { string source = @" public class AA : System.Attribute { } public class BB : System.Attribute { } public class CC : System.Attribute { } public class DD : System.Attribute { } public class EE : System.Attribute { } public class FF : System.Attribute { } public class GG : System.Attribute { } public class HH : System.Attribute { } public class II : System.Attribute { } public class JJ : System.Attribute { } public class Test { [AA] //in event decl public event System.Action E1; [event: BB] //in event decl public event System.Action E2; [method: CC] //in both accessors public event System.Action E3; [field: DD] //on field public event System.Action E4; [EE] //in event decl public event System.Action E5 { add { } remove { } } [event: FF] //in event decl public event System.Action E6 { add { } remove { } } public event System.Action E7 { [GG] add { } remove { } } //in accessor public event System.Action E8 { [method: HH] add { } remove { } } //in accessor public event System.Action E9 { [param: II] add { } remove { } } //on parameter (after .param[1]) public event System.Action E10 { [return: JJ] add { } remove { } } //on return (after .param[0]) } "; Func<bool, Action<ModuleSymbol>> symbolValidator = isFromSource => moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var event1 = @class.GetMember<EventSymbol>("E1"); var event2 = @class.GetMember<EventSymbol>("E2"); var event3 = @class.GetMember<EventSymbol>("E3"); var event4 = @class.GetMember<EventSymbol>("E4"); var event5 = @class.GetMember<EventSymbol>("E5"); var event6 = @class.GetMember<EventSymbol>("E6"); var event7 = @class.GetMember<EventSymbol>("E7"); var event8 = @class.GetMember<EventSymbol>("E8"); var event9 = @class.GetMember<EventSymbol>("E9"); var event10 = @class.GetMember<EventSymbol>("E10"); var accessorsExpected = isFromSource ? new string[0] : new[] { "CompilerGeneratedAttribute" }; Assert.Equal("AA", GetSingleAttributeName(event1)); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event1.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event1.RemoveMethod.GetAttributes())); if (isFromSource) { AssertNoAttributes(event1.AssociatedField); Assert.Equal(0, event1.GetFieldAttributes().Length); } Assert.Equal("BB", GetSingleAttributeName(event2)); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event2.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event2.RemoveMethod.GetAttributes())); if (isFromSource) { AssertNoAttributes(event2.AssociatedField); Assert.Equal(0, event2.GetFieldAttributes().Length); } AssertNoAttributes(event3); AssertEx.SetEqual(accessorsExpected.Concat(new[] { "CC" }), GetAttributeNames(event3.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected.Concat(new[] { "CC" }), GetAttributeNames(event3.RemoveMethod.GetAttributes())); if (isFromSource) { AssertNoAttributes(event3.AssociatedField); Assert.Equal(0, event3.GetFieldAttributes().Length); } AssertNoAttributes(event4); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event4.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event4.RemoveMethod.GetAttributes())); if (isFromSource) { Assert.Equal("DD", GetSingleAttributeName(event4.AssociatedField)); Assert.Equal("DD", event4.GetFieldAttributes().Single().AttributeClass.Name); } Assert.Equal("EE", GetSingleAttributeName(event5)); AssertNoAttributes(event5.AddMethod); AssertNoAttributes(event5.RemoveMethod); Assert.Equal("FF", GetSingleAttributeName(event6)); AssertNoAttributes(event6.AddMethod); AssertNoAttributes(event6.RemoveMethod); AssertNoAttributes(event7); Assert.Equal("GG", GetSingleAttributeName(event7.AddMethod)); AssertNoAttributes(event7.RemoveMethod); AssertNoAttributes(event8); Assert.Equal("HH", GetSingleAttributeName(event8.AddMethod)); AssertNoAttributes(event8.RemoveMethod); AssertNoAttributes(event9); AssertNoAttributes(event9.AddMethod); AssertNoAttributes(event9.RemoveMethod); Assert.Equal("II", GetSingleAttributeName(event9.AddMethod.Parameters.Single())); AssertNoAttributes(event10); AssertNoAttributes(event10.AddMethod); AssertNoAttributes(event10.RemoveMethod); Assert.Equal("JJ", event10.AddMethod.GetReturnTypeAttributes().Single().AttributeClass.Name); }; CompileAndVerify(source, sourceSymbolValidator: symbolValidator(true), symbolValidator: symbolValidator(false)); } [Fact] public void TestAttributesOnEvents_NoDuplicateDiagnostics() { string source = @" public class AA : System.Attribute { } public class BB : System.Attribute { } public class CC : System.Attribute { } public class DD : System.Attribute { } public class EE : System.Attribute { } public class FF : System.Attribute { } public class GG : System.Attribute { } public class HH : System.Attribute { } public class II : System.Attribute { } public class JJ : System.Attribute { } public class Test { [AA(0)] //in event decl public event System.Action E1; [event: BB(0)] //in event decl public event System.Action E2; [method: CC(0)] //in both accessors public event System.Action E3; [field: DD(0)] //on field public event System.Action E4; [EE(0)] //in event decl public event System.Action E5 { add { } remove { } } [event: FF(0)] //in event decl public event System.Action E6 { add { } remove { } } public event System.Action E7 { [GG(0)] add { } remove { } } //in accessor public event System.Action E8 { [method: HH(0)] add { } remove { } } //in accessor public event System.Action E9 { [param: II(0)] add { } remove { } } //on parameter (after .param[1]) public event System.Action E10 { [return: JJ(0)] add { } remove { } } //on return (after .param[0]) } "; CreateCompilation(source).VerifyDiagnostics( // (15,6): error CS1729: 'AA' does not contain a constructor that takes 1 arguments // [AA(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "AA(0)").WithArguments("AA", "1"), // (17,13): error CS1729: 'BB' does not contain a constructor that takes 1 arguments // [event: BB(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "BB(0)").WithArguments("BB", "1"), // (19,14): error CS1729: 'CC' does not contain a constructor that takes 1 arguments // [method: CC(0)] //in both accessors Diagnostic(ErrorCode.ERR_BadCtorArgCount, "CC(0)").WithArguments("CC", "1"), // (21,13): error CS1729: 'DD' does not contain a constructor that takes 1 arguments // [field: DD(0)] //on field Diagnostic(ErrorCode.ERR_BadCtorArgCount, "DD(0)").WithArguments("DD", "1"), // (24,6): error CS1729: 'EE' does not contain a constructor that takes 1 arguments // [EE(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "EE(0)").WithArguments("EE", "1"), // (26,13): error CS1729: 'FF' does not contain a constructor that takes 1 arguments // [event: FF(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "FF(0)").WithArguments("FF", "1"), // (29,38): error CS1729: 'GG' does not contain a constructor that takes 1 arguments // public event System.Action E7 { [GG(0)] add { } remove { } } //in accessor Diagnostic(ErrorCode.ERR_BadCtorArgCount, "GG(0)").WithArguments("GG", "1"), // (30,46): error CS1729: 'HH' does not contain a constructor that takes 1 arguments // public event System.Action E8 { [method: HH(0)] add { } remove { } } //in accessor Diagnostic(ErrorCode.ERR_BadCtorArgCount, "HH(0)").WithArguments("HH", "1"), // (31,45): error CS1729: 'II' does not contain a constructor that takes 1 arguments // public event System.Action E9 { [param: II(0)] add { } remove { } } //on parameter (after .param[1]) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "II(0)").WithArguments("II", "1"), // (32,47): error CS1729: 'JJ' does not contain a constructor that takes 1 arguments // public event System.Action E10 { [return: JJ(0)] add { } remove { } } //on return (after .param[0]) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "JJ(0)").WithArguments("JJ", "1"), // (22,32): warning CS0067: The event 'Test.E4' is never used // public event System.Action E4; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E4").WithArguments("Test.E4"), // (18,32): warning CS0067: The event 'Test.E2' is never used // public event System.Action E2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E2").WithArguments("Test.E2"), // (20,32): warning CS0067: The event 'Test.E3' is never used // public event System.Action E3; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E3").WithArguments("Test.E3"), // (16,32): warning CS0067: The event 'Test.E1' is never used // public event System.Action E1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("Test.E1")); } [Fact] public void TestAttributesOnIndexer_NoDuplicateDiagnostics() { string source = @" public class AA : System.Attribute { } public class BB : System.Attribute { } public class CC : System.Attribute { } public class DD : System.Attribute { } public class EE : System.Attribute { } public class Test { public int this[[AA(0)]int x] { [return: BB(0)] [CC(0)] get { return x; } [param: DD(0)] [EE(0)] set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,22): error CS1729: 'AA' does not contain a constructor that takes 1 arguments // public int this[[AA(0)]int x] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "AA(0)").WithArguments("AA", "1"), // (13,10): error CS1729: 'CC' does not contain a constructor that takes 1 arguments // [CC(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "CC(0)").WithArguments("CC", "1"), // (12,18): error CS1729: 'BB' does not contain a constructor that takes 1 arguments // [return: BB(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "BB(0)").WithArguments("BB", "1"), // (16,17): error CS1729: 'DD' does not contain a constructor that takes 1 arguments // [param: DD(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "DD(0)").WithArguments("DD", "1"), // (17,10): error CS1729: 'EE' does not contain a constructor that takes 1 arguments // [EE(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "EE(0)").WithArguments("EE", "1")); } private static string GetSingleAttributeName(Symbol symbol) { return symbol.GetAttributes().Single().AttributeClass.Name; } private static void AssertNoAttributes(Symbol symbol) { Assert.Equal(0, symbol.GetAttributes().Length); } [Fact] public void TestAttributesOnDelegates() { string source = @" using System; public class TypeAttribute : System.Attribute { } public class ParamAttribute : System.Attribute { } public class ReturnTypeAttribute : System.Attribute { } public class TypeParamAttribute : System.Attribute { } class C { [TypeAttribute] [return: ReturnTypeAttribute] public delegate T Delegate<[TypeParamAttribute]T> ([ParamAttribute]T p1, [param: ParamAttribute]ref T p2, [ParamAttribute]out T p3); public delegate int Delegate2 ([ParamAttribute]int p1 = 0, [param: ParamAttribute]params int[] p2); static void Main() { typeof(Delegate<int>).GetCustomAttributes(false); } }"; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var type = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var typeAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeAttribute"); var paramAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ParamAttribute"); var returnTypeAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ReturnTypeAttribute"); var typeParamAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeParamAttribute"); // Verify delegate type attribute var delegateType = type.GetTypeMember("Delegate"); Assert.Equal(1, delegateType.GetAttributes(typeAttrType).Count()); // Verify type parameter attribute var typeParameters = delegateType.TypeParameters; Assert.Equal(1, typeParameters.Length); Assert.Equal(1, typeParameters[0].GetAttributes(typeParamAttrType).Count()); // Verify delegate methods (return type/parameters) attributes // Invoke method // 1) Has return type attributes from delegate declaration syntax // 2) Has parameter attributes from delegate declaration syntax var invokeMethod = delegateType.GetMethod("Invoke"); Assert.Equal(1, invokeMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, returnTypeAttrType, TypeCompareKind.ConsiderEverything2)).Count()); Assert.Equal(typeParameters[0], invokeMethod.ReturnType); var parameters = invokeMethod.GetParameters(); Assert.Equal(3, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal("p3", parameters[2].Name); Assert.Equal(1, parameters[2].GetAttributes(paramAttrType).Count()); // Delegate Constructor: // 1) Doesn't have any return type attributes // 2) Doesn't have any parameter attributes var ctor = delegateType.GetMethod(".ctor"); Assert.Equal(0, ctor.GetReturnTypeAttributes().Length); parameters = ctor.GetParameters(); Assert.Equal(2, parameters.Length); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.Equal(0, parameters[1].GetAttributes().Length); // BeginInvoke method: // 1) Doesn't have any return type attributes // 2) Has parameter attributes from delegate declaration parameters syntax var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke"); Assert.Equal(0, beginInvokeMethod.GetReturnTypeAttributes().Length); parameters = beginInvokeMethod.GetParameters(); Assert.Equal(5, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal("p3", parameters[2].Name); Assert.Equal(1, parameters[2].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[3].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[4].GetAttributes(paramAttrType).Count()); // EndInvoke method: // 1) Has return type attributes from delegate declaration syntax // 2) Has parameter attributes from delegate declaration syntax // only for ref/out parameters. var endInvokeMethod = (MethodSymbol)delegateType.GetMember("EndInvoke"); Assert.Equal(1, endInvokeMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, returnTypeAttrType, TypeCompareKind.ConsiderEverything2)).Count()); parameters = endInvokeMethod.GetParameters(); Assert.Equal(3, parameters.Length); Assert.Equal("p2", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p3", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[2].GetAttributes(paramAttrType).Count()); }; CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); } [Fact] public void TestAttributesOnDelegates_NoDuplicateDiagnostics() { string source = @" public class TypeAttribute : System.Attribute { } public class ParamAttribute1 : System.Attribute { } public class ParamAttribute2 : System.Attribute { } public class ParamAttribute3 : System.Attribute { } public class ParamAttribute4 : System.Attribute { } public class ParamAttribute5 : System.Attribute { } public class ReturnTypeAttribute : System.Attribute { } public class TypeParamAttribute : System.Attribute { } class C { [TypeAttribute(0)] [return: ReturnTypeAttribute(0)] public delegate T Delegate<[TypeParamAttribute(0)]T> ([ParamAttribute1(0)]T p1, [param: ParamAttribute2(0)]ref T p2, [ParamAttribute3(0)]out T p3); public delegate int Delegate2 ([ParamAttribute4(0)]int p1 = 0, [param: ParamAttribute5(0)]params int[] p2); }"; CreateCompilation(source).VerifyDiagnostics( // (13,6): error CS1729: 'TypeAttribute' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "TypeAttribute(0)").WithArguments("TypeAttribute", "1"), // (15,33): error CS1729: 'TypeParamAttribute' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "TypeParamAttribute(0)").WithArguments("TypeParamAttribute", "1"), // (15,60): error CS1729: 'ParamAttribute1' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute1(0)").WithArguments("ParamAttribute1", "1"), // (15,93): error CS1729: 'ParamAttribute2' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute2(0)").WithArguments("ParamAttribute2", "1"), // (15,123): error CS1729: 'ParamAttribute3' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute3(0)").WithArguments("ParamAttribute3", "1"), // (14,14): error CS1729: 'ReturnTypeAttribute' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ReturnTypeAttribute(0)").WithArguments("ReturnTypeAttribute", "1"), // (17,37): error CS1729: 'ParamAttribute4' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute4(0)").WithArguments("ParamAttribute4", "1"), // (17,76): error CS1729: 'ParamAttribute5' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute5(0)").WithArguments("ParamAttribute5", "1")); } [Fact] public void TestAttributesOnDelegateWithOptionalAndParams() { string source = @" using System; public class ParamAttribute : System.Attribute { } class C { public delegate int Delegate ([ParamAttribute]int p1 = 0, [param: ParamAttribute]params int[] p2); static void Main() { typeof(Delegate).GetCustomAttributes(false); } }"; Func<bool, Action<ModuleSymbol>> symbolValidator = isFromMetadata => moduleSymbol => { var type = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var paramAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ParamAttribute"); // Verify delegate type attribute var delegateType = type.GetTypeMember("Delegate"); // Verify delegate methods (return type/parameters) attributes // Invoke method has parameter attributes from delegate declaration syntax var invokeMethod = (MethodSymbol)delegateType.GetMember("Invoke"); var parameters = invokeMethod.GetParameters(); Assert.Equal(2, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); if (isFromMetadata) { // verify ParamArrayAttribute on p2 VerifyParamArrayAttribute(parameters[1]); } // Delegate Constructor: Doesn't have any parameter attributes var ctor = (MethodSymbol)delegateType.GetMember(".ctor"); parameters = ctor.GetParameters(); Assert.Equal(2, parameters.Length); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.Equal(0, parameters[1].GetAttributes().Length); // BeginInvoke method: Has parameter attributes from delegate declaration parameters syntax var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke"); parameters = beginInvokeMethod.GetParameters(); Assert.Equal(4, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[2].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[3].GetAttributes(paramAttrType).Count()); if (isFromMetadata) { // verify no ParamArrayAttribute on p2 VerifyParamArrayAttribute(parameters[1], expected: false); } }; CompileAndVerify(source, sourceSymbolValidator: symbolValidator(false), symbolValidator: symbolValidator(true)); } [Fact] public void TestAttributesOnEnumField() { string source = @" using System; using System.Collections.Generic; using System.Reflection; using CustomAttribute; using AN = CustomAttribute.AttrName; // Use AttrName without Attribute suffix [assembly: AN(UShortField = 4321)] [assembly: AN(UShortField = 1234)] // TODO: below attribute seems to be an ambiguous attribute specification // TODO: modify the test assembly to remove ambiguity // [module: AttrName(TypeField = typeof(System.IO.FileStream))] namespace AttributeTest { class Goo { public class NestedClass { // enum as object [AllInheritMultiple(System.IO.FileMode.Open, BindingFlags.DeclaredOnly | BindingFlags.Public, UIntField = 123 * Field)] internal const uint Field = 10; } [AllInheritMultiple(new char[] { 'q', 'c' }, """")] [AllInheritMultiple()] enum NestedEnum { zero, one = 1, [AllInheritMultiple(null, 256, 0f, -1, AryField = new ulong[] { 0, 1, 12345657 })] [AllInheritMultipleAttribute(typeof(Dictionary<string, int>), 255 + NestedClass.Field, -0.0001f, 3 - (short)NestedEnum.oneagain)] three = 3, oneagain = one } } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; var compilation = CreateCompilation(source, references, options: TestOptions.ReleaseDll); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var attrs = m.GetAttributes(); // Assert.Equal(1, attrs.Count); // Assert.Equal("CustomAttribute.AttrName", attrs[0].AttributeClass.ToDisplayString()); // attrs[0].VerifyValue<Type>(0, "TypeField", TypedConstantKind.Type, typeof(System.IO.FileStream)); var assembly = m.ContainingSymbol; attrs = assembly.GetAttributes(); Assert.Equal(2, attrs.Length); Assert.Equal("CustomAttribute.AttrName", attrs[0].AttributeClass.ToDisplayString()); attrs[1].VerifyNamedArgumentValue<ushort>(0, "UShortField", TypedConstantKind.Primitive, 1234); var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var top = (NamedTypeSymbol)ns.GetMember("Goo"); var type = top.GetMember<NamedTypeSymbol>("NestedClass"); var field = type.GetMember<FieldSymbol>("Field"); attrs = field.GetAttributes(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attrs[0].AttributeClass.ToDisplayString()); attrs[0].VerifyValue(0, TypedConstantKind.Enum, (int)FileMode.Open); attrs[0].VerifyValue(1, TypedConstantKind.Enum, (int)(BindingFlags.DeclaredOnly | BindingFlags.Public)); attrs[0].VerifyNamedArgumentValue<uint>(0, "UIntField", TypedConstantKind.Primitive, 1230); var nenum = top.GetMember<TypeSymbol>("NestedEnum"); attrs = nenum.GetAttributes(); Assert.Equal(2, attrs.Length); attrs[0].VerifyValue(0, TypedConstantKind.Array, new char[] { 'q', 'c' }); Assert.Equal(SyntaxKind.Attribute, attrs[0].ApplicationSyntaxReference.GetSyntax().Kind()); var syntax = (AttributeSyntax)attrs[0].ApplicationSyntaxReference.GetSyntax(); Assert.Equal(2, syntax.ArgumentList.Arguments.Count()); syntax = (AttributeSyntax)attrs[1].ApplicationSyntaxReference.GetSyntax(); Assert.Equal(0, syntax.ArgumentList.Arguments.Count()); attrs = nenum.GetMember("three").GetAttributes(); Assert.Equal(2, attrs.Length); attrs[0].VerifyValue<object>(0, TypedConstantKind.Primitive, null); attrs[0].VerifyValue<long>(1, TypedConstantKind.Primitive, 256); attrs[0].VerifyValue<float>(2, TypedConstantKind.Primitive, 0); attrs[0].VerifyValue<short>(3, TypedConstantKind.Primitive, -1); attrs[0].VerifyNamedArgumentValue<ulong[]>(0, "AryField", TypedConstantKind.Array, new ulong[] { 0, 1, 12345657 }); attrs[1].VerifyValue<object>(0, TypedConstantKind.Type, typeof(Dictionary<string, int>)); attrs[1].VerifyValue<long>(1, TypedConstantKind.Primitive, 265); attrs[1].VerifyValue<float>(2, TypedConstantKind.Primitive, -0.0001f); attrs[1].VerifyValue<short>(3, TypedConstantKind.Primitive, 2); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] public void TestAttributesOnDelegate() { string source = @" using System; using System.Collections.Generic; using CustomAttribute; namespace AttributeTest { public class Goo { [AllInheritMultiple(new object[] { 0, """", null }, 255, -127 - 1, AryProp = new object[] { new object[] { """", typeof(IList<string>) } })] public delegate void NestedSubDele([AllInheritMultiple()]string p1, [Derived(typeof(string[, ,]))]string p2); } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Goo"); var dele = (NamedTypeSymbol)type.GetTypeMember("NestedSubDele"); var attrs = dele.GetAttributes(); attrs.First().VerifyValue<object>(0, TypedConstantKind.Array, new object[] { 0, "", null }); attrs.First().VerifyValue<byte>(1, TypedConstantKind.Primitive, 255); attrs.First().VerifyValue<sbyte>(2, TypedConstantKind.Primitive, -128); attrs.First().VerifyNamedArgumentValue<object[]>(0, "AryProp", TypedConstantKind.Array, new object[] { new object[] { "", typeof(IList<string>) } }); var mem = dele.GetMember<MethodSymbol>("Invoke"); attrs = mem.Parameters[0].GetAttributes(); Assert.Equal(1, attrs.Length); attrs = mem.Parameters[1].GetAttributes(); Assert.Equal(1, attrs.Length); attrs[0].VerifyValue<object>(0, TypedConstantKind.Type, typeof(string[,,])); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [Fact] public void TestAttributesUseBaseAttributeField() { string source = @" using System; namespace AttributeTest { public interface IGoo { [CustomAttribute.Derived(new object[] { 1, null, ""Hi"" }, ObjectField = 2)] int F(int p); } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetMember<MethodSymbol>("F").GetAttributes(); Assert.Equal(@"CustomAttribute.DerivedAttribute({1, null, ""Hi""}, ObjectField = 2)", attrs.First().ToString()); attrs.First().VerifyValue<object>(0, TypedConstantKind.Array, new object[] { 1, null, "Hi" }); attrs.First().VerifyNamedArgumentValue<object>(0, "ObjectField", TypedConstantKind.Primitive, 2); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007a() { string source = @" using System; using X; using Z; namespace X { public class AttrAttribute : Attribute { } } namespace Z { public class Attr { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("X.AttrAttribute", attrs[0].AttributeClass.ToDisplayString()); CompileAndVerify(compilation).VerifyDiagnostics(); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007b() { string source = @" using System; using X; using Z; namespace X { public class AttrAttribute : Attribute { } public class Attr : Attribute { } } namespace Z { public class Attr : Attribute { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("X.AttrAttribute", attrs[0].AttributeClass.ToDisplayString()); CompileAndVerify(compilation).VerifyDiagnostics(); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007c() { string source = @" using System; using X; using Y; using Z; namespace X { public class AttrAttribute /*: Attribute*/ { } } namespace Y { public class AttrAttribute /*: Attribute*/ { } } namespace Z { public class Attr : Attribute { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("Z.Attr", attrs[0].AttributeClass.ToDisplayString()); CompileAndVerify(compilation).VerifyDiagnostics(); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007d() { string source = @" using System; using X; using Y; using Z; namespace X { public class AttrAttribute : Attribute { } } namespace Y { public class AttrAttribute : Attribute { } } namespace Z { public class Attr : Attribute { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("Z.Attr", attrs[0].AttributeClass.ToDisplayString()); var syntax = attrs.Single().ApplicationSyntaxReference.GetSyntax(); Assert.NotNull(syntax); Assert.IsType<AttributeSyntax>(syntax); CompileAndVerify(compilation).VerifyDiagnostics(); } [Fact] public void TestAttributesWithParamArrayInCtor01() { string source = @" using System; using CustomAttribute; namespace AttributeTest { [AllInheritMultiple(new char[] { ' '}, """")] public interface IGoo { } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> sourceAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "" }); Assert.True(attrs.First().AttributeConstructor.Parameters.Last().IsParams); }; Action<ModuleSymbol> mdAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "" }); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: sourceAttributeValidator, symbolValidator: mdAttributeValidator); } [Fact] public void TestAttributesWithParamArrayInCtor02() { string source = @" using System; namespace AttributeTest { class ExampleAttribute : Attribute { public int[] Numbers; public ExampleAttribute(string message, params int[] numbers) { Numbers = numbers; } } class Program { [Example(""MultipleArgumentsToParamsParameter"", 4, 5, 6)] public void MultipleArgumentsToParamsParameter() { } [Example(""NoArgumentsToParamsParameter"")] public void NoArgumentsToParamsParameter() { } [Example(""NullArgumentToParamsParameter"", null)] public void NullArgumentToParamsParameter() { } static void Main() { ExampleAttribute att = null; try { var programType = typeof(Program); var method = programType.GetMember(""MultipleArgumentsToParamsParameter"")[0]; att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0]; method = programType.GetMember(""NoArgumentsToParamsParameter"")[0]; att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0]; method = programType.GetMember(""NullArgumentToParamsParameter"")[0]; att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0]; } catch (Exception e) { Console.WriteLine(e.Message); return; } Console.WriteLine(true); } } } "; Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Program"); var attributeClass = (NamedTypeSymbol)ns.GetMember("ExampleAttribute"); var method = (MethodSymbol)type.GetMember("MultipleArgumentsToParamsParameter"); var attrs = method.GetAttributes(attributeClass); var attr = attrs.Single(); Assert.Equal(2, attr.CommonConstructorArguments.Length); attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "MultipleArgumentsToParamsParameter"); attr.VerifyValue<int[]>(1, TypedConstantKind.Array, new int[] { 4, 5, 6 }); method = (MethodSymbol)type.GetMember("NoArgumentsToParamsParameter"); attrs = method.GetAttributes(attributeClass); attr = attrs.Single(); Assert.Equal(2, attr.CommonConstructorArguments.Length); attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "NoArgumentsToParamsParameter"); attr.VerifyValue<int[]>(1, TypedConstantKind.Array, new int[] { }); method = (MethodSymbol)type.GetMember("NullArgumentToParamsParameter"); attrs = method.GetAttributes(attributeClass); attr = attrs.Single(); Assert.Equal(2, attr.CommonConstructorArguments.Length); attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "NullArgumentToParamsParameter"); attr.VerifyValue<int[]>(1, TypedConstantKind.Array, null); }; // Verify attributes from source and then load metadata to see attributes are written correctly. var compVerifier = CompileAndVerify( source, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator, expectedOutput: "True\r\n", expectedSignatures: new[] { Signature("AttributeTest.Program", "MultipleArgumentsToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"MultipleArgumentsToParamsParameter\", System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] public hidebysig instance System.Void MultipleArgumentsToParamsParameter() cil managed"), Signature("AttributeTest.Program", "NoArgumentsToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"NoArgumentsToParamsParameter\", System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] public hidebysig instance System.Void NoArgumentsToParamsParameter() cil managed"), Signature("AttributeTest.Program", "NullArgumentToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"NullArgumentToParamsParameter\", )] public hidebysig instance System.Void NullArgumentToParamsParameter() cil managed"), }); } [Fact, WorkItem(531385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531385")] public void TestAttributesWithParamArrayInCtor3() { string source = @" using System; using CustomAttribute; namespace AttributeTest { [AllInheritMultiple(new char[] { ' ' }, new string[] { ""whatever"" })] public interface IGoo { } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> sourceAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "whatever" }); Assert.True(attrs.First().AttributeConstructor.Parameters.Last().IsParams); }; Action<ModuleSymbol> mdAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "whatever" }); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: sourceAttributeValidator, symbolValidator: mdAttributeValidator); } [Fact] public void TestAttributeSpecifiedOnItself() { string source = @" using System; namespace AttributeTest { [MyAttribute(typeof(object))] public class MyAttribute : Attribute { public MyAttribute(Type t) { } public static void Main() { } } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("MyAttribute"); var attrs = type.GetAttributes(); Assert.Equal(1, attrs.Length); attrs.First().VerifyValue(0, TypedConstantKind.Type, typeof(Object)); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [Fact] public void TestAttributesWithEnumArrayInCtor() { string source = @" using System; namespace AttributeTest { public enum X { a, b }; public class Y : Attribute { public int f; public Y(X[] x) { } } [Y(A.x)] public class A { public const X[] x = null; public static void Main() { } } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Array, (object[])null); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541058")] [Fact] public void TestAttributesWithTypeof() { string source = @" using System; [MyAttribute(typeof(object))] public class MyAttribute : Attribute { public MyAttribute(Type t) { } public static void Main() { } } "; CompileAndVerify(source); } [WorkItem(541071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541071")] [Fact] public void TestAttributesWithParams() { string source = @" using System; class ExampleAttribute : Attribute { public int[] Numbers; public ExampleAttribute(string message, params int[] numbers) { Numbers = numbers; } } [Example(""wibble"", 4, 5, 6)] class Program { static void Main() { ExampleAttribute att = null; try { att = (ExampleAttribute)typeof(Program).GetCustomAttributes(typeof(ExampleAttribute), false)[0]; } catch (Exception e) { Console.WriteLine(e.Message); return; } Console.WriteLine(true); } } "; var expectedOutput = @"True"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestAttributesOnReturnType() { string source = @" using System; using CustomAttribute; namespace AttributeTest { public class Goo { int p; public int Property { [return: AllInheritMultipleAttribute()] [AllInheritMultipleAttribute()] get { return p; } [return: AllInheritMultipleAttribute()] [AllInheritMultipleAttribute()] set { p = value; } } [return: AllInheritMultipleAttribute()] [return: AllInheritMultipleAttribute()] public int Method() { return p; } [return: AllInheritMultipleAttribute()] public delegate void Delegate(); public static void Main() {} } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Goo"); var property = (PropertySymbol)type.GetMember("Property"); var getter = property.GetMethod; var attrs = getter.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); var attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var setter = property.SetMethod; attrs = setter.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var method = (MethodSymbol)type.GetMember("Method"); attrs = method.GetReturnTypeAttributes(); Assert.Equal(2, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); attr = attrs.Last(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var delegateType = type.GetTypeMember("Delegate"); var invokeMethod = (MethodSymbol)delegateType.GetMember("Invoke"); attrs = invokeMethod.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var ctor = (MethodSymbol)delegateType.GetMember(".ctor"); attrs = ctor.GetReturnTypeAttributes(); Assert.Equal(0, attrs.Length); var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke"); attrs = beginInvokeMethod.GetReturnTypeAttributes(); Assert.Equal(0, attrs.Length); var endInvokeMethod = (MethodSymbol)delegateType.GetMember("EndInvoke"); attrs = endInvokeMethod.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541397")] [Fact] public void TestAttributeWithSameNameAsTypeParameter() { string source = @" using System; namespace AttributeTest { public class TAttribute : Attribute { } public class RAttribute : TAttribute { } public class GClass<T> { [T] public enum E { } [R] internal R M<R>() { return default(R); } } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("GClass"); var enumType = (NamedTypeSymbol)type.GetTypeMember("E"); var attributeType = (NamedTypeSymbol)ns.GetMember("TAttribute"); var attributeType2 = (NamedTypeSymbol)ns.GetMember("RAttribute"); var genMethod = (MethodSymbol)type.GetMember("M"); var attrs = enumType.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs = genMethod.GetAttributes(attributeType2); Assert.Equal(1, attrs.Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541615")] [Fact] public void TestAttributeWithVarIdentifierName() { string source = @" using System; namespace AttributeTest { public class var: Attribute { } [var] class Program { public static void Main() {} } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Program"); var attributeType = (NamedTypeSymbol)ns.GetMember("var"); var attrs = type.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); var attr = attrs.First(); Assert.Equal("AttributeTest.var", attr.ToString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541505")] [Fact] public void AttributeArgumentBind_PropertyWithSameName() { var source = @"using System; namespace AttributeTest { class TestAttribute : Attribute { public TestAttribute(ProtectionLevel p){} } enum ProtectionLevel { Privacy = 0 } class TestClass { ProtectionLevel ProtectionLevel { get { return ProtectionLevel.Privacy; } } [TestAttribute(ProtectionLevel.Privacy)] public int testField; } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("TestClass"); var attributeType = (NamedTypeSymbol)ns.GetMember("TestAttribute"); var field = (FieldSymbol)type.GetMember("testField"); var attrs = field.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541709, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541709")] [Fact] public void AttributeOnSynthesizedParameterSymbol() { var source = @"using System; namespace AttributeTest { public class TestAttributeForMethod : System.Attribute { } public class TestAttributeForParam : System.Attribute { } public class TestAttributeForReturn : System.Attribute { } class TestClass { int P1 { [TestAttributeForMethod] [param: TestAttributeForParam] [return: TestAttributeForReturn] set { } } int P2 { [TestAttributeForMethod] [return: TestAttributeForReturn] get { return 0; } } public static void Main() {} } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("TestClass"); var attributeTypeForMethod = (NamedTypeSymbol)ns.GetMember("TestAttributeForMethod"); var attributeTypeForParam = (NamedTypeSymbol)ns.GetMember("TestAttributeForParam"); var attributeTypeForReturn = (NamedTypeSymbol)ns.GetMember("TestAttributeForReturn"); var property = (PropertySymbol)type.GetMember("P1"); var setter = property.SetMethod; var attrs = setter.GetAttributes(attributeTypeForMethod); Assert.Equal(1, attrs.Count()); var attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForMethod", attr.AttributeClass.ToDisplayString()); Assert.Equal(1, setter.ParameterCount); attrs = setter.Parameters[0].GetAttributes(attributeTypeForParam); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForParam", attr.AttributeClass.ToDisplayString()); attrs = setter.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, attributeTypeForReturn, TypeCompareKind.ConsiderEverything2)); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForReturn", attr.AttributeClass.ToDisplayString()); property = (PropertySymbol)type.GetMember("P2"); var getter = property.GetMethod; attrs = getter.GetAttributes(attributeTypeForMethod); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForMethod", attr.AttributeClass.ToDisplayString()); attrs = getter.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, attributeTypeForReturn, TypeCompareKind.ConsiderEverything2)); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForReturn", attr.AttributeClass.ToDisplayString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] public void TestAttributeStringForEnumTypedConstant() { var source = CreateCompilationWithMscorlib40(@" using System; namespace AttributeTest { enum X { One = 1, Two = 2, Three = 3 }; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Event, Inherited = false, AllowMultiple = true)] class A : System.Attribute { public A(X x) { } public static void Main() { } // AttributeData.ToString() should display 'X.Three' not 'X.One | X.Two' [A(X.Three)] int field; // AttributeData.ToString() should display '5' [A((X)5)] int field2; } } "); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); Assert.Equal(1, attrs.Length); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue(0, TypedConstantKind.Enum, (int)(AttributeTargets.Field | AttributeTargets.Event)); Assert.Equal(2, attr.CommonNamedArguments.Length); attr.VerifyNamedArgumentValue(0, "Inherited", TypedConstantKind.Primitive, false); attr.VerifyNamedArgumentValue(1, "AllowMultiple", TypedConstantKind.Primitive, true); Assert.Equal(@"System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Event, Inherited = false, AllowMultiple = true)", attr.ToString()); var fieldSymbol = (FieldSymbol)type.GetMember("field"); attrs = fieldSymbol.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal(@"AttributeTest.A(AttributeTest.X.Three)", attrs.First().ToString()); fieldSymbol = (FieldSymbol)type.GetMember("field2"); attrs = fieldSymbol.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal(@"AttributeTest.A(5)", attrs.First().ToString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] public void TestAttributesWithNamedConstructorArguments_01() { string source = @" using System; namespace AttributeTest { [A(y:4, z:5, X = 6)] public class A : Attribute { public int X; public A(int y, int z) { Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 4); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 5); attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6); }; string expectedOutput = @"4 5 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [Fact] public void TestAttributesWithNamedConstructorArguments_02() { string source = @" using System; namespace AttributeTest { [A(3, z:5, y:4, X = 6)] public class A : Attribute { public int X; public A(int x, int y, int z) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 3); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 4); attrs.First().VerifyValue(2, TypedConstantKind.Primitive, 5); attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6); }; string expectedOutput = @"3 4 5 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(541864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541864")] [Fact] public void Bug_8769_TestAttributesWithNamedConstructorArguments() { string source = @" using System; namespace AttributeTest { [A(y: 1, x: 2)] public class A : Attribute { public A(int x, int y) { Console.WriteLine(x); Console.WriteLine(y); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); Assert.Equal(2, attrs.First().CommonConstructorArguments.Length); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 1); Assert.Equal(0, attrs.First().CommonNamedArguments.Length); }; string expectedOutput = @"2 1 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [Fact] public void TestAttributesWithOptionalConstructorArguments_01() { string source = @" using System; namespace AttributeTest { [A(3, z:5, X = 6)] public class A : Attribute { public int X; public A(int x, int y = 4, int z = 0) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 3); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 4); attrs.First().VerifyValue(2, TypedConstantKind.Primitive, 5); attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6); }; string expectedOutput = @"3 4 5 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(541861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541861")] [Fact] public void Bug_8768_TestAttributesWithOptionalConstructorArguments() { string source = @" using System; namespace AttributeTest { [A] public class A : Attribute { public A(int x = 2) { Console.Write(x); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<int>(0, TypedConstantKind.Primitive, 2); Assert.Equal(0, attrs.First().CommonNamedArguments.Length); }; string expectedOutput = @"2"; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(541854, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541854")] [Fact] public void Bug8761_StringArrayArgument() { var source = @"using System; [A(X = new string[] { """" })] public class A : Attribute { public object[] X; static void Main() { typeof(A).GetCustomAttributes(false); } } "; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541856, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541856")] [Fact] public void Bug8763_NullInArrayInitializer() { var source = @"using System; [A(X = new object[] { null })] public class A : Attribute { public object[] X; static void Main() { typeof(A).GetCustomAttributes(false); typeof(B).GetCustomAttributes(false); } } [A(X = new object[] { typeof(int), typeof(System.Type), 1, null, ""hi"" })] public class B { public object[] X; } "; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541856, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541856")] [Fact] public void AttributeArrayTypeArgument() { var source = @"using System; [A(objArray = new string[] { ""a"", null })] public class A : Attribute { public object[] objArray; public object obj; static void Main() { typeof(A).GetCustomAttributes(false); typeof(B).GetCustomAttributes(false); typeof(C).GetCustomAttributes(false); typeof(D).GetCustomAttributes(false); typeof(E).GetCustomAttributes(false); typeof(F).GetCustomAttributes(false); typeof(G).GetCustomAttributes(false); typeof(H).GetCustomAttributes(false); typeof(I).GetCustomAttributes(false); } } [A(objArray = new object[] { ""a"", null, 3 })] public class B { } /* CS0029: Cannot implicitly convert type 'int[]' to 'object[]' [A(objArray = new int[] { 3 })] public class Error { } */ [A(objArray = null)] public class C { } [A(obj = new string[] { ""a"" })] public class D { } [A(obj = new object[] { ""a"", null, 3 })] public class E { } [A(obj = new int[] { 1 })] public class F { } [A(obj = 1)] public class G { } [A(obj = ""a"")] public class H { } [A(obj = null)] public class I { } "; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541859")] [Fact] public void Bug8766_AttributeCtorOverloadResolution() { var source = @"using System; [A(C)] public class A : Attribute { const int C = 1; A(int x) { Console.Write(""int""); } public A(long x) { Console.Write(""long""); } static void Main() { typeof(A).GetCustomAttributes(false); } } "; CompileAndVerify(source, expectedOutput: "int"); } [WorkItem(541876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541876")] [Fact] public void Bug8771_AttributeArgumentNameBinding() { var source = @"using System; public class A : Attribute { public A(int x) { Console.WriteLine(x); } } class B { const int X = 1; [A(X)] class C<[A(X)] T> { const int X = 2; } static void Main() { typeof(C<>).GetCustomAttributes(false); typeof(C<>).GetGenericArguments()[0].GetCustomAttributes(false); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol cClass = bClass.GetTypeMember("C"); NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = cClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2); var typeParameters = cClass.TypeParameters; Assert.Equal(1, typeParameters.Length); attrs = typeParameters[0].GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2); }; string expectedOutput = @"2 2 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(546380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546380")] [Fact] public void AttributeWithNestedUnboundGenericType() { var source = @"using System; using System.Collections.Generic; public class A : Attribute { public A(object o) { } } [A(typeof(B<>.C))] public class B<T> { public class C { } } public class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol cClass = bClass.GetTypeMember("C"); NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = bClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Type, cClass.AsUnboundGenericType()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [WorkItem(546380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546380")] [Fact] public void AttributeWithUnboundGenericType() { var source = @"using System; using System.Collections.Generic; public class A : Attribute { public A(object o) { } } [A(typeof(B<>))] public class B<T> { } class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = bClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Type, bClass.AsUnboundGenericType()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [WorkItem(542223, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542223")] [Fact] public void AttributeArgumentAsEnumFromMetadata() { var metadataStream1 = CSharpCompilation.Create("bar.dll", references: new[] { MscorlibRef }, syntaxTrees: new[] { Parse("public enum Bar { Baz }") }).EmitToStream(options: new EmitOptions(metadataOnly: true)); var ref1 = MetadataReference.CreateFromStream(metadataStream1); var metadataStream2 = CSharpCompilation.Create("goo.dll", references: new[] { MscorlibRef, ref1 }, syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree( "public class Ca : System.Attribute { public Ca(object o) { } } " + "[Ca(Bar.Baz)]" + "public class Goo { }") }).EmitToStream(options: new EmitOptions(metadataOnly: true)); var ref2 = MetadataReference.CreateFromStream(metadataStream2); var compilation = CSharpCompilation.Create("moo.dll", references: new[] { MscorlibRef, ref1, ref2 }); var goo = compilation.GetTypeByMetadataName("Goo"); var ca = goo.GetAttributes().First().CommonConstructorArguments.First(); Assert.Equal("Bar", ca.Type.Name); } [WorkItem(542318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542318")] [Fact] public void AttributeWithDaysOfWeekArgument() { // DELIBERATE SPEC VIOLATION: // // Object creation expressions like "new int()" are not considered constant expressions // by the specification but they are by the native compiler; we maintain compatibility // with this bug. // // Additionally, it also treats "new X()", where X is an enum type, as a // constant expression with default value 0, we maintaining compatibility with it. var source = @"using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] [A(X = new DayOfWeek())] [A(X = new bool())] [A(X = new sbyte())] [A(X = new byte())] [A(X = new short())] [A(X = new ushort())] [A(X = new int())] [A(X = new uint())] [A(X = new char())] [A(X = new float())] [A(X = new Single())] [A(X = new double())] public class A : Attribute { public object X; const DayOfWeek dayofweek = new DayOfWeek(); const bool b = new bool(); const sbyte sb = new sbyte(); const byte by = new byte(); const short s = new short(); const ushort us = new ushort(); const int i = new int(); const uint ui = new uint(); const char c = new char(); const float f = new float(); const Single si = new Single(); const double d = new double(); public static void Main() { typeof(A).GetCustomAttributes(false); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = attributeType.GetAttributes(attributeType); Assert.Equal(12, attrs.Count()); var enumerator = attrs.GetEnumerator(); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Enum, (int)new DayOfWeek()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new bool()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new sbyte()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new byte()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new short()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new ushort()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new int()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new uint()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new char()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new float()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new Single()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new double()); }; string expectedOutput = ""; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(542534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542534")] [Fact] public void AttributeOnDefiningPartialMethodDeclaration() { var source = @" using System; class A : Attribute { } partial class Program { [A] static partial void Goo(); static partial void Goo() { } static void Main() { Console.WriteLine(((Action) Goo).Method.GetCustomAttributesData().Count); } } "; CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(542534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542534")] [Fact] public void AttributeOnDefiningPartialMethodDeclaration_02() { var source1 = @" using System; class A1 : Attribute {} class B1 : Attribute {} class C1 : Attribute {} class D1 : Attribute {} class E1 : Attribute {} partial class Program { [A1] [return: B1] static partial void Goo<[C1] T, [D1] U>([E1]int x); } "; var source2 = @" using System; class A2 : Attribute {} class B2 : Attribute {} class C2 : Attribute {} class D2 : Attribute {} class E2 : Attribute {} partial class Program { [A2] [return: B2] static partial void Goo<[C2] U, [D2] T>([E2]int y) { } static void Main() {} } "; var compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var programClass = m.GlobalNamespace.GetTypeMember("Program"); var gooMethod = (MethodSymbol)programClass.GetMember("Goo"); TestAttributeOnPartialMethodHelper(m, gooMethod); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } private void TestAttributeOnPartialMethodHelper(ModuleSymbol m, MethodSymbol gooMethod) { var a1Class = m.GlobalNamespace.GetTypeMember("A1"); var a2Class = m.GlobalNamespace.GetTypeMember("A2"); var b1Class = m.GlobalNamespace.GetTypeMember("B1"); var b2Class = m.GlobalNamespace.GetTypeMember("B2"); var c1Class = m.GlobalNamespace.GetTypeMember("C1"); var c2Class = m.GlobalNamespace.GetTypeMember("C2"); var d1Class = m.GlobalNamespace.GetTypeMember("D1"); var d2Class = m.GlobalNamespace.GetTypeMember("D2"); var e1Class = m.GlobalNamespace.GetTypeMember("E1"); var e2Class = m.GlobalNamespace.GetTypeMember("E2"); Assert.Equal(1, gooMethod.GetAttributes(a1Class).Count()); Assert.Equal(1, gooMethod.GetAttributes(a2Class).Count()); Assert.Equal(1, gooMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, b1Class, TypeCompareKind.ConsiderEverything2)).Count()); Assert.Equal(1, gooMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, b2Class, TypeCompareKind.ConsiderEverything2)).Count()); var typeParam1 = gooMethod.TypeParameters[0]; Assert.Equal(1, typeParam1.GetAttributes(c1Class).Count()); Assert.Equal(1, typeParam1.GetAttributes(c2Class).Count()); var typeParam2 = gooMethod.TypeParameters[1]; Assert.Equal(1, typeParam2.GetAttributes(d1Class).Count()); Assert.Equal(1, typeParam2.GetAttributes(d2Class).Count()); var param = gooMethod.Parameters[0]; Assert.Equal(1, param.GetAttributes(e1Class).Count()); Assert.Equal(1, param.GetAttributes(e2Class).Count()); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void AttributesInMultiplePartialDeclarations_Type() { var source1 = @" using System; class A : Attribute {} [A] partial class X {}"; var source2 = @" using System; class B : Attribute {} [B] partial class X {} class C { public static void Main() { typeof(X).GetCustomAttributes(false); } }"; var compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var aClass = m.GlobalNamespace.GetTypeMember("A"); var bClass = m.GlobalNamespace.GetTypeMember("B"); var type = m.GlobalNamespace.GetTypeMember("X"); Assert.Equal(2, type.GetAttributes().Length); Assert.Equal(1, type.GetAttributes(aClass).Count()); Assert.Equal(1, type.GetAttributes(bClass).Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void AttributesInMultiplePartialDeclarations_TypeParam() { var source1 = @" using System; class A : Attribute {} partial class Gen<[A] T> {}"; var source2 = @" using System; class B : Attribute {} partial class Gen<[B] T> {} class C { public static void Main() {} }"; var compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var aClass = m.GlobalNamespace.GetTypeMember("A"); var bClass = m.GlobalNamespace.GetTypeMember("B"); var type = m.GlobalNamespace.GetTypeMember("Gen"); var typeParameter = type.TypeParameters.First(); Assert.Equal(2, typeParameter.GetAttributes().Length); Assert.Equal(1, typeParameter.GetAttributes(aClass).Count()); Assert.Equal(1, typeParameter.GetAttributes(bClass).Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } [WorkItem(542550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542550")] [Fact] public void Bug9824() { var source = @" using System; public class TAttribute : Attribute { public static void Main () {} } [T] public class GClass<T> where T : Attribute { [T] public enum E { } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("TAttribute"); NamedTypeSymbol GClass = m.GlobalNamespace.GetTypeMember("GClass").AsUnboundGenericType(); Assert.Equal(1, GClass.GetAttributes(attributeType).Count()); NamedTypeSymbol enumE = GClass.GetTypeMember("E"); Assert.Equal(1, enumE.GetAttributes(attributeType).Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(543135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543135")] [Fact] public void AttributeAndDefaultValueArguments_01() { var source = @" using System; [A] public class A : Attribute { public A(object a = default(A)) { } } [A(1)] class C { public static void Main() { typeof(C).GetCustomAttributes(false); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); NamedTypeSymbol cClass = m.GlobalNamespace.GetTypeMember("C"); var attrs = attributeType.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); attrs = cClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<int>(0, TypedConstantKind.Primitive, 1); }; string expectedOutput = ""; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(543135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543135")] [Fact] public void AttributeAndDefaultValueArguments_02() { var source = @" using System; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class A : System.Attribute { public A(object o = null) { } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class B : System.Attribute { public B(object o = default(B)) { } } [A] [A(null)] [B] [B(default(B))] class C { public static void Main() { typeof(C).GetCustomAttributes(false); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeTypeA = m.GlobalNamespace.GetTypeMember("A"); NamedTypeSymbol attributeTypeB = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol cClass = m.GlobalNamespace.GetTypeMember("C"); // Verify A attributes var attrs = cClass.GetAttributes(attributeTypeA); Assert.Equal(2, attrs.Count()); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); attr = attrs.ElementAt(1); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); // Verify B attributes attrs = cClass.GetAttributes(attributeTypeB); Assert.Equal(2, attrs.Count()); attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); attr = attrs.ElementAt(1); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); }; string expectedOutput = ""; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(529044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529044")] [Fact] public void AttributeNameLookup() { var source = @" using System; public class MyClass<T> { } public class MyClassAttribute : Attribute { } [MyClass] public class Test { public static void Main() { typeof(Test).GetCustomAttributes(false); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("MyClassAttribute"); NamedTypeSymbol testClass = m.GlobalNamespace.GetTypeMember("Test"); // Verify attributes var attrs = testClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } [WorkItem(542003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542003")] [Fact] public void Bug8956_NullArgumentToSystemTypeParam() { string source = @" using System; class A : Attribute { public A(System.Type t) {} } [A(null)] class Test { static void Main(string[] args) { typeof(Test).GetCustomAttributes(false); } } "; CompileAndVerify(source); } [Fact] public void SpecialNameAttributeFromSource() { string source = @" using System; using System.Runtime.CompilerServices; [SpecialName()] public struct S { [SpecialName] byte this[byte x] { get { return x; } } [SpecialName] public event Action<string> E; } "; var comp = CreateCompilation(source); var global = comp.SourceModule.GlobalNamespace; var typesym = global.GetMember("S") as NamedTypeSymbol; Assert.NotNull(typesym); Assert.True(typesym.HasSpecialName); var idxsym = typesym.GetMember(WellKnownMemberNames.Indexer) as PropertySymbol; Assert.NotNull(idxsym); Assert.True(idxsym.HasSpecialName); var etsym = typesym.GetMember("E") as EventSymbol; Assert.NotNull(etsym); Assert.True(etsym.HasSpecialName); } [WorkItem(546277, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546277")] [Fact] public void TestArrayTypeInAttributeArgument() { var source = @"using System; public class W {} public class Y<T> { public class F {} public class Z<U> {} } public class X : Attribute { public X(Type y) { } } [X(typeof(W[]))] public class C1 {} [X(typeof(W[,]))] public class C2 {} [X(typeof(W[,][]))] public class C3 {} [X(typeof(Y<W>[][,]))] public class C4 {} [X(typeof(Y<int>.F[,][][,,]))] public class C5 {} [X(typeof(Y<int>.Z<W>[,][]))] public class C6 {} "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol classW = m.GlobalNamespace.GetTypeMember("W"); NamedTypeSymbol classY = m.GlobalNamespace.GetTypeMember("Y"); NamedTypeSymbol classF = classY.GetTypeMember("F"); NamedTypeSymbol classZ = classY.GetTypeMember("Z"); NamedTypeSymbol classX = m.GlobalNamespace.GetTypeMember("X"); NamedTypeSymbol classC1 = m.GlobalNamespace.GetTypeMember("C1"); NamedTypeSymbol classC2 = m.GlobalNamespace.GetTypeMember("C2"); NamedTypeSymbol classC3 = m.GlobalNamespace.GetTypeMember("C3"); NamedTypeSymbol classC4 = m.GlobalNamespace.GetTypeMember("C4"); NamedTypeSymbol classC5 = m.GlobalNamespace.GetTypeMember("C5"); NamedTypeSymbol classC6 = m.GlobalNamespace.GetTypeMember("C6"); var attrs = classC1.GetAttributes(); Assert.Equal(1, attrs.Length); var typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classW)); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC2.GetAttributes(); Assert.Equal(1, attrs.Length); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classW), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC3.GetAttributes(); Assert.Equal(1, attrs.Length); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classW)); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC4.GetAttributes(); Assert.Equal(1, attrs.Length); NamedTypeSymbol classYOfW = classY.ConstructIfGeneric(ImmutableArray.Create(TypeWithAnnotations.Create(classW))); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classYOfW), rank: 2); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg)); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC5.GetAttributes(); Assert.Equal(1, attrs.Length); NamedTypeSymbol classYOfInt = classY.ConstructIfGeneric(ImmutableArray.Create(TypeWithAnnotations.Create(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)))); NamedTypeSymbol substNestedF = classYOfInt.GetTypeMember("F"); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(substNestedF), rank: 3); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg)); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC6.GetAttributes(); Assert.Equal(1, attrs.Length); NamedTypeSymbol substNestedZ = classYOfInt.GetTypeMember("Z").ConstructIfGeneric(ImmutableArray.Create(TypeWithAnnotations.Create(classW))); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(substNestedZ)); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [WorkItem(546621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546621")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void TestUnicodeAttributeArgument_Bug16353() { var source = @"using System; [Obsolete(UnicodeHighSurrogate)] class C { public const string UnicodeHighSurrogate = ""\uD800""; public const string UnicodeReplacementCharacter = ""\uFFFD""; static void Main() { string message = ((ObsoleteAttribute)typeof(C).GetCustomAttributes(false)[0]).Message; Console.WriteLine(message == UnicodeReplacementCharacter + UnicodeReplacementCharacter); } }"; CompileAndVerify(source, expectedOutput: "True"); } [WorkItem(546621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546621")] [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/41280")] public void TestUnicodeAttributeArgumentsStrings() { string HighSurrogateCharacter = "\uD800"; string LowSurrogateCharacter = "\uDC00"; string UnicodeReplacementCharacter = "\uFFFD"; string UnicodeLT0080 = "\u007F"; string UnicodeLT0800 = "\u07FF"; string UnicodeLT10000 = "\uFFFF"; string source = @" using System; public class C { public const string UnicodeSurrogate1 = ""\uD800""; public const string UnicodeSurrogate2 = ""\uD800\uD800""; public const string UnicodeSurrogate3 = ""\uD800\uDC00""; public const string UnicodeSurrogate4 = ""\uD800\u07FF\uD800""; public const string UnicodeSurrogate5 = ""\uD800\u007F\uDC00""; public const string UnicodeSurrogate6 = ""\uD800\u07FF\uDC00""; public const string UnicodeSurrogate7 = ""\uD800\uFFFF\uDC00""; public const string UnicodeSurrogate8 = ""\uD800\uD800\uDC00""; public const string UnicodeSurrogate9 = ""\uDC00\uDC00""; [Obsolete(UnicodeSurrogate1)] public int x1; [Obsolete(UnicodeSurrogate2)] public int x2; [Obsolete(UnicodeSurrogate3)] public int x3; [Obsolete(UnicodeSurrogate4)] public int x4; [Obsolete(UnicodeSurrogate5)] public int x5; [Obsolete(UnicodeSurrogate6)] public int x6; [Obsolete(UnicodeSurrogate7)] public int x7; [Obsolete(UnicodeSurrogate8)] public int x8; [Obsolete(UnicodeSurrogate9)] public int x9; } "; Action<FieldSymbol, string> VerifyAttributes = (field, value) => { var attributes = field.GetAttributes(); Assert.Equal(1, attributes.Length); attributes[0].VerifyValue(0, TypedConstantKind.Primitive, value); }; Func<bool, Action<ModuleSymbol>> validator = isFromSource => (ModuleSymbol module) => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var x1 = type.GetMember<FieldSymbol>("x1"); var x2 = type.GetMember<FieldSymbol>("x2"); var x3 = type.GetMember<FieldSymbol>("x3"); var x4 = type.GetMember<FieldSymbol>("x4"); var x5 = type.GetMember<FieldSymbol>("x5"); var x6 = type.GetMember<FieldSymbol>("x6"); var x7 = type.GetMember<FieldSymbol>("x7"); var x8 = type.GetMember<FieldSymbol>("x8"); var x9 = type.GetMember<FieldSymbol>("x9"); // public const string UnicodeSurrogate1 = ""\uD800""; VerifyAttributes(x1, isFromSource ? HighSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate2 = ""\uD800\uD800""; VerifyAttributes(x2, isFromSource ? HighSurrogateCharacter + HighSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate3 = ""\uD800\uDC00""; VerifyAttributes(x3, HighSurrogateCharacter + LowSurrogateCharacter); // public const string UnicodeSurrogate4 = ""\uD800\u07FF\uD800""; VerifyAttributes(x4, isFromSource ? HighSurrogateCharacter + UnicodeLT0800 + HighSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0800 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate5 = ""\uD800\u007F\uDC00""; VerifyAttributes(x5, isFromSource ? HighSurrogateCharacter + UnicodeLT0080 + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0080 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate6 = ""\uD800\u07FF\uDC00""; VerifyAttributes(x6, isFromSource ? HighSurrogateCharacter + UnicodeLT0800 + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0800 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate7 = ""\uD800\uFFFF\uDC00""; VerifyAttributes(x7, isFromSource ? HighSurrogateCharacter + UnicodeLT10000 + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT10000 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate8 = ""\uD800\uD800\uDC00""; VerifyAttributes(x8, isFromSource ? HighSurrogateCharacter + HighSurrogateCharacter + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + HighSurrogateCharacter + LowSurrogateCharacter); // public const string UnicodeSurrogate9 = ""\uDC00\uDC00""; VerifyAttributes(x9, isFromSource ? LowSurrogateCharacter + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter); }; CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] [WorkItem(546896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546896")] public void MissingTypeInSignature() { string lib1 = @" public enum E { A, B, C } "; string lib2 = @" public class A : System.Attribute { public A(E e) { } } public class C { [A(E.A)] public void M() { } } "; string main = @" class D : C { void N() { M(); } } "; var c1 = CreateCompilation(lib1); var r1 = c1.EmitToImageReference(); var c2 = CreateCompilation(lib2, references: new[] { r1 }); var r2 = c2.EmitToImageReference(); var cm = CreateCompilation(main, new[] { r2 }); cm.VerifyDiagnostics(); var model = cm.GetSemanticModel(cm.SyntaxTrees[0]); int index = main.IndexOf("M()", StringComparison.Ordinal); var m = (ExpressionSyntax)cm.SyntaxTrees[0].GetCompilationUnitRoot().FindToken(index).Parent.Parent; var info = model.GetSymbolInfo(m); var args = info.Symbol.GetAttributes()[0].CommonConstructorArguments; // unresolved type - parameter ignored Assert.Equal(0, args.Length); } [Fact] [WorkItem(569089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569089")] public void NullArrays() { var source = @" using System; public class A : Attribute { public A(object[] a, int[] b) { } public object[] P { get; set; } public int[] F; } [A(null, null, P = null, F = null)] class C { } "; CompileAndVerify(source, symbolValidator: (m) => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var attr = c.GetAttributes().Single(); var args = attr.ConstructorArguments.ToArray(); Assert.True(args[0].IsNull); Assert.Equal("object[]", args[0].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => args[0].Value); Assert.True(args[1].IsNull); Assert.Equal("int[]", args[1].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => args[1].Value); var named = attr.NamedArguments.ToDictionary(e => e.Key, e => e.Value); Assert.True(named["P"].IsNull); Assert.Equal("object[]", named["P"].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => named["P"].Value); Assert.True(named["F"].IsNull); Assert.Equal("int[]", named["F"].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => named["F"].Value); }); } [Fact] public void NullTypeAndString() { var source = @" using System; public class A : Attribute { public A(Type t, string s) { } } [A(null, null)] class C { } "; CompileAndVerify(source, symbolValidator: (m) => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var attr = c.GetAttributes().Single(); var args = attr.ConstructorArguments.ToArray(); Assert.Null(args[0].Value); Assert.Equal("Type", args[0].Type.Name); Assert.Throws<InvalidOperationException>(() => args[0].Values); Assert.Null(args[1].Value); Assert.Equal("String", args[1].Type.Name); Assert.Throws<InvalidOperationException>(() => args[1].Values); }); } [WorkItem(121, "https://github.com/dotnet/roslyn/issues/121")] [Fact] public void Bug_AttributeOnWrongGenericParameter() { var source = @" using System; class XAttribute : Attribute { } class C<T> { public void M<[X]U>() { } } "; CompileAndVerify(source, symbolValidator: module => { var @class = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var classTypeParameter = @class.TypeParameters.Single(); var method = @class.GetMember<MethodSymbol>("M"); var methodTypeParameter = method.TypeParameters.Single(); Assert.Empty(classTypeParameter.GetAttributes()); var attribute = methodTypeParameter.GetAttributes().Single(); Assert.Equal("XAttribute", attribute.AttributeClass.Name); }); } #endregion #region Error Tests [Fact] public void AttributeConstructorErrors1() { var compilation = CreateCompilationWithMscorlib40AndSystemCore(@" using System; static class m { public static int NotAConstant() { return 9; } } public enum e1 { a } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class XAttribute : Attribute { public XAttribute() { } public XAttribute(decimal d) { } public XAttribute(ref int i) { } public XAttribute(e1 e) { } } [XDoesNotExist()] [X(1m)] [X(1)] [X(e1.a)] [X(A.dyn)] [X(m.NotAConstant() + 2)] class A { public const dynamic dyn = null; } ", options: TestOptions.ReleaseDll); // Note that the dev11 compiler produces errors that XDoesNotExist *and* XDoesNotExistAttribute could not be found. // It does not go on to produce the other errors. compilation.VerifyDiagnostics( // (33,2): error CS0246: The type or namespace name 'XDoesNotExistAttribute' could not be found (are you missing a using directive or an assembly reference?) // [XDoesNotExist()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "XDoesNotExist").WithArguments("XDoesNotExistAttribute").WithLocation(33, 2), // (33,2): error CS0246: The type or namespace name 'XDoesNotExist' could not be found (are you missing a using directive or an assembly reference?) // [XDoesNotExist()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "XDoesNotExist").WithArguments("XDoesNotExist").WithLocation(33, 2), // (34,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type // [X(1m)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(34, 2), // (35,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type // [X(1)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(35, 2), // (37,2): error CS0121: The call is ambiguous between the following methods or properties: 'XAttribute.XAttribute(ref int)' and 'XAttribute.XAttribute(e1)' // [X(A.dyn)] Diagnostic(ErrorCode.ERR_AmbigCall, "X(A.dyn)").WithArguments("XAttribute.XAttribute(ref int)", "XAttribute.XAttribute(e1)").WithLocation(37, 2), // (38,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type // [X(m.NotAConstant() + 2)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(38, 2)); } [Fact] public void AttributeNamedArgumentErrors1() { var compilation = CreateCompilation(@" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class XAttribute : Attribute { public void F1(int i) { } private int PrivateField; public static int SharedProperty { get; set; } public int? ReadOnlyProperty { get { return null; } } public decimal BadDecimalType { get; set; } public System.DateTime BadDateType { get; set; } public Attribute[] BadArrayType { get; set; } } [X(NotFound = null)] [X(F1 = null)] [X(PrivateField = null)] [X(SharedProperty = null)] [X(ReadOnlyProperty = null)] [X(BadDecimalType = null)] [X(BadDateType = null)] [X(BadArrayType = null)] class A { } ", options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (21,4): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // [X(NotFound = null)] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound"), // (22,4): error CS0617: 'F1' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [X(F1 = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "F1").WithArguments("F1"), // (23,4): error CS0122: 'XAttribute.PrivateField' is inaccessible due to its protection level // [X(PrivateField = null)] Diagnostic(ErrorCode.ERR_BadAccess, "PrivateField").WithArguments("XAttribute.PrivateField"), // (24,4): error CS0617: 'SharedProperty' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [X(SharedProperty = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "SharedProperty").WithArguments("SharedProperty"), // (25,4): error CS0617: 'ReadOnlyProperty' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [X(ReadOnlyProperty = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "ReadOnlyProperty").WithArguments("ReadOnlyProperty"), // (26,4): error CS0655: 'BadDecimalType' is not a valid named attribute argument because it is not a valid attribute parameter type // [X(BadDecimalType = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadDecimalType").WithArguments("BadDecimalType"), // (27,4): error CS0655: 'BadDateType' is not a valid named attribute argument because it is not a valid attribute parameter type // [X(BadDateType = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadDateType").WithArguments("BadDateType"), // (28,4): error CS0655: 'BadArrayType' is not a valid named attribute argument because it is not a valid attribute parameter type // [X(BadArrayType = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadArrayType").WithArguments("BadArrayType")); } [Fact] public void AttributeNoMultipleAndInvalidTarget() { string source = @" using CustomAttribute; [Base(1)] [@BaseAttribute(""SOS"")] static class AttributeMod { [Derived('Q')] [Derived('C')] public class Goo { } [BaseAttribute(1)] [Base("""")] public class Bar { } }"; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); compilation.VerifyDiagnostics( // (4,2): error CS0579: Duplicate 'BaseAttribute' attribute // [@BaseAttribute("SOS")] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "@BaseAttribute").WithArguments("BaseAttribute").WithLocation(4, 2), // (7,6): error CS0592: Attribute 'Derived' is not valid on this declaration type. It is only valid on 'struct, method, parameter' declarations. // [Derived('Q')] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Derived").WithArguments("Derived", "struct, method, parameter").WithLocation(7, 6), // (8,6): error CS0579: Duplicate 'Derived' attribute // [Derived('C')] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Derived").WithArguments("Derived").WithLocation(8, 6), // (13,6): error CS0579: Duplicate 'Base' attribute // [Base("")] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Base").WithArguments("Base").WithLocation(13, 6)); } [Fact] public void AttributeAmbiguousSpecification() { string source = @" using System; [AttributeUsage(AttributeTargets.All)] public class X : Attribute {} [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } [X] // Error: Ambiguous class Class1 { } [XAttribute] // Refers to XAttribute class Class2 { } [@X] // Refers to X class Class3 { } [@XAttribute] // Refers to XAttribute class Class4 { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,2): error CS1614: 'X' is ambiguous between 'X' and 'XAttribute'; use either '@X' or 'XAttribute' // [X] // Error: Ambiguous Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "X").WithArguments("X", "X", "XAttribute").WithLocation(10, 2)); } [Fact] public void AttributeErrorVerbatimIdentifierInSpecification() { string source = @" using System; [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } [X] // Refers to X class Class1 { } [XAttribute] // Refers to XAttribute class Class2 { } [@X] // Error: No attribute named X class Class3 { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (13,2): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // [@X] // Error: No attribute named X Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "@X").WithArguments("X").WithLocation(13, 2)); } [Fact] public void AttributeOpenTypeInAttribute() { string source = @" using System; using System.Collections.Generic; [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { public XAttribute(Type t) { } } class G<T> { [X(typeof(T))] T t1; // Error: open type in attribute [X(typeof(List<T>))] T t2; // Error: open type in attribute } class X { [X(typeof(List<int>))] int x; // okay: X refers to XAttribute and List<int> is a closed constructed type [X(typeof(List<>))] int y; // okay: X refers to XAttribute and List<> is an unbound generic type } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (13,8): error CS0416: 'T': an attribute argument cannot use type parameters // [X(typeof(T))] T t1; // Error: open type in attribute Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(T)").WithArguments("T"), // (14,8): error CS0416: 'System.Collections.Generic.List<T>': an attribute argument cannot use type parameters // [X(typeof(List<T>))] T t2; // Error: open type in attribute Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(List<T>)").WithArguments("System.Collections.Generic.List<T>"), // (13,22): warning CS0169: The field 'G<T>.t1' is never used // [X(typeof(T))] T t1; // Error: open type in attribute Diagnostic(ErrorCode.WRN_UnreferencedField, "t1").WithArguments("G<T>.t1"), // (14,28): warning CS0169: The field 'G<T>.t2' is never used // [X(typeof(List<T>))] T t2; // Error: open type in attribute Diagnostic(ErrorCode.WRN_UnreferencedField, "t2").WithArguments("G<T>.t2"), // (19,32): warning CS0169: The field 'X.x' is never used // [X(typeof(List<int>))] int x; // okay: X refers to XAttribute and List<int> is a closed constructed type Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("X.x"), // (20,29): warning CS0169: The field 'X.y' is never used // [X(typeof(List<>))] int y; // okay: X refers to XAttribute and List<> is an unbound generic type Diagnostic(ErrorCode.WRN_UnreferencedField, "y").WithArguments("X.y") ); } [WorkItem(540924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540924")] [Fact] public void AttributeEnumsAsAttributeParameters() { string source = @" using System; class EClass { public enum EEK { a, b, c, d }; } [AttributeUsage(AttributeTargets.Class)] internal class HelpAttribute : Attribute { public HelpAttribute(EClass.EEK[] b1) { } } [HelpAttribute(new EClass.EEK[2] { EClass.EEK.b, EClass.EEK.c })] public class MainClass { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); } [WorkItem(768798, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768798")] [Fact(Skip = "768798")] public void AttributeInvalidTargetSpecifier() { string source = @" using System; // Below attribute specification generates a warning regarding invalid target specifier, // We skip binding the attribute with invalid target specifier, // no error generated for invalid use of AttributeUsage on non attribute class. [method: AttributeUsage(AttributeTargets.All)] class X { public static void Main() {} } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type")); } [WorkItem(768798, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768798")] [Fact(Skip = "768798")] public void AttributeInvalidTargetSpecifierOnInvalidAttribute() { string source = @" [method: OopsForgotToBindThis(Haha)] class X { public static void Main() {} } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(/*CS0657, CS0246*/); } [Fact] public void AttributeUsageMultipleErrors() { string source = @"using System; class A { [AttributeUsage(AttributeTargets.Method)] void M1() { } [AttributeUsage(0)] void M2() { } } [AttributeUsage(0)] class B { }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,6): error CS0592: Attribute 'AttributeUsage' is not valid on this declaration type. It is only valid on 'class' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "AttributeUsage").WithArguments("AttributeUsage", "class").WithLocation(4, 6), // (6,6): error CS0592: Attribute 'AttributeUsage' is not valid on this declaration type. It is only valid on 'class' declarations. // [AttributeUsage(0)] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "AttributeUsage").WithArguments("AttributeUsage", "class").WithLocation(6, 6), // (9,2): error CS0641: Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute Diagnostic(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, "AttributeUsage").WithArguments("AttributeUsage").WithLocation(9, 2)); } [Fact] public void CS0643ERR_DuplicateNamedAttributeArgument02() { string source = @" using System; [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] class MyAtt : Attribute { } [MyAtt] public class Test { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (3,39): error CS0643: 'AllowMultiple' duplicate named attribute argument // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_DuplicateNamedAttributeArgument, "AllowMultiple = false").WithArguments("AllowMultiple").WithLocation(3, 39), // (3,2): error CS7036: There is no argument given that corresponds to the required formal parameter 'validOn' of 'AttributeUsageAttribute.AttributeUsageAttribute(AttributeTargets)' // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AttributeUsage(AllowMultiple = true, AllowMultiple = false)").WithArguments("validOn", "System.AttributeUsageAttribute.AttributeUsageAttribute(System.AttributeTargets)").WithLocation(3, 2) ); } [WorkItem(541059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541059")] [Fact] public void AttributeUsageIsNull() { string source = @" using System; [AttributeUsage(null)] public class Att1 : Attribute { } public class Goo { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "System.AttributeTargets")); } [WorkItem(541072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541072")] [Fact] public void AttributeContainsGeneric() { string source = @" [Goo<int>] class G { } class Goo<T> { } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2), // (2,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Goo<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Goo<int>").WithArguments("generic attributes").WithLocation(2, 2)); compilation = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2)); } /// <summary> /// Bug 7620: System.Nullreference Exception throws while the value of parameter AttributeUsage Is Null /// </summary> [Fact] public void CS1502ERR_NullAttributeUsageArgument() { string source = @" using System; [AttributeUsage(null)] public class Attr : Attribute { } public class Goo { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,17): error CS1503: Argument 1: cannot convert from '<null>' to 'System.AttributeTargets' // [AttributeUsage(null)] Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "System.AttributeTargets")); } /// <summary> /// Bug 7632: Debug.Assert() Failure while Attribute Contains Generic /// </summary> [Fact] public void CS0404ERR_GenericAttributeError() { string source = @" [Goo<int>] class G { } class Goo<T> { } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2), // (2,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Goo<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Goo<int>").WithArguments("generic attributes").WithLocation(2, 2)); compilation = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2)); } [WorkItem(541423, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541423")] [Fact] public void ErrorsInMultipleSyntaxTrees() { var source1 = @"using System; [module: A] [AttributeUsage(AttributeTargets.Class)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { }"; var source2 = @"[module: B]"; var compilation = CreateCompilation(new[] { source1, source2 }); compilation.VerifyDiagnostics( // (2,10): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'class' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "class").WithLocation(2, 10), // (1,10): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(1, 10)); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void ErrorsInMultipleSyntaxTrees_TypeParam() { var source1 = @"using System; [AttributeUsage(AttributeTargets.Class)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { } class Gen<[A] T> {} "; var source2 = @"class Gen2<[B] T> {}"; var compilation = CreateCompilation(new[] { source1, source2 }); compilation.VerifyDiagnostics( // (11,12): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'class' declarations. // class Gen<[A] T> {} Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "class").WithLocation(11, 12), // (1,13): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. // class Gen2<[B] T> {} Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(1, 13)); } [WorkItem(541423, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541423")] [Fact] public void ErrorsInMultiplePartialDeclarations() { var source = @"using System; [AttributeUsage(AttributeTargets.Struct)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { } [A] partial class C { } [B] partial class C { }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,2): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'struct' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "struct").WithLocation(10, 2), // (14,2): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(14, 2)); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void ErrorsInMultiplePartialDeclarations_TypeParam() { var source = @"using System; [AttributeUsage(AttributeTargets.Struct)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { } partial class Gen<[A] T> { } partial class Gen<[B] T> { }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,20): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'struct' declarations. // partial class Gen<[A] T> Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "struct").WithLocation(11, 20), // (14,20): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. // partial class Gen<[B] T> Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(14, 20)); } [WorkItem(541505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541505")] [Fact] public void AttributeArgumentError_CS0120() { var source = @"using System; class A : Attribute { public A(ProtectionLevel p){} } enum ProtectionLevel { Privacy = 0 } class F { int ProtectionLevel; [A(ProtectionLevel.Privacy)] public int test; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (16,6): error CS0120: An object reference is required for the non-static field, method, or property 'F.ProtectionLevel' // [A(ProtectionLevel.Privacy)] Diagnostic(ErrorCode.ERR_ObjectRequired, "ProtectionLevel").WithArguments("F.ProtectionLevel"), // (14,7): warning CS0169: The field 'F.ProtectionLevel' is never used // int ProtectionLevel; Diagnostic(ErrorCode.WRN_UnreferencedField, "ProtectionLevel").WithArguments("F.ProtectionLevel"), // (17,14): warning CS0649: Field 'F.test' is never assigned to, and will always have its default value 0 // public int test; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "test").WithArguments("F.test", "0") ); } [Fact, WorkItem(541427, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541427")] public void AttributeTargetsString() { var source = @" using System; [AttributeUsage(AttributeTargets.All & ~AttributeTargets.Class)] class A : Attribute { } [A] class C { } "; CreateCompilation(source).VerifyDiagnostics( // (3,2): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'assembly, module, struct, enum, constructor, method, property, indexer, field, event, interface, parameter, delegate, return, type parameter' declarations. // [A] class C { } Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "assembly, module, struct, enum, constructor, method, property, indexer, field, event, interface, parameter, delegate, return, type parameter") ); } [Fact] public void AttributeTargetsAssemblyModule() { var source = @" using System; [module: Attr()] [AttributeUsage(AttributeTargets.Assembly)] class Attr: Attribute { public Attr(){} }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (3,10): error CS0592: Attribute 'Attr' is not valid on this declaration type. It is only valid on 'assembly' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Attr").WithArguments("Attr", "assembly")); } [WorkItem(541259, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541259")] [Fact] public void CS0182_NonConstantArrayCreationAttributeArgument() { var source = @"using System; [A(new int[1] {Program.f})] // error [A(new int[1])] // error [A(new int[1,1])] // error [A(new int[1 - 1])] // OK create an empty array [A(new A[0])] // error class Program { static public int f = 10; public static void Main() { typeof(Program).GetCustomAttributes(false); } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class A : Attribute { public A(object x) { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (3,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[1] {Program.f})] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "Program.f"), // (4,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[1])] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[1]"), // (5,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[1,1])] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[1,1]"), // (7,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new A[0])] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new A[0]")); } [WorkItem(541753, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541753")] [Fact] public void CS0182_NestedArrays() { var source = @" using System; [A(new int[][] { new int[] { 1 } })] class Program { static void Main() { typeof(Program).GetCustomAttributes(false); } } class A : Attribute { public A(object x) { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[][] { new int[] { 1 } })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[][] { new int[] { 1 } }").WithLocation(4, 4)); } [WorkItem(541849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541849")] [Fact] public void CS0182_MultidimensionalArrays() { var source = @"using System; class MyAttribute : Attribute { public MyAttribute(params int[][,] x) { } } [My] class Program { static void Main() { typeof(Program).GetCustomAttributes(false); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (8,2): error CS0181: Attribute constructor parameter 'x' has type 'int[][*,*]', which is not a valid attribute parameter type // [My] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("x", "int[][*,*]").WithLocation(8, 2)); } [WorkItem(541858, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541858")] [Fact] public void AttributeDefaultValueArgument() { var source = @"using System; namespace AttributeTest { [A(3, X = 6)] public class A : Attribute { public int X; public A(int x, int y = 4, object a = default(A)) { } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541858, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541858")] [Fact] public void CS0416_GenericAttributeDefaultValueArgument() { var source = @"using System; public class A : Attribute { public object X; static void Main() { typeof(C<int>.E).GetCustomAttributes(false); } } public class C<T> { [A(X = default(E))] public enum E { } [A(X = typeof(E2))] public enum E2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (14,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = default(E))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(14, 12), // (17,12): error CS0416: 'C<T>.E2': an attribute argument cannot use type parameters // [A(X = typeof(E2))] Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(E2)").WithArguments("C<T>.E2").WithLocation(17, 12)); } [WorkItem(541615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541615")] [Fact] public void CS0246_VarAttributeIdentifier() { var source = @" [var()] class Program { public static void Main() {} } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (2,2): error CS0246: The type or namespace name 'varAttribute' could not be found (are you missing a using directive or an assembly reference?) // [var()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "var").WithArguments("varAttribute").WithLocation(2, 2), // (2,2): error CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?) // [var()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "var").WithArguments("var").WithLocation(2, 2)); } [Fact] public void TestAttributesWithInvalidArgumentsOrder() { string source = @" using System; namespace AttributeTest { [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] [A(3, z: 5, X = 6, y: 1)] [A(3, z: 5, 1)] [A(3, 1, X = 6, z: 5)] [A(X = 6, 0)] [A(X = 6, x: 0)] public class A : Attribute { public int X; public A(int x, int y = 4, int z = 0) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } public class B { } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics( // (7,27): error CS1016: Named attribute argument expected // [A(3, z: 5, X = 6, y: 1)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "1").WithLocation(7, 27), // (8,17): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // [A(3, z: 5, 1)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "1").WithArguments("7.2").WithLocation(8, 17), // (8,11): error CS8321: Named argument 'z' is used out-of-position but is followed by an unnamed argument // [A(3, z: 5, 1)] Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "z").WithArguments("z").WithLocation(8, 11), // (9,24): error CS1016: Named attribute argument expected // [A(3, 1, X = 6, z: 5)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "5").WithLocation(9, 24), // (10,15): error CS1016: Named attribute argument expected // [A(X = 6, 0)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "0").WithLocation(10, 15), // (11,18): error CS1016: Named attribute argument expected // [A(X = 6, x: 0)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "0").WithLocation(11, 18) ); } [WorkItem(541877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541877")] [Fact] public void Bug8772_TestDelegateAttributeNameBinding() { string source = @" using System; class A : Attribute { public A(int x) { Console.WriteLine(x); } } class C { [A(Invoke)] delegate void F1(); delegate T F2<[A(Invoke)]T> (); const int Invoke = 1; static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,8): error CS1503: Argument 1: cannot convert from 'method group' to 'int' // [A(Invoke)] Diagnostic(ErrorCode.ERR_BadArgType, "Invoke").WithArguments("1", "method group", "int").WithLocation(11, 8), // (14,22): error CS1503: Argument 1: cannot convert from 'method group' to 'int' // delegate T F2<[A(Invoke)]T> (); Diagnostic(ErrorCode.ERR_BadArgType, "Invoke").WithArguments("1", "method group", "int").WithLocation(14, 22)); } [Fact] public void AmbiguousAttributeErrors_01() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_01 { using ValidWithSuffix; using ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS1614: 'Description' is ambiguous between 'ValidWithoutSuffix.Description' and 'ValidWithSuffix.DescriptionAttribute'; use either '@Description' or 'DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "Description").WithArguments("Description", "ValidWithoutSuffix.Description", "ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_02() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_02 { using ValidWithSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'ValidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute", "ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_03() { string source = @" namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_03 { using ValidWithoutSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); } [Fact] public void AmbiguousAttributeErrors_04() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_04 { using ValidWithSuffix; using ValidWithoutSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (36,6): error CS0104: 'Description' is an ambiguous reference between 'ValidWithSuffix_And_ValidWithoutSuffix.Description' and 'ValidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "ValidWithSuffix_And_ValidWithoutSuffix.Description", "ValidWithoutSuffix.Description"), // (39,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'ValidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute", "ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_05() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace TestNamespace_05 { using InvalidWithSuffix; using InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS0616: 'InvalidWithoutSuffix.Description' is not an attribute class // [Description(null)] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Description").WithArguments("InvalidWithoutSuffix.Description"), // (26,6): error CS0616: 'InvalidWithSuffix.DescriptionAttribute' is not an attribute class // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DescriptionAttribute").WithArguments("InvalidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_06() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithSuffix_And_InvalidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_06 { using InvalidWithSuffix; using InvalidWithSuffix_And_InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute"), // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_07() { string source = @" namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace InvalidWithSuffix_And_InvalidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_07 { using InvalidWithoutSuffix; using InvalidWithSuffix_And_InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (30,6): error CS0616: 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' is not an attribute class // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DescriptionAttribute").WithArguments("InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute"), // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_And_InvalidWithoutSuffix.Description' and 'InvalidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_And_InvalidWithoutSuffix.Description", "InvalidWithoutSuffix.Description")); } [Fact] public void AmbiguousAttributeErrors_08() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace InvalidWithSuffix_And_InvalidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_08 { using InvalidWithSuffix; using InvalidWithoutSuffix; using InvalidWithSuffix_And_InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (36,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_And_InvalidWithoutSuffix.Description' and 'InvalidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_And_InvalidWithoutSuffix.Description", "InvalidWithoutSuffix.Description"), // (39,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_09() { string source = @" namespace InvalidWithoutSuffix_But_ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace InvalidWithSuffix_But_ValidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_09 { using InvalidWithoutSuffix_But_ValidWithSuffix; using InvalidWithSuffix_But_ValidWithoutSuffix; [Description(null)] public class Test { public static void Main() {} } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (31,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_But_ValidWithoutSuffix.Description' and 'InvalidWithoutSuffix_But_ValidWithSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_But_ValidWithoutSuffix.Description", "InvalidWithoutSuffix_But_ValidWithSuffix.Description"), // (34,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix_But_ValidWithoutSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix_But_ValidWithoutSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_10() { string source = @" namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace TestNamespace_10 { using ValidWithoutSuffix; using InvalidWithoutSuffix; [Description(null)] public class Test { public static void Main() {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithoutSuffix.Description' and 'ValidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithoutSuffix.Description", "ValidWithoutSuffix.Description")); } [Fact] public void AmbiguousAttributeErrors_11() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace TestNamespace_11 { using ValidWithSuffix; using InvalidWithSuffix; [Description(null)] public class Test { public static void Main() {} } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix.DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute"), // (26,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_12() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithoutSuffix_But_ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_12 { using InvalidWithoutSuffix_But_ValidWithSuffix; using InvalidWithSuffix; [Description(null)] public class Test { public static void Main() {} } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute"), // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AliasAttributeName() { var source = @"using A = A1; using AAttribute = A2; class A1 : System.Attribute { } class A2 : System.Attribute { } [A]class C { }"; CreateCompilation(source).VerifyDiagnostics( // (5,2): error CS1614: 'A' is ambiguous between 'A2' and 'A1'; use either '@A' or 'AAttribute' Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "A").WithArguments("A", "A1", "A2").WithLocation(5, 2)); } [WorkItem(542279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542279")] [Fact] public void MethodSignatureAttributes() { var text = @"class A : System.Attribute { public A(object o) { } } class B { } class C { [return: A(new B())] static object F( [A(new B())] object x, [param: A(new B())] object y) { return null; } }"; CreateCompilation(text).VerifyDiagnostics( // (8,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(8, 16), // (10,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(10, 12), // (11,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(11, 19)); } [Fact] public void AttributeDiagnosticsForEachArgument01() { var source = @"using System; public class A : Attribute { public A(object[] a) {} } [A(new object[] { default(E), default(E) })] class C<T, U> { public enum E {} }"; CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 19), // (7,31): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 31) ); } [Fact] public void AttributeDiagnosticsForEachArgument02() { var source = @"using System; public class A : Attribute { public A(object[] a, object[] b) {} } [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] class C<T, U> { public enum E {} }"; // Note that we suppress further errors once we have reported a bad attribute argument. CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 19), // (7,31): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 31), // (7,60): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 60), // (7,72): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 72) ); } [Fact] public void AttributeArgumentDecimalTypeConstant() { var source = @"using System; [A(X = new decimal())] public class A : Attribute { public object X; const decimal y = new decimal(); }"; CreateCompilation(source).VerifyDiagnostics( // (2,8): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = new decimal())] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new decimal()").WithLocation(2, 8)); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void DuplicateAttributeOnTypeParameterOfPartialClass() { string source = @" class A : System.Attribute { } partial class C<T> { } partial class C<[A][A] T> { } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (4,2): error CS0579: Duplicate 'A' attribute Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"A").WithArguments("A")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void MethodParameterScope() { string source = @" using System; class A : Attribute { public A(int x) { Console.WriteLine(x); } } class C { [A(qq)] // CS0103 - no 'qq' in scope C(int qq) { } [A(rr)] // CS0103 - no 'rr' in scope void M(int rr) { } int P { [A(value)]set { } } // CS0103 - no 'value' in scope static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,8): error CS0103: The name 'qq' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "qq").WithArguments("qq"), // (14,8): error CS0103: The name 'rr' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "rr").WithArguments("rr"), // (17,16): error CS0103: The name 'value' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "value").WithArguments("value")); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var attrArgSyntaxes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AttributeArgumentSyntax>(); Assert.Equal(3, attrArgSyntaxes.Count()); foreach (var argSyntax in attrArgSyntaxes) { var info = semanticModel.GetSymbolInfo(argSyntax.Expression); Assert.Null(info.Symbol); Assert.Equal(0, info.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, info.CandidateReason); } } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void MethodTypeParameterScope() { string source = @" using System; class A : Attribute { public A(int x) { Console.WriteLine(x); } } class C { [A(typeof(T))] // CS0246 - no 'T' in scope void M<T>() { } static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,15): error CS0246: The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "T").WithArguments("T")); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var attrArgSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().Single(); var typeofSyntax = (TypeOfExpressionSyntax)attrArgSyntax.Expression; var typeofArgSyntax = typeofSyntax.Type; Assert.Equal("T", typeofArgSyntax.ToString()); var info = semanticModel.GetSymbolInfo(typeofArgSyntax); Assert.Null(info.Symbol); Assert.Equal(0, info.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, info.CandidateReason); } [WorkItem(542625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542625")] [Fact] public void DuplicateAttributeOnPartialMethod() { string source = @" class A : System.Attribute { } class B : System.Attribute { } partial class C { [return: B] [A] static partial void Goo(); [return: B] [A] static partial void Goo() { } } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // error CS0579: Duplicate 'A' attribute Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"A").WithArguments("A"), // error CS0579: Duplicate 'B' attribute Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"B").WithArguments("B")); } [WorkItem(542625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542625")] [Fact] public void DuplicateAttributeOnTypeParameterOfPartialMethod() { string source = @" class A : System.Attribute { } partial class C { static partial void Goo<[A] T>(); static partial void Goo<[A] T>() { } // partial method without implementation, but another method with same name static partial void Goo2<[A] T>(); static void Goo2<[A] T>() { } // partial method without implementation, but another member with same name static partial void Goo3<[A] T>(); private int Goo3; // partial method without implementation static partial void Goo4<[A][A] T>(); // partial methods differing by signature static partial void Goo5<[A] T>(int x); static partial void Goo5<[A] T>(); // partial method without defining declaration static partial void Goo6<[A][A] T>() { } } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (25,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Goo6<T>()' // static partial void Goo6<[A][A] T>() { } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Goo6").WithArguments("C.Goo6<T>()").WithLocation(25, 25), // (11,17): error CS0111: Type 'C' already defines a member called 'Goo2' with the same parameter types // static void Goo2<[A] T>() { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Goo2").WithArguments("Goo2", "C").WithLocation(11, 17), // (15,17): error CS0102: The type 'C' already contains a definition for 'Goo3' // private int Goo3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Goo3").WithArguments("C", "Goo3").WithLocation(15, 17), // (18,34): error CS0579: Duplicate 'A' attribute // static partial void Goo4<[A][A] T>(); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(18, 34), // (25,34): error CS0579: Duplicate 'A' attribute // static partial void Goo6<[A][A] T>() { } Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(25, 34), // (7,30): error CS0579: Duplicate 'A' attribute // static partial void Goo<[A] T>() { } Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(7, 30), // (15,17): warning CS0169: The field 'C.Goo3' is never used // private int Goo3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Goo3").WithArguments("C.Goo3").WithLocation(15, 17)); } [WorkItem(542625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542625")] [Fact] public void DuplicateAttributeOnParameterOfPartialMethod() { string source = @" class A : System.Attribute { } partial class C { static partial void Goo([param: A]int y); static partial void Goo([A] int y) { } // partial method without implementation, but another method with same name static partial void Goo2([A] int y); static void Goo2([A] int y) { } // partial method without implementation, but another member with same name static partial void Goo3([A] int y); private int Goo3; // partial method without implementation static partial void Goo4([A][param: A] int y); // partial methods differing by signature static partial void Goo5([A] int y); static partial void Goo5([A] int y, int z); // partial method without defining declaration static partial void Goo6([A][A] int y) { } } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (25,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Goo6(int)' // static partial void Goo6([A][A] int y) { } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Goo6").WithArguments("C.Goo6(int)").WithLocation(25, 25), // (11,17): error CS0111: Type 'C' already defines a member called 'Goo2' with the same parameter types // static void Goo2([A] int y) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Goo2").WithArguments("Goo2", "C").WithLocation(11, 17), // (15,17): error CS0102: The type 'C' already contains a definition for 'Goo3' // private int Goo3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Goo3").WithArguments("C", "Goo3").WithLocation(15, 17), // (18,41): error CS0579: Duplicate 'A' attribute // static partial void Goo4([A][param: A] int y); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(18, 41), // (25,34): error CS0579: Duplicate 'A' attribute // static partial void Goo6([A][A] int y) { } Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(25, 34), // (6,37): error CS0579: Duplicate 'A' attribute // static partial void Goo([param: A]int y); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(6, 37), // (15,17): warning CS0169: The field 'C.Goo3' is never used // private int Goo3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Goo3").WithArguments("C.Goo3").WithLocation(15, 17)); } [Fact] public void PartialMethodOverloads() { string source = @" class A : System.Attribute { } partial class C { static partial void F([A] int y); static partial void F(int y, [A]int z); } "; CompileAndVerify(source); } [WorkItem(543456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543456")] [Fact] public void StructLayoutFieldsAreUsed() { var source = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] struct S { int a, b, c; }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542662")] [Fact] public void FalseDuplicateOnPartial() { var source = @" using System; class A : Attribute { } partial class Program { static partial void Goo(int x); [A] static partial void Goo(int x) { } static partial void Goo(); [A] static partial void Goo() { } static void Main() { Console.WriteLine(((Action) Goo).Method.GetCustomAttributesData().Count); } } "; CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(542652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542652")] [Fact] public void Bug9958() { var source = @" class A : System.Attribute { } partial class C { static partial void Goo<T,[A] S>(); static partial void Goo<[A]>() { } }"; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (7,32): error CS1001: Identifier expected // static partial void Goo<[A]>() { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ">"), // (7,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Goo<>()' // static partial void Goo<[A]>() { } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Goo").WithArguments("C.Goo<>()")); } [WorkItem(542909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542909")] [Fact] public void OverriddenPropertyMissingAccessor() { var source = @"using System; class A : Attribute { public virtual int P { get; set; } } class B1 : A { public override int P { get { return base.P; } } } class B2 : A { public override int P { set { } } } [A(P=0)] [B1(P=1)] [B2(P = 2)] class C { }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542899")] [Fact] public void TwoSyntaxTrees() { var source = @" using System.Reflection; [assembly: AssemblyTitle(""EnterpriseLibraryExtensions"")] "; var source2 = @" using Microsoft.Practices.EnterpriseLibrary.Configuration.Design; using EnterpriseLibraryExtensions; [assembly: ConfigurationDesignManager(typeof(ExtensionDesignManager))] "; var compilation = CreateCompilation(new string[] { source, source2 }); compilation.GetDiagnostics(); } [WorkItem(543785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543785")] [Fact] public void OpenGenericTypesUsedAsAttributeArgs() { var source = @" class Gen<T> { [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; }"; var compilation = CreateCompilation(source); Assert.NotEmpty(compilation.GetDiagnostics()); compilation.VerifyDiagnostics( // (4,6): error CS0246: The type or namespace name 'TypeAttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "TypeAttribute").WithArguments("TypeAttributeAttribute").WithLocation(4, 6), // (4,6): error CS0246: The type or namespace name 'TypeAttribute' could not be found (are you missing a using directive or an assembly reference?) // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "TypeAttribute").WithArguments("TypeAttribute").WithLocation(4, 6), // (4,27): error CS0246: The type or namespace name 'L1' could not be found (are you missing a using directive or an assembly reference?) // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "L1").WithArguments("L1").WithLocation(4, 27), // (4,55): warning CS0649: Field 'Gen<T>.Fld6' is never assigned to, and will always have its default value // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Fld6").WithArguments("Gen<T>.Fld6", "").WithLocation(4, 55)); } [WorkItem(543914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543914")] [Fact] public void OpenGenericTypeInAttribute() { var source = @" class Gen<T> {} class Gen2<T>: System.Attribute {} [Gen] [Gen2] public class Test { public static int Main() { return 1; } }"; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,16): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class Gen2<T>: System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(3, 16), // (5,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(6, 2)); } [Fact] public void OpenGenericTypeInAttributeWithGenericAttributeFeature() { var source = @" class Gen<T> {} class Gen2<T> : System.Attribute {} class Gen3<T> : System.Attribute { Gen3(T parameter) { } } [Gen] [Gen2] [Gen2()] [Gen2<U>] [Gen2<System.Collections.Generic.List<U>>] [Gen3(1)] public class Test<U> { public static int Main() { return 1; } }"; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics( // (6,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(6, 2), // (7,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(7, 2), // (8,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2()] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(8, 2), // (9,2): error CS8958: 'U': an attribute type argument cannot use type parameters // [Gen2<U>] Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Gen2<U>").WithArguments("U").WithLocation(9, 2), // (10,2): error CS8958: 'System.Collections.Generic.List<U>': an attribute type argument cannot use type parameters // [Gen2<System.Collections.Generic.List<U>>] Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Gen2<System.Collections.Generic.List<U>>").WithArguments("System.Collections.Generic.List<U>").WithLocation(10, 2), // (10,2): error CS0579: Duplicate 'Gen2<>' attribute // [Gen2<System.Collections.Generic.List<U>>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Gen2<System.Collections.Generic.List<U>>").WithArguments("Gen2<>").WithLocation(10, 2), // (11,2): error CS0305: Using the generic type 'Gen3<T>' requires 1 type arguments // [Gen3(1)] Diagnostic(ErrorCode.ERR_BadArity, "Gen3").WithArguments("Gen3<T>", "type", "1").WithLocation(11, 2)); } [Fact] public void GenericAttributeTypeFromILSource() { var ilSource = @" .class public Gen<T> { } .class public Gen2<T> extends [mscorlib] System.Attribute { } "; var csharpSource = @" [Gen] [Gen2] public class Test { public static int Main() { return 1; } }"; var comp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(2, 2), // (3,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(3, 2)); comp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (2,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(2, 2), // (3,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(3, 2)); } [WorkItem(544230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544230")] [Fact] public void Warnings_Unassigned_Unreferenced_AttributeTypeFields() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class B : Attribute { public Type PublicField; // CS0649 private Type PrivateField; // CS0169 protected Type ProtectedField; // CS0649 internal Type InternalField; // CS0649 }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,17): warning CS0649: Field 'B.PublicField' is never assigned to, and will always have its default value null // public Type PublicField; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "PublicField").WithArguments("B.PublicField", "null"), // (8,18): warning CS0169: The field 'B.PrivateField' is never used // private Type PrivateField; // CS0169 Diagnostic(ErrorCode.WRN_UnreferencedField, "PrivateField").WithArguments("B.PrivateField"), // (9,20): warning CS0649: Field 'B.ProtectedField' is never assigned to, and will always have its default value null // protected Type ProtectedField; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ProtectedField").WithArguments("B.ProtectedField", "null"), // (10,19): warning CS0649: Field 'B.InternalField' is never assigned to, and will always have its default value null // internal Type InternalField; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "InternalField").WithArguments("B.InternalField", "null")); } [WorkItem(544230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544230")] [Fact] public void No_Warnings_For_Assigned_AttributeTypeFields() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class A : Attribute { public Type PublicField; // No CS0649 private Type PrivateField; // No CS0649 protected Type ProtectedField; // No CS0649 internal Type InternalField; // No CS0649 [A(PublicField = typeof(int))] [A(PrivateField = typeof(int))] [A(ProtectedField = typeof(int))] [A(InternalField = typeof(int))] static void Main() { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,8): error CS0617: 'PrivateField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [A(PrivateField = typeof(int))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "PrivateField").WithArguments("PrivateField"), // (14,8): error CS0617: 'ProtectedField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [A(ProtectedField = typeof(int))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "ProtectedField").WithArguments("ProtectedField"), // (15,8): error CS0617: 'InternalField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [A(InternalField = typeof(int))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "InternalField").WithArguments("InternalField")); } [WorkItem(544351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544351")] [Fact] public void CS0182_ERR_BadAttributeArgument_Bug_12638() { var source = @" using System; [A(X = new Array[] { new[] { 1 } })] class A : Attribute { public object X; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,8): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = new Array[] { new[] { 1 } })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new Array[] { new[] { 1 } }").WithLocation(4, 8)); } [WorkItem(544348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544348")] [Fact] public void CS0182_ERR_BadAttributeArgument_WithConversions() { var source = @"using System; [A((int)(object)""ABC"")] class A : Attribute { public A(int x) { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A((int)(object)"ABC")] Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"(int)(object)""ABC""").WithLocation(3, 4)); } [WorkItem(544348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544348")] [Fact] public void CS0182_ERR_BadAttributeArgument_WithConversions_02() { var source = @"using System; [A((object[])(object)( new [] { 1 }))] class A : Attribute { public A(object[] x) { } } [B((object[])(object)(new string[] { ""a"", null }))] class B : Attribute { public B(object[] x) { } } "; CreateCompilation(source).VerifyDiagnostics( // (3,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A((object[])(object)( new [] { 1 }))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "(object[])(object)( new [] { 1 })").WithLocation(3, 4), // (9,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [B((object[])(object)(new string[] { "a", null }))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"(object[])(object)(new string[] { ""a"", null })").WithLocation(9, 4)); } [WorkItem(529392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529392")] [Fact] public void CS0182_ERR_BadAttributeArgument_OpenType_ConstantValue() { // SPEC ERROR: C# language specification does not explicitly disallow constant values of open types. For e.g. // public class C<T> // { // public enum E { V } // } // // [SomeAttr(C<T>.E.V)] // case (a): Constant value of open type. // [SomeAttr(C<int>.E.V)] // case (b): Constant value of constructed type. // Both expressions 'C<T>.E.V' and 'C<int>.E.V' satisfy the requirements for a valid attribute-argument-expression: // (a) Its type is a valid attribute parameter type as per section 17.1.3 of the specification. // (b) It has a compile time constant value. // However, native compiler disallows both the above cases. // We disallow case (a) as it cannot be serialized correctly, but allow case (b) to compile. var source = @" using System; class A : Attribute { public object X; } class C<T> { [A(X = C<T>.E.V)] public enum E { V } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = C<T>.E.V)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C<T>.E.V").WithLocation(11, 12)); } [WorkItem(529392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529392")] [Fact] public void AttributeArgument_ConstructedType_ConstantValue() { // See comments for test CS0182_ERR_BadAttributeArgument_OpenType_ConstantValue var source = @" using System; class A : Attribute { public object X; public static void Main() { typeof(C<>.E).GetCustomAttributes(false); } } public class C<T> { [A(X = C<int>.E.V)] public enum E { V } }"; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(544512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544512")] [Fact] public void LambdaInAttributeArg() { string source = @" public delegate void D(); public class myAttr : System.Attribute { public D d { get { return () => { }; } set { } } } [myAttr(d = () => { })] class X { public static int Main() { return 1; } } "; CreateCompilation(source).VerifyDiagnostics( // (14,9): error CS0655: 'd' is not a valid named attribute argument because it is not a valid attribute parameter type // [myAttr(d = () => { })] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "d").WithArguments("d").WithLocation(14, 9)); } [WorkItem(544590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544590")] [Fact] public void LambdaInAttributeArg2() { string source = @" using System; [AttributeUsage(AttributeTargets.All)] public class Goo : Attribute { public Goo(int sName) { } } public class Class1 { [field: Goo(((System.Func<int>)(() => 5))())] public event EventHandler Click; public static void Main() { } } "; CreateCompilation(source).VerifyDiagnostics( // (11,17): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [field: Goo(((System.Func<int>)(() => 5))())] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "((System.Func<int>)(() => 5))()"), // (12,31): warning CS0067: The event 'Class1.Click' is never used // public event EventHandler Click; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Click").WithArguments("Class1.Click")); } [WorkItem(545030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545030")] [Fact] public void UserDefinedAttribute_Bug13264() { string source = @" namespace System.Runtime.InteropServices { [DllImport] // Error class DllImportAttribute {} } namespace System { [Object] // Warning public class Object : System.Attribute {} } "; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (4,6): error CS0616: 'System.Runtime.InteropServices.DllImportAttribute' is not an attribute class // [DllImport] // Error Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DllImport").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), // (9,6): warning CS0436: The type 'System.Object' in '' conflicts with the imported type 'object' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // [Object] // Warning Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Object").WithArguments("", "System.Object", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "object")); } [WorkItem(545241, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545241")] [Fact] public void ConditionalAttributeOnAttribute() { string source = @" using System; using System.Diagnostics; [Conditional(""A"")] class Attr1 : Attribute { } class Attr2 : Attribute { } class Attr3 : Attr1 { } [Attr1, Attr2, Attr3] class Test { } "; Action<ModuleSymbol> sourceValidator = module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var attrs = type.GetAttributes(); Assert.Equal(3, attrs.Length); }; Action<ModuleSymbol> metadataValidator = module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var attrs = type.GetAttributes(); Assert.Equal(1, attrs.Length); // only one is not conditional Assert.Equal("Attr2", attrs.Single().AttributeClass.Name); }; CompileAndVerify(source, sourceSymbolValidator: sourceValidator, symbolValidator: metadataValidator); } [WorkItem(545499, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545499")] [Fact] public void IncompleteMethodParamAttribute() { string source = @" using System; public class MyAttribute2 : Attribute { public Type[] Types; } public class Test { public void goo([MyAttribute2(Types = new Type[ "; var compilation = CreateCompilation(source); Assert.NotEmpty(compilation.GetDiagnostics()); } [Fact, WorkItem(545556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545556")] public void NameLookupInDelegateParameterAttribute() { var source = @" using System; class A : Attribute { new const int Equals = 1; delegate void F([A(Equals)] int x); public A(int x) { } } "; CreateCompilation(source).VerifyDiagnostics( // (7,24): error CS1503: Argument 1: cannot convert from 'method group' to 'int' // delegate void F([A(Equals)] int x); Diagnostic(ErrorCode.ERR_BadArgType, "Equals").WithArguments("1", "method group", "int")); } [Fact, WorkItem(546234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546234")] public void AmbiguousClassNamespaceLookup() { // One from source, one from PE var source = @" using System; [System] class System : Attribute { } "; var compilation = CreateCompilationWithMscorlib40(source); compilation.VerifyDiagnostics( // (2,7): warning CS0437: The type 'System' in '' conflicts with the imported namespace 'System' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // using System; Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "System").WithArguments("", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System"), // (2,7): error CS0138: A 'using namespace' directive can only be applied to namespaces; 'System' is a type not a namespace. Consider a 'using static' directive instead // using System; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "System").WithArguments("System").WithLocation(2, 7), // (4,16): error CS0246: The type or namespace name 'Attribute' could not be found (are you missing a using directive or an assembly reference?) // class System : Attribute Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Attribute").WithArguments("Attribute"), // (3,2): error CS0616: 'System' is not an attribute class // [System] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "System").WithArguments("System"), // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); source = @" [assembly: X] namespace X { } "; var source2 = @" using System; public class X: Attribute { } "; var comp1 = CreateCompilationWithMscorlib40(source2, assemblyName: "Temp0").ToMetadataReference(); CreateCompilationWithMscorlib40(source, references: new[] { comp1 }).VerifyDiagnostics( // (2,12): error CS0616: 'X' is not an attribute class // [assembly: X] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X")); // Multiple from PE, none from Source source2 = @" using System; public class X { } "; var source3 = @" namespace X { } "; var source4 = @" [X] class Y { } "; comp1 = CreateCompilationWithMscorlib40(source2, assemblyName: "Temp1").ToMetadataReference(); var comp2 = CreateEmptyCompilation(source3, assemblyName: "Temp2").ToMetadataReference(); var comp3 = CreateCompilationWithMscorlib40(source4, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (2,2): error CS0434: The namespace 'X' in 'Temp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with the type 'X' in 'Temp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // [X] Diagnostic(ErrorCode.ERR_SameFullNameNsAgg, "X").WithArguments("Temp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "X", "Temp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "X")); // Multiple from PE, one from Source: Failure var source5 = @" [X] class X { } "; comp3 = CreateCompilationWithMscorlib40(source5, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (2,2): error CS0616: 'X' is not an attribute class // [X] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X")); // Multiple from PE, one from Source: Success source5 = @" using System; [X] class X: Attribute { } "; CompileAndVerifyWithMscorlib40(source5, references: new[] { comp1, comp2 }); // Multiple from PE, multiple from Source var source6 = @" [X] class X { } namespace X { } "; comp3 = CreateCompilationWithMscorlib40(source6, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (3,7): error CS0101: The namespace '<global namespace>' already contains a definition for 'X' // class X Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "X").WithArguments("X", "<global namespace>")); // Multiple from PE, one from Source with alias var source7 = @" using System; using X = Goo; [X] class Goo: Attribute { } "; comp3 = CreateCompilationWithMscorlib40(source7, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (4,2): error CS0576: Namespace '<global namespace>' contains a definition conflicting with alias 'X' // [X] Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "X").WithArguments("X", "<global namespace>"), // (4,2): error CS0616: 'X' is not an attribute class // [X] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X")); } [Fact] public void AmbiguousClassNamespaceLookup_Container() { var source1 = @"using System; public class A : Attribute { } namespace N1 { public class B : Attribute { } public class C : Attribute { } }"; var comp = CreateCompilation(source1, assemblyName: "A"); var ref1 = comp.EmitToImageReference(); var source2 = @"using System; using N1; using N2; namespace N1 { class A : Attribute { } class B : Attribute { } } namespace N2 { class C : Attribute { } } [A] [B] [C] class D { }"; comp = CreateCompilation(source2, references: new[] { ref1 }, assemblyName: "B"); comp.VerifyDiagnostics( // (14,2): warning CS0436: The type 'B' in '' conflicts with the imported type 'B' in 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // [B] Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "B").WithArguments("", "N1.B", "A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "N1.B").WithLocation(14, 2), // (15,2): error CS0104: 'C' is an ambiguous reference between 'N2.C' and 'N1.C' // [C] Diagnostic(ErrorCode.ERR_AmbigContext, "C").WithArguments("C", "N2.C", "N1.C").WithLocation(15, 2)); } [Fact] public void AmbiguousClassNamespaceLookup_Generic() { var source1 = @"public class A { } public class B<T> { } public class C<T, U> { }"; var comp = CreateCompilation(source1); var ref1 = comp.EmitToImageReference(); var source2 = @"class A<U> { } class B<U> { } class C<U> { } [A] [B] [C] class D { }"; comp = CreateCompilation(source2, references: new[] { ref1 }); comp.VerifyDiagnostics( // (4,2): error CS0616: 'A' is not an attribute class // [A] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "A").WithArguments("A").WithLocation(4, 2), // (5,2): error CS0616: 'B<U>' is not an attribute class // [B] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "B").WithArguments("B<U>").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'C<U>' requires 1 type arguments // [C] Diagnostic(ErrorCode.ERR_BadArity, "C").WithArguments("C<U>", "type", "1").WithLocation(6, 2)); } [WorkItem(546283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546283")] [Fact] public void ApplyIndexerNameAttributeTwice() { var source = @"using System.Runtime.CompilerServices; public class IA { [IndexerName(""ItemX"")] [IndexerName(""ItemY"")] public virtual int this[int index] { get { return 1;} set {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,3): error CS0579: Duplicate 'IndexerName' attribute // [IndexerName("ItemY")] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "IndexerName").WithArguments("IndexerName").WithLocation(6, 3)); var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("IA").GetMember<PropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal("ItemX", indexer.MetadataName); //First one wins. } [WorkItem(530524, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530524")] [Fact] public void PEMethodSymbolExtensionAttribute1() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .class public E { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void M(object o) { o.M(); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal(0, assembly.GetAttributes().Length); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E"); Assert.Equal(0, type.GetAttributes().Length); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); Assert.True(method.TestIsExtensionBitSet); Assert.True(method.TestIsExtensionBitTrue); Assert.True(method.IsExtensionMethod); } [WorkItem(530524, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530524")] [Fact] public void PEMethodSymbolExtensionAttribute2() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { } .class public E { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void M(object o) { o.M(); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics(); // we now recognize the extension method even without the assembly-level attribute var assembly = compilation.Assembly; Assert.Equal(0, assembly.GetAttributes().Length); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E"); Assert.Equal(0, type.GetAttributes().Length); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); Assert.True(method.TestIsExtensionBitSet); Assert.True(method.TestIsExtensionBitTrue); Assert.True(method.IsExtensionMethod); } [WorkItem(530524, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530524")] [Fact] public void PEMethodSymbolExtensionAttribute3() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .class public E { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(object o) { ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void M(object o) { o.M(); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics( // (5,11): error CS1061: 'object' does not contain a definition for 'M' and no extension method 'M' accepting a // first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o.M(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("object", "M")); var assembly = compilation.Assembly; Assert.Equal(0, assembly.GetAttributes().Length); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E"); Assert.Equal(0, type.GetAttributes().Length); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); Assert.True(method.TestIsExtensionBitSet); Assert.False(method.TestIsExtensionBitTrue); Assert.False(method.IsExtensionMethod); } [WorkItem(530310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530310")] [Fact] public void PEParameterSymbolParamArrayAttribute() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(int32 x, int32[] y) { .param [2] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void Main(string[] args) { A.M(1, 2, 3); A.M(1, 2, 3, 4); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics(); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); var yParam = method.Parameters[1]; Assert.True(yParam.IsParams); Assert.Equal(0, yParam.GetAttributes().Length); } [WorkItem(546490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546490")] [Fact] public void Bug15984() { var source1 = @" .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern FSharp.Core {} .assembly '<<GeneratedFileName>>' { } .class public abstract auto ansi sealed Library1.Goo extends [mscorlib]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .method public static int32 inc(int32 x) cil managed { // Code size 5 (0x5) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: add IL_0004: ret } // end of method Goo::inc } // end of class Library1.Goo "; var reference1 = CompileIL(source1, prependDefaultHeader: false); var compilation = CreateCompilation("", new[] { reference1 }); var type = compilation.GetTypeByMetadataName("Library1.Goo"); Assert.Equal(0, type.GetAttributes()[0].ConstructorArguments.Count()); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void GenericAttributeType() { var source = @" using System; [A<>] // 1, 2 [A<int>] // 3, 4 [B] // 5 [B<>] // 6, 7 [B<int>] // 8, 9 [C] // 10 [C<>] // 11, 12 [C<int>] // 13, 14 [C<,>] // 15, 16 [C<int, int>] // 17, 18 class Test { } public class A : Attribute { } public class B<T> : Attribute // 19 { } public class C<T, U> : Attribute // 20 { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<>] // 1, 2 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<>").WithArguments("A", "type").WithLocation(4, 2), // (4,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [A<>] // 1, 2 Diagnostic(ErrorCode.ERR_FeatureInPreview, "A<>").WithArguments("generic attributes").WithLocation(4, 2), // (5,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<int>] // 3, 4 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<int>").WithArguments("A", "type").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [A<int>] // 3, 4 Diagnostic(ErrorCode.ERR_FeatureInPreview, "A<int>").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'B<T>' requires 1 type arguments // [B] // 5 Diagnostic(ErrorCode.ERR_BadArity, "B").WithArguments("B<T>", "type", "1").WithLocation(6, 2), // (7,2): error CS7003: Unexpected use of an unbound generic name // [B<>] // 6, 7 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "B<>").WithLocation(7, 2), // (7,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [B<>] // 6, 7 Diagnostic(ErrorCode.ERR_FeatureInPreview, "B<>").WithArguments("generic attributes").WithLocation(7, 2), // (8,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [B<int>] // 8, 9 Diagnostic(ErrorCode.ERR_FeatureInPreview, "B<int>").WithArguments("generic attributes").WithLocation(8, 2), // (8,2): error CS0579: Duplicate 'B<>' attribute // [B<int>] // 8, 9 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "B<int>").WithArguments("B<>").WithLocation(8, 2), // (9,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C] // 10 Diagnostic(ErrorCode.ERR_BadArity, "C").WithArguments("C<T, U>", "type", "2").WithLocation(9, 2), // (10,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<>] // 11, 12 Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("C<T, U>", "type", "2").WithLocation(10, 2), // (10,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<>] // 11, 12 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<>").WithArguments("generic attributes").WithLocation(10, 2), // (11,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<int>] // 13, 14 Diagnostic(ErrorCode.ERR_BadArity, "C<int>").WithArguments("C<T, U>", "type", "2").WithLocation(11, 2), // (11,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<int>] // 13, 14 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<int>").WithArguments("generic attributes").WithLocation(11, 2), // (12,2): error CS7003: Unexpected use of an unbound generic name // [C<,>] // 15, 16 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<,>").WithLocation(12, 2), // (12,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<,>] // 15, 16 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<,>").WithArguments("generic attributes").WithLocation(12, 2), // (13,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<int, int>] // 17, 18 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<int, int>").WithArguments("generic attributes").WithLocation(13, 2), // (13,2): error CS0579: Duplicate 'C<,>' attribute // [C<int, int>] // 17, 18 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<int, int>").WithArguments("C<,>").WithLocation(13, 2), // (22,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class B<T> : Attribute // 19 Diagnostic(ErrorCode.ERR_FeatureInPreview, "Attribute").WithArguments("generic attributes").WithLocation(22, 21), // (26,24): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T, U> : Attribute // 20 Diagnostic(ErrorCode.ERR_FeatureInPreview, "Attribute").WithArguments("generic attributes").WithLocation(26, 24)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<>] // 1, 2 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<>").WithArguments("A", "type").WithLocation(4, 2), // (5,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<int>] // 3, 4 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<int>").WithArguments("A", "type").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'B<T>' requires 1 type arguments // [B] // 5 Diagnostic(ErrorCode.ERR_BadArity, "B").WithArguments("B<T>", "type", "1").WithLocation(6, 2), // (7,2): error CS7003: Unexpected use of an unbound generic name // [B<>] // 6, 7 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "B<>").WithLocation(7, 2), // (8,2): error CS0579: Duplicate 'B<>' attribute // [B<int>] // 8, 9 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "B<int>").WithArguments("B<>").WithLocation(8, 2), // (9,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C] // 10 Diagnostic(ErrorCode.ERR_BadArity, "C").WithArguments("C<T, U>", "type", "2").WithLocation(9, 2), // (10,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<>] // 11, 12 Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("C<T, U>", "type", "2").WithLocation(10, 2), // (11,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<int>] // 13, 14 Diagnostic(ErrorCode.ERR_BadArity, "C<int>").WithArguments("C<T, U>", "type", "2").WithLocation(11, 2), // (12,2): error CS7003: Unexpected use of an unbound generic name // [C<,>] // 15, 16 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<,>").WithLocation(12, 2), // (13,2): error CS0579: Duplicate 'C<,>' attribute // [C<int, int>] // 17, 18 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<int, int>").WithArguments("C<,>").WithLocation(13, 2)); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void AliasedGenericAttributeType_Source() { var source = @" using System; using Alias = C<int>; [Alias] [Alias<>] [Alias<int>] class Test { } public class C<T> : Attribute { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T> : Attribute Diagnostic(ErrorCode.ERR_FeatureInPreview, "Attribute").WithArguments("generic attributes").WithLocation(12, 21), // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(6, 2), // (7,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(7, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<>").WithArguments("generic attributes").WithLocation(6, 2), // (7,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<int>").WithArguments("generic attributes").WithLocation(7, 2)); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(6, 2), // (7,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(7, 2)); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void AliasedGenericAttributeType_Metadata() { var il = @" .class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } "; var source = @" using Alias = C<int>; [Alias] [Alias<>] [Alias<int>] class Test { } "; // NOTE: Dev11 does not give an error for "[Alias]" - it just silently drops the // attribute at emit-time. var comp = CreateCompilationWithILAndMscorlib40(source, il, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias").WithArguments("generic attributes").WithLocation(4, 2), // (5,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<>").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(6, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<int>").WithArguments("generic attributes").WithLocation(6, 2)); // NOTE: Dev11 does not give an error for "[Alias]" - it just silently drops the // attribute at emit-time. comp = CreateCompilationWithILAndMscorlib40(source, il, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(5, 2), // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(6, 2)); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void AliasedGenericAttributeType_Nested() { var source = @" using InnerAlias = Outer<int>.Inner; using OuterAlias = Outer<int>; [InnerAlias] class Test { [OuterAlias.Inner] static void Main() { } } public class Outer<T> { public class Inner { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,2): error CS0616: 'Outer<int>.Inner' is not an attribute class // [InnerAlias] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "InnerAlias").WithArguments("Outer<int>.Inner").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [InnerAlias] Diagnostic(ErrorCode.ERR_FeatureInPreview, "InnerAlias").WithArguments("generic attributes").WithLocation(5, 2), // (8,17): error CS0616: 'Outer<int>.Inner' is not an attribute class // [OuterAlias.Inner] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Inner").WithArguments("Outer<int>.Inner").WithLocation(8, 17), // (8,6): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [OuterAlias.Inner] Diagnostic(ErrorCode.ERR_FeatureInPreview, "OuterAlias.Inner").WithArguments("generic attributes").WithLocation(8, 6)); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS0616: 'Outer<int>.Inner' is not an attribute class // [InnerAlias] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "InnerAlias").WithArguments("Outer<int>.Inner").WithLocation(5, 2), // (8,17): error CS0616: 'Outer<int>.Inner' is not an attribute class // [OuterAlias.Inner] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Inner").WithArguments("Outer<int>.Inner").WithLocation(8, 17)); } [Fact] public void NestedWithGenericAttributeFeature() { var source = @" [Outer<int>.Inner] class Test { [Outer<int>.Inner] static void Main() { } } public class Outer<T> { public class Inner : System.Attribute { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void AliasedGenericAttributeType_NestedWithGenericAttributeFeature_IsAttribute() { var source = @" using InnerAlias = Outer<int>.Inner; using OuterAlias = Outer<int>; [InnerAlias] class Test { [OuterAlias.Inner] static void Main() { } } public class Outer<T> { public class Inner : System.Attribute { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [WorkItem(687816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/687816")] [Fact] public void VerbatimAliasVersusNonVerbatimAlias() { var source = @" using Action = A.ActionAttribute; using ActionAttribute = A.ActionAttribute; namespace A { class ActionAttribute : System.Attribute { } } class Program { [Action] static void Main(string[] args) { } } "; CreateCompilation(source).VerifyDiagnostics( // (12,6): error CS1614: 'Action' is ambiguous between 'A.ActionAttribute' and 'A.ActionAttribute'; use either '@Action' or 'ActionAttribute' // [Action] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "Action").WithArguments("Action", "A.ActionAttribute", "A.ActionAttribute")); } [WorkItem(687816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/687816")] [Fact] public void DeclarationVersusNonVerbatimAlias() { var source = @" using Action = A.ActionAttribute; using A; namespace A { class ActionAttribute : System.Attribute { } } class Program { [Action] static void Main(string[] args) { } } "; CreateCompilation(source).VerifyDiagnostics( // (12,6): error CS1614: 'Action' is ambiguous between 'A.ActionAttribute' and 'A.ActionAttribute'; use either '@Action' or 'ActionAttribute' // [Action] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "Action").WithArguments("Action", "A.ActionAttribute", "A.ActionAttribute")); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)] public void Repro728865() { var source = @" using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using Microsoft.Yeti; namespace PFxIntegration { public class ProducerConsumerScenario { static void Main(string[] args) { Type program = typeof(ProducerConsumerScenario); MethodInfo methodInfo = program.GetMethod(""ProducerConsumer""); Object[] myAttributes = methodInfo.GetCustomAttributes(false); ; if (myAttributes.Length > 0) { Console.WriteLine(""\r\nThe attributes for the method - {0} - are: \r\n"", methodInfo); for (int j = 0; j < myAttributes.Length; j++) Console.WriteLine(""The type of the attribute is {0}"", myAttributes[j]); } } public enum CollectionType { Default, Queue, Stack, Bag } public ProducerConsumerScenario() { } [CartesianRowData( new int[] { 5, 100, 100000 }, new CollectionType[] { CollectionType.Default, CollectionType.Queue, CollectionType.Stack, CollectionType.Bag })] public void ProducerConsumer(int inputSize, CollectionType collectionType) { Console.WriteLine(""Hello""); } } } namespace Microsoft.Yeti { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class CartesianRowDataAttribute : Attribute { public CartesianRowDataAttribute() { } public CartesianRowDataAttribute(params object[] data) { IEnumerable<object>[] asEnum = new IEnumerable<object>[data.Length]; for (int i = 0; i < data.Length; ++i) { WrapEnum((IEnumerable)data[i]); } } static void WrapEnum(IEnumerable x) { foreach (object a in x) { Console.WriteLine("" - "" + a + "" -""); } } } // class } // namespace "; CompileAndVerify(source, expectedOutput: @" - 5 - - 100 - - 100000 - - Default - - Queue - - Stack - - Bag - The attributes for the method - Void ProducerConsumer(Int32, CollectionType) - are: The type of the attribute is Microsoft.Yeti.CartesianRowDataAttribute "); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void StringArrayArgument1() { var source = @" using System; public class Test { [ArrayOnlyAttribute(new string[] { ""A"" })] //error [ObjectOnlyAttribute(new string[] { ""A"" })] [ArrayOrObjectAttribute(new string[] { ""A"" })] //error, even though the object ctor would work void M1() { } [ArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ArrayOrObjectAttribute(null)] //array void M2() { } [ArrayOnlyAttribute(new object[] { ""A"" })] [ObjectOnlyAttribute(new object[] { ""A"" })] [ArrayOrObjectAttribute(new object[] { ""A"" })] //array void M3() { } } public class ArrayOnlyAttribute : Attribute { public ArrayOnlyAttribute(object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ArrayOrObjectAttribute : Attribute { public ArrayOrObjectAttribute(object[] array) { } public ArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ArrayOnlyAttribute(new string[] { "A" })] //error Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ArrayOnlyAttribute(new string[] { ""A"" })"), // (8,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ArrayOrObjectAttribute(new string[] { "A" })] //error, even though the object ctor would work Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ArrayOrObjectAttribute(new string[] { ""A"" })")); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var attrs1 = method1.GetAttributes(); var value1 = new string[] { "A" }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); var attrs3 = method3.GetAttributes(); var value3 = new object[] { "A" }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void StringArrayArgument2() { var source = @" using System; public class Test { [ParamArrayOnlyAttribute(new string[] { ""A"" })] //error [ObjectOnlyAttribute(new string[] { ""A"" })] [ParamArrayOrObjectAttribute(new string[] { ""A"" })] //error, even though the object ctor would work void M1() { } [ParamArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ParamArrayOrObjectAttribute(null)] //array void M2() { } [ParamArrayOnlyAttribute(new object[] { ""A"" })] [ObjectOnlyAttribute(new object[] { ""A"" })] [ParamArrayOrObjectAttribute(new object[] { ""A"" })] //array void M3() { } [ParamArrayOnlyAttribute(""A"")] [ObjectOnlyAttribute(""A"")] [ParamArrayOrObjectAttribute(""A"")] //object void M4() { } } public class ParamArrayOnlyAttribute : Attribute { public ParamArrayOnlyAttribute(params object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ParamArrayOrObjectAttribute : Attribute { public ParamArrayOrObjectAttribute(params object[] array) { } public ParamArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ParamArrayOnlyAttribute(new string[] { "A" })] //error Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ParamArrayOnlyAttribute(new string[] { ""A"" })"), // (8,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ParamArrayOrObjectAttribute(new string[] { "A" })] //error, even though the object ctor would work Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ParamArrayOrObjectAttribute(new string[] { ""A"" })")); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); // As in the test above (i.e. not affected by params modifier). var attrs1 = method1.GetAttributes(); var value1 = new string[] { "A" }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); // As in the test above (i.e. not affected by params modifier). var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); // As in the test above (i.e. not affected by params modifier). var attrs3 = method3.GetAttributes(); var value3 = new object[] { "A" }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); attrs4[0].VerifyValue(0, TypedConstantKind.Array, new object[] { "A" }); attrs4[1].VerifyValue(0, TypedConstantKind.Primitive, "A"); attrs4[2].VerifyValue(0, TypedConstantKind.Primitive, "A"); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void StringArrayArgument3() { var source = @" using System; public class Test { [StringOnlyAttribute(new string[] { ""A"" })] [ObjectOnlyAttribute(new string[] { ""A"" })] //error [StringOrObjectAttribute(new string[] { ""A"" })] //string void M1() { } [StringOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [StringOrObjectAttribute(null)] //string void M2() { } //[StringOnlyAttribute(new object[] { ""A"" })] //overload resolution failure [ObjectOnlyAttribute(new object[] { ""A"" })] [StringOrObjectAttribute(new object[] { ""A"" })] //object void M3() { } [StringOnlyAttribute(""A"")] [ObjectOnlyAttribute(""A"")] [StringOrObjectAttribute(""A"")] //string void M4() { } } public class StringOnlyAttribute : Attribute { public StringOnlyAttribute(params string[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(params object[] array) { } } public class StringOrObjectAttribute : Attribute { public StringOrObjectAttribute(params string[] array) { } public StringOrObjectAttribute(params object[] array) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ObjectOnlyAttribute(new string[] { "A" })] //error Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ObjectOnlyAttribute(new string[] { ""A"" })")); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); var attrs1 = method1.GetAttributes(); var value1 = new string[] { "A" }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (string[])null); var attrs3 = method3.GetAttributes(); var value3 = new object[] { "A" }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); var value4 = new object[] { "A" }; attrs4[0].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[1].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[2].VerifyValue(0, TypedConstantKind.Array, value4); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void IntArrayArgument1() { var source = @" using System; public class Test { //[ArrayOnlyAttribute(new int[] { 1 })] //overload resolution failure [ObjectOnlyAttribute(new int[] { 1 })] [ArrayOrObjectAttribute(new int[] { 1 })] //object void M1() { } [ArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ArrayOrObjectAttribute(null)] //array void M2() { } [ArrayOnlyAttribute(new object[] { 1 })] [ObjectOnlyAttribute(new object[] { 1 })] [ArrayOrObjectAttribute(new object[] { 1 })] //array void M3() { } } public class ArrayOnlyAttribute : Attribute { public ArrayOnlyAttribute(object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ArrayOrObjectAttribute : Attribute { public ArrayOrObjectAttribute(object[] array) { } public ArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var attrs1 = method1.GetAttributes(); var value1 = new int[] { 1 }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); var attrs3 = method3.GetAttributes(); var value3 = new object[] { 1 }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void IntArrayArgument2() { var source = @" using System; public class Test { //[ParamArrayOnlyAttribute(new int[] { 1 })] //overload resolution failure [ObjectOnlyAttribute(new int[] { 1 })] [ParamArrayOrObjectAttribute(new int[] { 1 })] //object void M1() { } [ParamArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ParamArrayOrObjectAttribute(null)] //array void M2() { } [ParamArrayOnlyAttribute(new object[] { 1 })] [ObjectOnlyAttribute(new object[] { 1 })] [ParamArrayOrObjectAttribute(new object[] { 1 })] //array void M3() { } [ParamArrayOnlyAttribute(1)] [ObjectOnlyAttribute(1)] [ParamArrayOrObjectAttribute(1)] //object void M4() { } } public class ParamArrayOnlyAttribute : Attribute { public ParamArrayOnlyAttribute(params object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ParamArrayOrObjectAttribute : Attribute { public ParamArrayOrObjectAttribute(params object[] array) { } public ParamArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); // As in the test above (i.e. not affected by params modifier). var attrs1 = method1.GetAttributes(); var value1 = new int[] { 1 }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); // As in the test above (i.e. not affected by params modifier). var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); // As in the test above (i.e. not affected by params modifier). var attrs3 = method3.GetAttributes(); var value3 = new object[] { 1 }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); attrs4[0].VerifyValue(0, TypedConstantKind.Array, new object[] { 1 }); attrs4[1].VerifyValue(0, TypedConstantKind.Primitive, 1); attrs4[2].VerifyValue(0, TypedConstantKind.Primitive, 1); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void IntArrayArgument3() { var source = @" using System; public class Test { [IntOnlyAttribute(new int[] { 1 })] [ObjectOnlyAttribute(new int[] { 1 })] [IntOrObjectAttribute(new int[] { 1 })] //int void M1() { } [IntOnlyAttribute(null)] [ObjectOnlyAttribute(null)] //[IntOrObjectAttribute(null)] //ambiguous void M2() { } //[IntOnlyAttribute(new object[] { 1 })] //overload resolution failure [ObjectOnlyAttribute(new object[] { 1 })] [IntOrObjectAttribute(new object[] { 1 })] //object void M3() { } [IntOnlyAttribute(1)] [ObjectOnlyAttribute(1)] [IntOrObjectAttribute(1)] //int void M4() { } } public class IntOnlyAttribute : Attribute { public IntOnlyAttribute(params int[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(params object[] array) { } } public class IntOrObjectAttribute : Attribute { public IntOrObjectAttribute(params int[] array) { } public IntOrObjectAttribute(params object[] array) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); var attrs1 = method1.GetAttributes(); var value1 = new int[] { 1 }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, new object[] { value1 }); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); var value2 = (object[])null; attrs2[0].VerifyValue(0, TypedConstantKind.Array, value2); attrs2[1].VerifyValue(0, TypedConstantKind.Array, value2); var attrs3 = method3.GetAttributes(); var value3 = new object[] { 1 }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); var value4 = new object[] { 1 }; attrs4[0].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[1].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[2].VerifyValue(0, TypedConstantKind.Array, value4); } [WorkItem(739630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739630")] [Fact] public void NullVersusEmptyArray() { var source = @" using System; public class ArrayAttribute : Attribute { public int[] field; public ArrayAttribute(int[] param) { } } public class Test { [Array(null)] void M0() { } [Array(new int[] { })] void M1() { } [Array(null, field=null)] void M2() { } [Array(new int[] { }, field = null)] void M3() { } [Array(null, field = new int[] { })] void M4() { } [Array(new int[] { }, field = new int[] { })] void M5() { } static void Main() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var methods = Enumerable.Range(0, 6).Select(i => type.GetMember<MethodSymbol>("M" + i)); var attrs = methods.Select(m => m.GetAttributes().Single()).ToArray(); var nullArray = (int[])null; var emptyArray = new int[0]; const string fieldName = "field"; attrs[0].VerifyValue(0, TypedConstantKind.Array, nullArray); attrs[1].VerifyValue(0, TypedConstantKind.Array, emptyArray); attrs[2].VerifyValue(0, TypedConstantKind.Array, nullArray); attrs[2].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, nullArray); attrs[3].VerifyValue(0, TypedConstantKind.Array, emptyArray); attrs[3].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, nullArray); attrs[4].VerifyValue(0, TypedConstantKind.Array, nullArray); attrs[4].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, emptyArray); attrs[5].VerifyValue(0, TypedConstantKind.Array, emptyArray); attrs[5].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, emptyArray); } [Fact] [WorkItem(530266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530266")] public void UnboundGenericTypeInTypedConstant() { var source = @" using System; public class TestAttribute : Attribute { public TestAttribute(Type x){} } [TestAttribute(typeof(Target<>))] class Target<T> {}"; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Target"); var typeInAttribute = (INamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().Value; Assert.True(typeInAttribute.IsUnboundGenericType); Assert.True(((NamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().ValueInternal).IsUnboundGenericType); Assert.Equal("Target<>", typeInAttribute.ToTestDisplayString()); var comp2 = CreateCompilation("", new[] { comp.EmitToImageReference() }); type = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("Target"); Assert.IsAssignableFrom<PENamedTypeSymbol>(type); typeInAttribute = (INamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().Value; Assert.True(typeInAttribute.IsUnboundGenericType); Assert.True(((NamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().ValueInternal).IsUnboundGenericType); Assert.Equal("Target<>", typeInAttribute.ToTestDisplayString()); } [Fact, WorkItem(1020038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020038")] public void Bug1020038() { var source1 = @" public class CTest {} "; var compilation1 = CreateCompilation(source1, assemblyName: "Bug1020038"); var source2 = @" class CAttr : System.Attribute { public CAttr(System.Type x){} } [CAttr(typeof(CTest))] class Test {} "; var compilation2 = CreateCompilation(source2, new[] { new CSharpCompilationReference(compilation1) }); CompileAndVerify(compilation2, symbolValidator: (m) => { Assert.Equal(2, m.ReferencedAssemblies.Length); Assert.Equal("Bug1020038", m.ReferencedAssemblies[1].Name); }); var source3 = @" class CAttr : System.Attribute { public CAttr(System.Type x){} } [CAttr(typeof(System.Func<System.Action<CTest>>))] class Test {} "; var compilation3 = CreateCompilation(source3, new[] { new CSharpCompilationReference(compilation1) }); CompileAndVerify(compilation3, symbolValidator: (m) => { Assert.Equal(2, m.ReferencedAssemblies.Length); Assert.Equal("Bug1020038", m.ReferencedAssemblies[1].Name); }); } [Fact, WorkItem(937575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937575"), WorkItem(121, "CodePlex")] public void Bug937575() { var source = @" using System; class XAttribute : Attribute { } class C<T> { public void M<[X]U>() { } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugDll); CompileAndVerify(compilation, symbolValidator: (m) => { var cc = m.GlobalNamespace.GetTypeMember("C"); var mm = cc.GetMember<MethodSymbol>("M"); Assert.True(cc.TypeParameters.Single().GetAttributes().IsEmpty); Assert.Equal("XAttribute", mm.TypeParameters.Single().GetAttributes().Single().ToString()); }); } [WorkItem(1144603, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1144603")] [Fact] public void EmitMetadataOnlyInPresenceOfErrors() { var source1 = @" public sealed class DiagnosticAnalyzerAttribute : System.Attribute { public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) {} } public static class LanguageNames { public const xyz CSharp = ""C#""; } "; var compilation1 = CreateCompilationWithMscorlib40(source1, options: TestOptions.DebugDll); compilation1.VerifyDiagnostics( // (10,18): error CS0246: The type or namespace name 'xyz' could not be found (are you missing a using directive or an assembly reference?) // public const xyz CSharp = "C#"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "xyz").WithArguments("xyz").WithLocation(10, 18)); var source2 = @" [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpCompilerDiagnosticAnalyzer {} "; var compilation2 = CreateCompilationWithMscorlib40(source2, new[] { new CSharpCompilationReference(compilation1) }, options: TestOptions.DebugDll, assemblyName: "Test.dll"); Assert.Same(compilation1.Assembly, compilation2.SourceModule.ReferencedAssemblySymbols[1]); compilation2.VerifyDiagnostics(); var emitResult2 = compilation2.Emit(peStream: new MemoryStream(), options: new EmitOptions(metadataOnly: true)); Assert.False(emitResult2.Success); emitResult2.Diagnostics.Verify( // error CS7038: Failed to emit module 'Test.dll': Module has invalid attributes. Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("Test.dll", "Module has invalid attributes.").WithLocation(1, 1)); // Use different mscorlib to test retargeting scenario var compilation3 = CreateCompilationWithMscorlib45(source2, new[] { new CSharpCompilationReference(compilation1) }, options: TestOptions.DebugDll); Assert.NotSame(compilation1.Assembly, compilation3.SourceModule.ReferencedAssemblySymbols[1]); compilation3.VerifyDiagnostics( // (2,35): error CS0246: The type or namespace name 'xyz' could not be found (are you missing a using directive or an assembly reference?) // [DiagnosticAnalyzer(LanguageNames.CSharp)] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CSharp").WithArguments("xyz").WithLocation(2, 35)); var emitResult3 = compilation3.Emit(peStream: new MemoryStream(), options: new EmitOptions(metadataOnly: true)); Assert.False(emitResult3.Success); emitResult3.Diagnostics.Verify( // (2,35): error CS0246: The type or namespace name 'xyz' could not be found (are you missing a using directive or an assembly reference?) // [DiagnosticAnalyzer(LanguageNames.CSharp)] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CSharp").WithArguments("xyz").WithLocation(2, 35)); } [Fact, WorkItem(30833, "https://github.com/dotnet/roslyn/issues/30833")] public void AttributeWithTaskDelegateParameter() { string code = @" using System; using System.Threading.Tasks; namespace a { class Class1 { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] class CommandAttribute : Attribute { public delegate Task FxCommand(); public CommandAttribute(FxCommand Fx) { this.Fx = Fx; } public FxCommand Fx { get; set; } } [Command(UserInfo)] public static async Task UserInfo() { await Task.CompletedTask; } } } "; CreateCompilationWithMscorlib46(code).VerifyDiagnostics( // (22,4): error CS0181: Attribute constructor parameter 'Fx' has type 'Class1.CommandAttribute.FxCommand', which is not a valid attribute parameter type // [Command(UserInfo)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Command").WithArguments("Fx", "a.Class1.CommandAttribute.FxCommand").WithLocation(22, 4)); } [Fact, WorkItem(33388, "https://github.com/dotnet/roslyn/issues/33388")] public void AttributeCrashRepro_33388() { string source = @" using System; public static class C { public static int M(object obj) => 42; public static int M(C2 c2) => 42; } public class RecAttribute : Attribute { public RecAttribute(int i) { this.i = i; } private int i; } [Rec(C.M(null))] public class C2 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (20,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Rec(C.M(null))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(null)").WithLocation(20, 6)); } [Fact] [WorkItem(47308, "https://github.com/dotnet/roslyn/issues/47308")] public void ObsoleteAttribute_Delegate() { string source = @" using System; public class C { [Obsolete] public void M() { } void M2() { Action a = M; a = new Action(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,20): warning CS0612: 'C.M()' is obsolete // Action a = M; Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M").WithArguments("C.M()").WithLocation(12, 20), // (13,24): warning CS0612: 'C.M()' is obsolete // a = new Action(M); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M").WithArguments("C.M()").WithLocation(13, 24) ); } [Fact] [WorkItem(47308, "https://github.com/dotnet/roslyn/issues/47308")] public void ObsoleteAttributeWithUnsafeError() { string source = @" using System; unsafe delegate byte* D(); class C { [Obsolete(null, true)] unsafe static byte* F() => default; unsafe static D M1() => new D(F); static D M2() => new D(F); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (7,35): warning CS0612: 'C.F()' is obsolete // unsafe static D M1() => new D(F); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "F").WithArguments("C.F()").WithLocation(7, 35), // (8,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // static D M2() => new D(F); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "F").WithLocation(8, 28) ); } [Fact] [WorkItem(47308, "https://github.com/dotnet/roslyn/issues/47308")] public void UnmanagedAttributeWithUnsafeError() { string source = @" using System.Runtime.InteropServices; unsafe delegate byte* D(); class C { [UnmanagedCallersOnly] unsafe static byte* F() => default; unsafe static D M1() => new D(F); static D M2() => new D(F); } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class UnmanagedCallersOnlyAttribute : Attribute { public UnmanagedCallersOnlyAttribute() { } public Type[] CallConvs; public string EntryPoint; } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (8,35): error CS8902: 'C.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // unsafe static D M1() => new D(F); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("C.F()").WithLocation(8, 35), // (9,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // static D M2() => new D(F); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "F").WithLocation(9, 28) ); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage() { var lib_cs = @" public class A<T> : System.Attribute {} public class A : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_2() { var source = @" class A<T> : System.Attribute {} class A : System.Attribute {} [A] public class C { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,14): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class A<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 14) ); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_3() { var lib_cs = @" public class AAttribute<T> : System.Attribute {} public class AAttribute : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_4() { var lib_cs = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} public class A : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_5() { var lib_cs = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} public class AAttribute : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void MetadataForUsingGenericAttribute() { var source = @" public class A<T> : System.Attribute {} public class C { [A<int>] public void M() { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate); static void validate(ModuleSymbol module) { var m = (MethodSymbol)module.ContainingAssembly.GlobalNamespace.GetMember("C.M"); var attribute = m.GetAttributes().Single(); Assert.Equal("A<System.Int32>", attribute.AttributeClass.ToTestDisplayString()); Assert.Equal("A<System.Int32>..ctor()", attribute.AttributeConstructor.ToTestDisplayString()); } } [Fact] public void AmbiguityWithGenericAttribute() { var source = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} [A<int>] public class C { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,30): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class AAttribute<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 30), // (3,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class A<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(3, 21), // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [A<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "A<int>").WithArguments("generic attributes").WithLocation(5, 2)); } [Fact, WorkItem(54772, "https://github.com/dotnet/roslyn/issues/54772")] public void ResolveAmbiguityWithGenericAttribute() { var source = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} [@A<int>] [AAttribute<int>] public class C { }"; // This behavior is incorrect. No ambiguity errors should be reported in the above program. var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [@A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "@A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,30): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class AAttribute<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 30), // (3,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class A<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(3, 21), // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [@A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "@A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [@A<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "@A<int>").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [AAttribute<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "AAttribute<int>").WithArguments("generic attributes").WithLocation(6, 2)); } [Fact] public void InheritGenericAttribute() { var source1 = @" public class C<T> : System.Attribute { } public class D : C<int> { } "; var source2 = @" [D] public class Program { } "; var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T> : System.Attribute { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 21)); var comp1 = CreateCompilation(source1); var comp2 = CreateCompilation(source2, references: new[] { comp1.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); comp2 = CreateCompilation(source2, references: new[] { comp1.EmitToImageReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); } [Fact] public void InheritGenericAttributeInMetadata() { var il = @" .class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } .class public auto ansi beforefieldinit D extends class C`1<int32> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class C`1<int32>::.ctor() ret } } "; var source = @" [D] public class Program { } "; // Note that this behavior predates the "generic attributes" feature in C# 10. // If a type deriving from a generic attribute is found in metadata, it's permitted to be used as an attribute in C# 9 and below. var comp = CreateCompilationWithIL(source, il, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); comp = CreateCompilationWithIL(source, il); comp.VerifyDiagnostics(); } [Fact] public void InheritAttribute_BaseInsideGeneric() { var source1 = @" public class C<T> { public class Inner : System.Attribute { } } public class D : C<int>.Inner { } "; var source2 = @" [D] public class Program { } "; var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,26): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class Inner : System.Attribute { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(4, 26)); var comp1 = CreateCompilation(source1); var comp2 = CreateCompilation(source2, references: new[] { comp1.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); comp2 = CreateCompilation(source2, references: new[] { comp1.EmitToImageReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); } [Fact] public void GenericAttribute_Constraints() { var source = @" public class C<T> : System.Attribute where T : struct { } [C<object>] // 1 public class C1 { } [C<int>] public class C2 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,4): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'C<T>' // [C<object>] // 1 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "object").WithArguments("C<T>", "T", "object").WithLocation(4, 4)); } [Fact] public void GenericAttribute_ErrorTypeArg() { var source = @" public class C<T> : System.Attribute { } [C<ERROR>] [C<System>] [C<>] public class Program { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T> : System.Attribute { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 21), // (4,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<ERROR>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<ERROR>").WithArguments("generic attributes").WithLocation(4, 2), // (4,4): error CS0246: The type or namespace name 'ERROR' could not be found (are you missing a using directive or an assembly reference?) // [C<ERROR>] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ERROR").WithArguments("ERROR").WithLocation(4, 4), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<System>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<System>").WithArguments("generic attributes").WithLocation(5, 2), // (5,2): error CS0579: Duplicate 'C<>' attribute // [C<System>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<System>").WithArguments("C<>").WithLocation(5, 2), // (5,4): error CS0118: 'System' is a namespace but is used like a type // [C<System>] Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "type").WithLocation(5, 4), // (6,2): error CS7003: Unexpected use of an unbound generic name // [C<>] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>").WithLocation(6, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<>").WithArguments("generic attributes").WithLocation(6, 2), // (6,2): error CS0579: Duplicate 'C<>' attribute // [C<>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<>").WithArguments("C<>").WithLocation(6, 2)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,4): error CS0246: The type or namespace name 'ERROR' could not be found (are you missing a using directive or an assembly reference?) // [C<ERROR>] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ERROR").WithArguments("ERROR").WithLocation(4, 4), // (5,2): error CS0579: Duplicate 'C<>' attribute // [C<System>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<System>").WithArguments("C<>").WithLocation(5, 2), // (5,4): error CS0118: 'System' is a namespace but is used like a type // [C<System>] Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "type").WithLocation(5, 4), // (6,2): error CS7003: Unexpected use of an unbound generic name // [C<>] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>").WithLocation(6, 2), // (6,2): error CS0579: Duplicate 'C<>' attribute // [C<>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<>").WithArguments("C<>").WithLocation(6, 2)); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttribute_Reflection_CoreClr() { var source = @" using System; public class Attr<T> : Attribute { } [Attr<int>] public class Program { public static void Main() { var attr = Attribute.GetCustomAttribute(typeof(Program), typeof(Attr<int>)); Console.Write(attr); } } "; var verifier = CompileAndVerify(source, expectedOutput: "Attr`1[System.Int32]"); verifier.VerifyDiagnostics(); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttribute_AllowMultiple_False() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public class Attr<T> : Attribute { } [Attr<int>] [Attr<object>] // 1 [Attr<int>] // 2 public class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,2): error CS0579: Duplicate 'Attr<>' attribute // [Attr<object>] // 1 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Attr<object>").WithArguments("Attr<>").WithLocation(8, 2), // (9,2): error CS0579: Duplicate 'Attr<>' attribute // [Attr<int>] // 2 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Attr<int>").WithArguments("Attr<>").WithLocation(9, 2)); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttribute_AllowMultiple_True() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class Attr<T> : Attribute { } [Attr<int>] [Attr<object>] [Attr<int>] public class Program { static void Main() { var attrs = Attribute.GetCustomAttributes(typeof(Program)); foreach (var attr in attrs) { Console.Write(attr); Console.Write(' '); } } } "; var verifier = CompileAndVerify(source, expectedOutput: "Attr`1[System.Int32] Attr`1[System.Object] Attr`1[System.Int32]"); verifier.VerifyDiagnostics(); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttributeInvalidMultipleFromMetadata() { // This IL includes an attribute with `AllowMultiple = false` (the default). // Then the class `D` includes two copies of the attribute. var il = @" .class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Attribute { // [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 ff 7f 00 00 01 00 54 02 0d 41 6c 6c 6f 77 4d 75 6c 74 69 70 6c 65 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } .class public auto ansi beforefieldinit D { .custom instance void class C`1<int32>::.ctor() = ( 01 00 00 00 ) .custom instance void class C`1<int32>::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } "; var source = @" using System; class Program { static void Main() { var attrs = Attribute.GetCustomAttributes(typeof(D)); foreach (var attr in attrs) { Console.Write(attr); Console.Write(' '); } } } "; var comp = CreateCompilationWithIL(source, il, options: TestOptions.DebugExe); var verifier = CompileAndVerify( comp, expectedOutput: "C`1[System.Int32] C`1[System.Int32]"); verifier.VerifyDiagnostics(); } [Fact] [WorkItem(54778, "https://github.com/dotnet/roslyn/issues/54778")] [WorkItem(54804, "https://github.com/dotnet/roslyn/issues/54804")] public void GenericAttribute_AttributeDependentTypes() { var source = @" #nullable enable using System; using System.Collections.Generic; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class Attr<T> : Attribute { } [Attr<dynamic>] // 1 [Attr<List<dynamic>>] // 2 [Attr<nint>] // 3 [Attr<List<nint>>] // 4 [Attr<string?>] // 5 [Attr<List<string?>>] // 6 [Attr<(int a, int b)>] // 7 [Attr<List<(int a, int b)>>] // 8 [Attr<(int a, string? b)>] // 9 [Attr<ValueTuple<int, int>>] // ok class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,2): error CS8960: Type 'dynamic' cannot be used in this context because it cannot be represented in metadata. // [Attr<dynamic>] // 1 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<dynamic>").WithArguments("dynamic").WithLocation(10, 2), // (11,2): error CS8960: Type 'List<dynamic>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<dynamic>>] // 2 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<dynamic>>").WithArguments("List<dynamic>").WithLocation(11, 2), // (12,2): error CS8960: Type 'nint' cannot be used in this context because it cannot be represented in metadata. // [Attr<nint>] // 3 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<nint>").WithArguments("nint").WithLocation(12, 2), // (13,2): error CS8960: Type 'List<nint>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<nint>>] // 4 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<nint>>").WithArguments("List<nint>").WithLocation(13, 2), // (14,2): error CS8960: Type 'string?' cannot be used in this context because it cannot be represented in metadata. // [Attr<string?>] // 5 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<string?>").WithArguments("string?").WithLocation(14, 2), // (15,2): error CS8960: Type 'List<string?>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<string?>>] // 6 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<string?>>").WithArguments("List<string?>").WithLocation(15, 2), // (16,2): error CS8960: Type '(int a, int b)' cannot be used in this context because it cannot be represented in metadata. // [Attr<(int a, int b)>] // 7 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<(int a, int b)>").WithArguments("(int a, int b)").WithLocation(16, 2), // (17,2): error CS8960: Type 'List<(int a, int b)>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<(int a, int b)>>] // 8 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<(int a, int b)>>").WithArguments("List<(int a, int b)>").WithLocation(17, 2), // (18,2): error CS8960: Type '(int a, string? b)' cannot be used in this context because it cannot be represented in metadata. // [Attr<(int a, string? b)>] // 9 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<(int a, string? b)>").WithArguments("(int a, string? b)").WithLocation(18, 2)); } [Fact] public void GenericAttributeRestrictedTypeArgument() { var source = @" using System; class Attr<T> : Attribute { } [Attr<int*>] // 1 class C1 { } [Attr<delegate*<int, void>>] // 2 class C2 { } [Attr<TypedReference>] // 3 class C3 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,7): error CS0306: The type 'int*' may not be used as a type argument // [Attr<int*>] // 1 Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(5, 7), // (8,7): error CS0306: The type 'delegate*<int, void>' may not be used as a type argument // [Attr<delegate*<int, void>>] // 2 Diagnostic(ErrorCode.ERR_BadTypeArgument, "delegate*<int, void>").WithArguments("delegate*<int, void>").WithLocation(8, 7), // (11,7): error CS0306: The type 'TypedReference' may not be used as a type argument // [Attr<TypedReference>] // 3 Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference").WithArguments("System.TypedReference").WithLocation(11, 7)); } [Fact] public void GenericAttribute_AbstractStatic_01() { var source = @" using System; class Attr1<T> : Attribute { } class Attr2Base : Attribute { public virtual void M() { } } class Attr2<T> : Attr2Base where T : I1 { public override void M() { T.M(); } } interface I1 { static abstract void M(); } interface I2 : I1 { } class C : I1 { public static void M() { Console.Write(""C.M""); } } [Attr1<C>] [Attr2<C>] class C1 { public static void Main() { var attr2 = (Attr2Base)Attribute.GetCustomAttribute(typeof(C), typeof(Attr2Base)); attr2.M(); } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.Net60); comp.VerifyEmitDiagnostics(); } [Fact] public void GenericAttributeOnLambda() { var source = @" using System; class Attr<T> : Attribute { } class C { void M() { Func<string, string> x = [Attr<int>] (string x) => x; x(""a""); } } "; var verifier = CompileAndVerify(source, symbolValidator: validateMetadata, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifier.VerifyDiagnostics(); void validateMetadata(ModuleSymbol module) { var lambda = module.GlobalNamespace.GetMember<MethodSymbol>("C.<>c.<M>b__0_0"); var attrs = lambda.GetAttributes(); Assert.Equal(new[] { "Attr<System.Int32>" }, GetAttributeStrings(attrs)); } } [Fact] public void GenericAttributeSimilarToWellKnownAttribute() { var source = @" using System; class ObsoleteAttribute<T> : Attribute { } class C { [Obsolete<int>] void M0() { } void M1() => M0(); [Obsolete] void M2() { } void M3() => M2(); // 1 } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,18): warning CS0612: 'C.M2()' is obsolete // void M3() => M2(); // 1 Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M2()").WithArguments("C.M2()").WithLocation(15, 18)); } [Fact] public void GenericAttributesConsumeFromVB() { var csSource = @" using System; public class Attr<T> : Attribute { } [Attr<int>] public class C { } "; var comp = CreateCompilation(csSource); var vbSource = @" Public Class D Inherits C End Class "; var comp2 = CreateVisualBasicCompilation(vbSource, referencedAssemblies: TargetFrameworkUtil.GetReferences(TargetFramework.Standard).Concat(comp.EmitToImageReference())); var d = comp2.GetMember<INamedTypeSymbol>("D"); var attrs = d.BaseType.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("Attr(Of System.Int32)", attrs[0].AttributeClass.ToTestDisplayString()); } [Fact] public void GenericAttribute_AbstractStatic_02() { var source = @" using System; class Attr1<T> : Attribute { } class Attr2<T> : Attribute where T : I1 { } interface I1 { static abstract void M(); } interface I2 : I1 { } class C : I1 { public static void M() { } } [Attr1<I1>] [Attr2<I1>] class C1 { } [Attr1<I2>] [Attr2<I2>] class C2 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static abstract void M(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M").WithLocation(8, 26), // (13,11): error CS8929: 'C.M()' cannot implement interface member 'I1.M()' in type 'C' because the target runtime doesn't support static abstract members in interfaces. // class C : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("C.M()", "I1.M()", "C").WithLocation(13, 11), // (19,8): error CS8920: The interface 'I1' cannot be used as type parameter 'T' in the generic type or method 'Attr2<T>'. The constraint interface 'I1' or its base interface has static abstract members. // [Attr2<I1>] Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "I1").WithArguments("Attr2<T>", "I1", "T", "I1").WithLocation(19, 8), // (23,8): error CS8920: The interface 'I2' cannot be used as type parameter 'T' in the generic type or method 'Attr2<T>'. The constraint interface 'I1' or its base interface has static abstract members. // [Attr2<I2>] Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "I2").WithArguments("Attr2<T>", "I1", "T", "I2").WithLocation(23, 8)); } [Fact] public void GenericAttributeProperty_01() { var source = @" using System; using System.Reflection; class Attr<T> : Attribute { public T Prop { get; set; } } [Attr<string>(Prop = ""a"")] class Program { static void Main() { var attrs = CustomAttributeData.GetCustomAttributes(typeof(Program)); foreach (var attr in attrs) { foreach (var arg in attr.NamedArguments) { Console.Write(arg.MemberName); Console.Write("" = ""); Console.Write(arg.TypedValue.Value); } } } } "; var verifier = CompileAndVerify(source, sourceSymbolValidator: verify, symbolValidator: verify, expectedOutput: "Prop = a"); void verify(ModuleSymbol module) { var program = module.GlobalNamespace.GetMember<TypeSymbol>("Program"); var attrs = program.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>(Prop = \"a\")" }, GetAttributeStrings(attrs)); } } [Fact] public void GenericAttributeProperty_02() { var source = @" using System; class Attr<T1> : Attribute { public object Prop { get; set; } } class Outer<T2> { [Attr<object>(Prop = default(T2))] // 1 class Program1 { } [Attr<T2>(Prop = default(T2))] // 2, 3 class Program2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,26): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<object>(Prop = default(T2))] // 1 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(7, 26), // (10,6): error CS8967: 'T2': an attribute type argument cannot use type parameters // [Attr<T2>(Prop = default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Attr<T2>").WithArguments("T2").WithLocation(10, 6), // (10,22): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<T2>(Prop = default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(10, 22)); } [ConditionalFact(typeof(CoreClrOnly)), WorkItem(55190, "https://github.com/dotnet/roslyn/issues/55190")] public void GenericAttributeParameter_01() { var source = @" using System; using System.Reflection; class Attr<T> : Attribute { public Attr(T param) { } } [Attr<string>(""a"")] class Holder { } class Program { static void Main() { try { var attrs = CustomAttributeData.GetCustomAttributes(typeof(Holder)); foreach (var attr in attrs) { foreach (var arg in attr.ConstructorArguments) { Console.Write(arg.Value); } } } catch (Exception e) { Console.Write(e.GetType().Name); } } } "; // The expected output here will change once we consume a runtime // which has a fix for https://github.com/dotnet/runtime/issues/56492 var verifier = CompileAndVerify(source, sourceSymbolValidator: verify, symbolValidator: verifyMetadata, expectedOutput: "CustomAttributeFormatException"); verifier.VerifyTypeIL("Holder", @" .class private auto ansi beforefieldinit Holder extends [netstandard]System.Object { .custom instance void class Attr`1<string>::.ctor(!0) = ( 01 00 01 61 00 00 ) // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2058 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method Holder::.ctor } // end of class Holder "); void verify(ModuleSymbol module) { var holder = module.GlobalNamespace.GetMember<TypeSymbol>("Holder"); var attrs = holder.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>(\"a\")" }, GetAttributeStrings(attrs)); } void verifyMetadata(ModuleSymbol module) { // https://github.com/dotnet/roslyn/issues/55190 // The compiler should be able to read this attribute argument from metadata. // Once this is fixed, we should be able to use exactly the same 'verify' method for both source and metadata. var holder = module.GlobalNamespace.GetMember<TypeSymbol>("Holder"); var attrs = holder.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>" }, GetAttributeStrings(attrs)); } } [Fact] public void GenericAttributeParameter_02() { var source = @" using System; class Attr<T> : Attribute { public Attr(object param) { } } class Outer<T2> { [Attr<object>(default(T2))] // 1 class Program1 { } [Attr<T2>(default(T2))] // 2, 3 class Program2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<object>(default(T2))] // 1 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(7, 19), // (10,6): error CS8967: 'T2': an attribute type argument cannot use type parameters // [Attr<T2>(default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Attr<T2>").WithArguments("T2").WithLocation(10, 6), // (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<T2>(default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(10, 15)); } [Fact] public void GenericAttributeOnAssembly() { var source = @" using System; [assembly: Attr<string>] [assembly: Attr<int>] [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class Attr<T> : Attribute { } "; var verifier = CompileAndVerify(source, symbolValidator: verify, sourceSymbolValidator: verifySource); verifier.VerifyDiagnostics(); void verify(ModuleSymbol module) { var attrs = module.ContainingAssembly.GetAttributes(); Assert.Equal(new[] { "System.Runtime.CompilerServices.CompilationRelaxationsAttribute(8)", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)", "System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)", "Attr<System.String>", "Attr<System.Int32>" }, GetAttributeStrings(attrs)); } void verifySource(ModuleSymbol module) { var attrs = module.ContainingAssembly.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>", "Attr<System.Int32>" }, GetAttributeStrings(attrs)); } } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttributeReflection_OpenGeneric() { var source = @" using System; class Attr<T> : Attribute { } class Attr2<T> : Attribute { } [Attr<string>] [Attr2<int>] class Holder { } class Program { static void Main() { try { var attr = Attribute.GetCustomAttribute(typeof(Holder), typeof(Attr<>)); Console.Write(attr?.ToString() ?? ""not found""); } catch (Exception e) { Console.Write(e.GetType().Name); } } } "; var verifier = CompileAndVerify(source, expectedOutput: "not found"); verifier.VerifyDiagnostics(); } [Fact] public void GenericAttributeNested() { var source = @" using System; class Attr<T> : Attribute { } [Attr<Attr<string>>] class C { } "; var verifier = CompileAndVerify(source, symbolValidator: verify, sourceSymbolValidator: verify); verifier.VerifyDiagnostics(); void verify(ModuleSymbol module) { var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var attrs = c.GetAttributes(); Assert.Equal(new[] { "Attr<Attr<System.String>>" }, GetAttributeStrings(attrs)); } } #endregion } }
1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/CSharp/Test/Symbol/Symbols/DefaultInterfaceImplementationTests.cs
// 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. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { [CompilerTrait(CompilerFeature.DefaultInterfaceImplementation)] public class DefaultInterfaceImplementationTests : CSharpTestBase { [Fact] [WorkItem(33083, "https://github.com/dotnet/roslyn/issues/33083")] public void MethodImplementation_011() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } "; ValidateMethodImplementation_011(source1); } private static Verification VerifyOnMonoOrCoreClr { get { return ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped; } } private void ValidateMethodImplementation_011(string source) { foreach (string access in new[] { "x.M1();", "new System.Action(x.M1)();" }) { foreach (string typeKind in new[] { "class", "struct" }) { string source1 = source + typeKind + " Test1 " + @": I1 { static void Main() { I1 x = new Test1(); " + access + @" } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { ValidateMethodImplementationTest1_011(m, "void I1.M1()"); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var source2 = typeKind + " Test2 " + @": I1 { static void Main() { I1 x = new Test2(); " + access + @" } } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate2(ModuleSymbol m) { ValidateMethodImplementationTest2_011(m, "void I1.M1()"); } Validate2(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); } } } } private static void ValidateMethodImplementationTest1_011(ModuleSymbol m, string expectedImplementation) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var m1 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); if (m is PEModuleSymbol peModule) { int rva; peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)m1).Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); } var test1 = m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal(expectedImplementation, test1.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); Assert.Equal("I1", test1.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Assert.Same(m1, i1.FindImplementationForInterfaceMember(m1)); } private static void ValidateMethodImplementationTest2_011(ModuleSymbol m, string expectedImplementation) { var test2 = m.GlobalNamespace.GetTypeMember("Test2"); var i1 = test2.InterfacesNoUseSiteDiagnostics().Single(); Assert.Equal("I1", i1.ToTestDisplayString()); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.Equal(expectedImplementation, test2.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); Assert.Same(m1, i1.FindImplementationForInterfaceMember(m1)); } [Fact] public void MethodImplementation_012() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 { public void M1() { System.Console.WriteLine(""Test1 M1""); } static void Main() { I1 x = new Test1(); x.M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { ValidateMethodImplementationTest1_011(m, "void Test1.M1()"); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test1 M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var source2 = @" class Test2 : I1 { public void M1() { System.Console.WriteLine(""Test2 M1""); } static void Main() { I1 x = new Test2(); x.M1(); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate2(ModuleSymbol m) { ValidateMethodImplementationTest2_011(m, "void Test2.M1()"); } Validate2(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test2 M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate2(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test2 M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); } [Fact] public void MethodImplementation_013() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 { void I1.M1() { System.Console.WriteLine(""Test1 M1""); } static void Main() { I1 x = new Test1(); x.M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { ValidateMethodImplementationTest1_011(m, "void Test1.I1.M1()"); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test1 M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var source2 = @" class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2 M1""); } static void Main() { I1 x = new Test2(); x.M1(); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate2(ModuleSymbol m) { ValidateMethodImplementationTest2_011(m, "void Test2.I1.M1()"); } Validate2(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test2 M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate2(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test2 M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); } [Fact] public void MethodImplementation_021() { var source1 = @" interface I1 { void M1() { System.Console.WriteLine(""M1""); } void M2() { System.Console.WriteLine(""M2""); } } class Base { void M1() { } } class Derived : Base, I1 { void M2() { } static void Main() { I1 x = new Derived(); x.M1(); x.M2(); } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var m1 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M1"); var m2 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M2"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Same(m1, derived.FindImplementationForInterfaceMember(m1)); Assert.Same(m2, derived.FindImplementationForInterfaceMember(m2)); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void MethodImplementation_022() { var source1 = @" interface I1 { void M1() { System.Console.WriteLine(""M1""); } void M2() { System.Console.WriteLine(""M2""); } } class Base : Test { void M1() { } } class Derived : Base, I1 { void M2() { } static void Main() { I1 x = new Derived(); x.M1(); x.M2(); } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var m1 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M1"); var m2 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M2"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Same(m1, derived.FindImplementationForInterfaceMember(m1)); Assert.Same(m2, derived.FindImplementationForInterfaceMember(m2)); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void MethodImplementation_023() { var source1 = @" interface I1 { void M1() {} void M2() {} } class Base : Test { void M1() { } } class Derived : Base, I1 { void M2() { } static void Main() { I1 x = new Derived(); x.M1(); x.M2(); } } class Test : I1 { void I1.M1() { System.Console.WriteLine(""Test.M1""); } void I1.M2() { System.Console.WriteLine(""Test.M2""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var m1 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M1"); var m2 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M2"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Equal("void Test.I1.M1()", derived.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); Assert.Equal("void Test.I1.M2()", derived.FindImplementationForInterfaceMember(m2).ToTestDisplayString()); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"Test.M1 Test.M2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void MethodImplementation_024() { var source1 = @" interface I1 { void M1() {} void M2() {} } class Base : Test { new void M1() { } } class Derived : Base, I1 { new void M2() { } static void Main() { I1 x = new Derived(); x.M1(); x.M2(); } } class Test : I1 { public void M1() { System.Console.WriteLine(""Test.M1""); } public void M2() { System.Console.WriteLine(""Test.M2""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var m1 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M1"); var m2 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M2"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Equal("void Test.M1()", derived.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); Assert.Equal("void Test.M2()", derived.FindImplementationForInterfaceMember(m2).ToTestDisplayString()); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"Test.M1 Test.M2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void MethodImplementation_031() { var source1 = @" interface I1 { void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 { public static void M1() { } static void Main() { I1 x = new Test1(); x.M1(); } } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_032() { var source1 = @" interface I1 { void M1() { System.Console.WriteLine(""M1""); } } class Test1 : Test2, I1 { public static void M1() { } static void Main() { I1 x = new Test1(); x.M1(); } } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_033() { var source1 = @" interface I1 { void M1() {} } class Test1 : Test2, I1 { public static void M1() { } static void Main() { I1 x = new Test1(); x.M1(); } } class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2.M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Equal("void Test2.I1.M1()", test1.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test2.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_034() { var source1 = @" interface I1 { void M1() {} } class Test1 : Test2, I1 { new public static void M1() { } static void Main() { I1 x = new Test1(); x.M1(); } } class Test2 : I1 { public void M1() { System.Console.WriteLine(""Test2.M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Equal("void Test2.M1()", test1.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test2.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_041() { var source1 = @" interface I1 { void M1() { System.Console.WriteLine(""M1""); } int M2() => 2; } class Test1 : I1 { public int M1() { return 0; } public ref int M2() { throw null; } static void Main() { I1 x = new Test1(); x.M1(); System.Console.WriteLine(x.M2()); } } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var m2 = compilation1.GetMember<MethodSymbol>("I1.M2"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); Assert.Same(m2, test1.FindImplementationForInterfaceMember(m2)); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_042() { var source1 = @" interface I1 { void M1() { System.Console.WriteLine(""M1""); } int M2() => 2; } class Test1 : Test2, I1 { public int M1() { return 0; } public ref int M2() { throw null; } static void Main() { I1 x = new Test1(); x.M1(); System.Console.WriteLine(x.M2()); } } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var m2 = compilation1.GetMember<MethodSymbol>("I1.M2"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); Assert.Same(m2, test1.FindImplementationForInterfaceMember(m2)); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_043() { var source1 = @" interface I1 { void M1() {} int M2() => 1; } class Test1 : Test2, I1 { public int M1() { return 0; } public ref int M2() { throw null; } static void Main() { I1 x = new Test1(); x.M1(); System.Console.WriteLine(x.M2()); } } class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2.M1""); } int I1.M2() => 2; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var m2 = compilation1.GetMember<MethodSymbol>("I1.M2"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Equal("void Test2.I1.M1()", test1.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); Assert.Equal("System.Int32 Test2.I1.M2()", test1.FindImplementationForInterfaceMember(m2).ToTestDisplayString()); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"Test2.M1 2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_044() { var source1 = @" interface I1 { void M1() {} int M2() => 1; } class Test1 : Test2, I1 { new public int M1() { return 0; } new public ref int M2() { throw null; } static void Main() { I1 x = new Test1(); x.M1(); System.Console.WriteLine(x.M2()); } } class Test2 : I1 { public void M1() { System.Console.WriteLine(""Test2.M1""); } public int M2() => 2; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var m2 = compilation1.GetMember<MethodSymbol>("I1.M2"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Equal("void Test2.M1()", test1.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); Assert.Equal("System.Int32 Test2.M2()", test1.FindImplementationForInterfaceMember(m2).ToTestDisplayString()); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"Test2.M1 2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_051() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); compilation1.VerifyDiagnostics( // (4,10): error CS8501: Target runtime doesn't support default interface implementation. // void M1() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(4, 10) ); Assert.True(m1.IsMetadataVirtual()); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); m1 = compilation3.GetMember<MethodSymbol>("I1.M1"); var test2 = compilation3.GetTypeByMetadataName("Test2"); Assert.Same(m1, test2.FindImplementationForInterfaceMember(m1)); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.M1()' cannot implement interface member 'I1.M1()' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.M1()", "I1.M1()", "Test2").WithLocation(2, 15) ); } [Fact] public void MethodImplementation_052() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" class Test2 : I1 {} "; foreach (var reference in new[] { compilation1.EmitToImageReference(), compilation1.ToMetadataReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var m1 = compilation3.GetMember<MethodSymbol>("I1.M1"); var test2 = compilation3.GetTypeByMetadataName("Test2"); Assert.Same(m1, test2.FindImplementationForInterfaceMember(m1)); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.M1()' cannot implement interface member 'I1.M1()' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.M1()", "I1.M1()", "Test2").WithLocation(2, 15) ); } } [Fact] public void MethodImplementation_053() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" public interface I2 { void M2(); } class Test2 : I2 { public void M2() {} } "; foreach (var reference in new[] { compilation1.EmitToImageReference(), compilation1.ToMetadataReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var m1 = compilation3.GetMember<MethodSymbol>("I1.M1"); var test2 = compilation3.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(m1)); compilation3.VerifyDiagnostics(); } } [Fact] public void MethodImplementation_061() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); compilation1.VerifyDiagnostics( // (4,10): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // void M1() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M1").WithArguments("default interface implementation", "8.0").WithLocation(4, 10), // (4,10): error CS8701: Target runtime doesn't support default interface implementation. // void M1() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(4, 10) ); Assert.True(m1.IsMetadataVirtual()); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); m1 = compilation3.GetMember<MethodSymbol>("I1.M1"); var test2 = compilation3.GetTypeByMetadataName("Test2"); Assert.Same(m1, test2.FindImplementationForInterfaceMember(m1)); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.M1()' cannot implement interface member 'I1.M1()' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.M1()", "I1.M1()", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.M1()' cannot implement interface member 'I1.M1()' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.M1()", "I1.M1()", "Test2").WithLocation(2, 15) ); } [Fact] public void MethodImplementation_071() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); compilation1.VerifyDiagnostics( // (4,10): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // void M1() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M1").WithArguments("default interface implementation", "8.0").WithLocation(4, 10) ); Assert.True(m1.IsMetadataVirtual()); var source2 = @" class Test2 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); m1 = compilation2.GetMember<MethodSymbol>("I1.M1"); var test2 = compilation2.GetTypeByMetadataName("Test2"); Assert.Same(m1, test2.FindImplementationForInterfaceMember(m1)); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test2Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test2"); Assert.Equal("I1", test2Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); m1 = compilation3.GetMember<MethodSymbol>("I1.M1"); test2 = compilation3.GetTypeByMetadataName("Test2"); Assert.Same(m1, test2.FindImplementationForInterfaceMember(m1)); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.M1()' cannot implement interface member 'I1.M1()' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.M1()", "I1.M1()", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15) ); } [Fact] public void MethodImplementation_081() { var source1 = @" public interface I1 { I1 M1() { throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); compilation1.VerifyDiagnostics( // (4,8): error CS8501: Target runtime doesn't support default interface implementation. // I1 M1() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(4, 8) ); Assert.True(m1.IsMetadataVirtual()); } [Fact] public void MethodImplementation_091() { var source1 = @" public interface I1 { static void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsStatic); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); compilation1.VerifyDiagnostics( // (4,17): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static void M1() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M1").WithArguments("default interface implementation", "8.0").WithLocation(4, 17) ); Assert.False(m1.IsMetadataVirtual()); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (4,17): error CS8701: Target runtime doesn't support default interface implementation. // static void M1() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(4, 17) ); } [Fact] public void MethodImplementation_101() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } public interface I2 : I1 {} class Test1 : I2 { static void Main() { I1 x = new Test1(); x.M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); compilation1.VerifyDiagnostics(); Assert.True(m1.IsMetadataVirtual()); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var result = (PEMethodSymbol)i1.GetMember("M1"); Assert.True(result.IsMetadataVirtual()); Assert.False(result.IsAbstract); Assert.True(result.IsVirtual); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); int rva; ((PEModuleSymbol)m).Module.GetMethodDefPropsOrThrow(result.Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); var test1Result = m.GlobalNamespace.GetTypeMember("Test1"); var interfaces = test1Result.InterfacesNoUseSiteDiagnostics().ToArray(); Assert.Equal(2, interfaces.Length); Assert.Equal("I2", interfaces[0].ToTestDisplayString()); Assert.Equal("I1", interfaces[1].ToTestDisplayString()); }); var source2 = @" class Test2 : I2 { static void Main() { I1 x = new Test2(); x.M1(); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); m1 = compilation2.GetMember<MethodSymbol>("I1.M1"); var test2 = compilation2.GetTypeByMetadataName("Test2"); Assert.Same(m1, test2.FindImplementationForInterfaceMember(m1)); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test2Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test2"); var interfaces = test2Result.InterfacesNoUseSiteDiagnostics().ToArray(); Assert.Equal(2, interfaces.Length); Assert.Equal("I2", interfaces[0].ToTestDisplayString()); Assert.Equal("I1", interfaces[1].ToTestDisplayString()); }); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); m1 = compilation3.GetMember<MethodSymbol>("I1.M1"); test2 = compilation3.GetTypeByMetadataName("Test2"); Assert.Same(m1, test2.FindImplementationForInterfaceMember(m1)); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test2Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test2"); var interfaces = test2Result.InterfacesNoUseSiteDiagnostics().ToArray(); Assert.Equal(2, interfaces.Length); Assert.Equal("I2", interfaces[0].ToTestDisplayString()); Assert.Equal("I1", interfaces[1].ToTestDisplayString()); }); } [Fact] public void MethodImplementation_111() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2 : I1<string> { } "; var source2 = @" #nullable enable class Test1 : I2, I1<string?> { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[2].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I1<string?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I1.M1 I1.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementation_112() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2 : I1<string> { } "; var source2 = @" #nullable enable class Test1 : I1<string?>, I2 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I1<System.String?>", "I2", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I1<System.String>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[0].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I1<System.String>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[2].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I1<string?>, I2 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string>", "Test1").WithLocation(4, 7) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I1.M1 I1.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementation_113() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2 : I1<string> { } public interface I3 : I1<string?> { } "; var source2 = @" #nullable enable class Test1 : I2, I3 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I1.M1 I1.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementation_114() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2 : I1<string> { } public interface I3 : I1<string?> { } "; var source2 = @" #nullable enable class Test1 : I3, I2 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I3", "I1<System.String?>", "I2", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I1<System.String>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I1<System.String>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I3, I2 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string>", "Test1").WithLocation(4, 7) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I1.M1 I1.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void PropertyImplementation_101() { var source1 = @" public interface I1 { int P1 { get { System.Console.WriteLine(""get P1""); return 0; } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "; ValidatePropertyImplementation_101(source1); } private void ValidatePropertyImplementation_101(string source1) { ValidatePropertyImplementation_101(source1, "P1", haveGet: true, haveSet: false, accessCode: @" _ = i1.P1; ", expectedOutput: "get P1"); } private void ValidatePropertyImplementation_101(string source1, string propertyName, bool haveGet, bool haveSet, string accessCode, string expectedOutput) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { ValidatePropertyImplementationTest1_101(m, propertyName, haveGet, haveSet); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { I1 i1 = new Test2(); " + accessCode + @" } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate2(ModuleSymbol m) { ValidatePropertyImplementationTest2_101(m, propertyName, haveGet, haveSet); } Validate2(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate2(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); } private static void ValidatePropertyImplementationTest1_101(ModuleSymbol m, string propertyName, bool haveGet, bool haveSet) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var p1 = i1.GetMember<PropertySymbol>(propertyName); Assert.Equal(!haveSet, p1.IsReadOnly); Assert.Equal(!haveGet, p1.IsWriteOnly); if (haveGet) { ValidateAccessor(p1.GetMethod); } else { Assert.Null(p1.GetMethod); } if (haveSet) { ValidateAccessor(p1.SetMethod); } else { Assert.Null(p1.SetMethod); } void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); if (m is PEModuleSymbol peModule) { int rva; if (haveGet) { peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)p1.GetMethod).Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); } if (haveSet) { peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)p1.SetMethod).Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); } } var test1 = m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); if (haveGet) { Assert.Same(p1.GetMethod, test1.FindImplementationForInterfaceMember(p1.GetMethod)); } if (haveSet) { Assert.Same(p1.SetMethod, test1.FindImplementationForInterfaceMember(p1.SetMethod)); } } private static void ValidatePropertyImplementationTest2_101(ModuleSymbol m, string propertyName, bool haveGet, bool haveSet) { var test2 = m.GlobalNamespace.GetTypeMember("Test2"); Assert.Equal("I1", test2.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); var p1 = test2.InterfacesNoUseSiteDiagnostics().Single().GetMember<PropertySymbol>(propertyName); Assert.Same(p1, test2.FindImplementationForInterfaceMember(p1)); if (haveGet) { var getP1 = p1.GetMethod; Assert.Same(getP1, test2.FindImplementationForInterfaceMember(getP1)); } if (haveSet) { var setP1 = p1.SetMethod; Assert.Same(setP1, test2.FindImplementationForInterfaceMember(setP1)); } } [Fact] public void PropertyImplementation_102() { var source1 = @" public interface I1 { int P1 { get { System.Console.WriteLine(""get P1""); return 0; } set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.P1 = i1.P1; } } "; ValidatePropertyImplementation_102(source1); } private void ValidatePropertyImplementation_102(string source1) { ValidatePropertyImplementation_101(source1, "P1", haveGet: true, haveSet: true, accessCode: @" i1.P1 = i1.P1; ", expectedOutput: @"get P1 set P1"); } [Fact] public void PropertyImplementation_103() { var source1 = @" public interface I1 { int P1 { set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } } "; ValidatePropertyImplementation_103(source1); } private void ValidatePropertyImplementation_103(string source1) { ValidatePropertyImplementation_101(source1, "P1", haveGet: false, haveSet: true, accessCode: @" i1.P1 = 1; ", expectedOutput: "set P1"); } [Fact] public void PropertyImplementation_104() { var source1 = @" public interface I1 { int P1 => Test1.GetInt(); } class Test1 : I1 { public static int GetInt() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "; ValidatePropertyImplementation_101(source1); } [Fact] public void PropertyImplementation_105() { var source1 = @" public interface I1 { int P1 {add; remove;} => 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,13): error CS1014: A get, set or init accessor expected // int P1 {add; remove;} => 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "add").WithLocation(4, 13), // (4,18): error CS1014: A get, set or init accessor expected // int P1 {add; remove;} => 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "remove").WithLocation(4, 18), // (4,9): error CS0548: 'I1.P1': property or indexer must have at least one accessor // int P1 {add; remove;} => 0; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "P1").WithArguments("I1.P1").WithLocation(4, 9), // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // int P1 {add; remove;} => 0; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "int P1 {add; remove;} => 0;").WithLocation(4, 5) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.P1"); Assert.True(p1.IsAbstract); Assert.Null(p1.GetMethod); Assert.Null(p1.SetMethod); Assert.True(p1.IsReadOnly); Assert.True(p1.IsWriteOnly); } [Fact] public void PropertyImplementation_106() { var source1 = @" public interface I1 { int P1 {get; set;} => 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // int P1 {get; set;} => 0; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "int P1 {get; set;} => 0;").WithLocation(4, 5) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.P1"); Assert.True(p1.IsAbstract); Assert.True(p1.GetMethod.IsAbstract); Assert.True(p1.SetMethod.IsAbstract); Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); } [Fact] public void PropertyImplementation_107() { var source1 = @" public interface I1 { int P1 {add; remove;} = 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics( // (4,13): error CS1014: A get, set or init accessor expected // int P1 {add; remove;} = 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "add").WithLocation(4, 13), // (4,18): error CS1014: A get, set or init accessor expected // int P1 {add; remove;} = 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "remove").WithLocation(4, 18), // (4,9): error CS8053: Instance properties in interfaces cannot have initializers. // int P1 {add; remove;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P1").WithArguments("I1.P1").WithLocation(4, 9), // (4,9): error CS0548: 'I1.P1': property or indexer must have at least one accessor // int P1 {add; remove;} = 0; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "P1").WithArguments("I1.P1").WithLocation(4, 9) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.P1"); Assert.True(p1.IsAbstract); Assert.Null(p1.GetMethod); Assert.Null(p1.SetMethod); Assert.True(p1.IsReadOnly); Assert.True(p1.IsWriteOnly); } [Fact] public void PropertyImplementation_108() { var source1 = @" public interface I1 { int P1 {get; set;} = 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics( // (4,9): error CS8053: Instance properties in interfaces cannot have initializers.. // int P1 {get; set;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P1").WithArguments("I1.P1").WithLocation(4, 9) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.P1"); Assert.True(p1.IsAbstract); Assert.True(p1.GetMethod.IsAbstract); Assert.True(p1.SetMethod.IsAbstract); Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); } [Fact] public void PropertyImplementation_109() { var source1 = @" public interface I1 { int P1 { get { System.Console.WriteLine(""get P1""); return 0; } set; } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // According to LDM decision captured at https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-04-18.md, // we don't want to allow only one accessor to have an implementation. compilation1.VerifyDiagnostics( // (11,9): error CS0501: 'I1.P1.set' must declare a body because it is not marked abstract, extern, or partial // set; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.P1.set").WithLocation(11, 9) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.P1"); var getP1 = p1.GetMethod; var setP1 = p1.SetMethod; Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(getP1.IsAbstract); Assert.True(getP1.IsVirtual); Assert.False(setP1.IsAbstract); Assert.True(setP1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(getP1, test1.FindImplementationForInterfaceMember(getP1)); Assert.Same(setP1, test1.FindImplementationForInterfaceMember(setP1)); Assert.True(getP1.IsMetadataVirtual()); Assert.True(setP1.IsMetadataVirtual()); } [Fact] public void PropertyImplementation_110() { var source1 = @" public interface I1 { int P1 { get; set => System.Console.WriteLine(""set P1""); } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // According to LDM decision captured at https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-04-18.md, // we don't want to allow only one accessor to have an implementation. compilation1.VerifyDiagnostics( // (6,9): error CS0501: 'I1.P1.get' must declare a body because it is not marked abstract, extern, or partial // get; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.P1.get").WithLocation(6, 9) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.P1"); var getP1 = p1.GetMethod; var setP1 = p1.SetMethod; Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(getP1.IsAbstract); Assert.True(getP1.IsVirtual); Assert.False(setP1.IsAbstract); Assert.True(setP1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(getP1, test1.FindImplementationForInterfaceMember(getP1)); Assert.Same(setP1, test1.FindImplementationForInterfaceMember(setP1)); Assert.True(getP1.IsMetadataVirtual()); Assert.True(setP1.IsMetadataVirtual()); } [Fact] public void PropertyImplementation_201() { var source1 = @" interface I1 { int P1 => 1; int P2 => 2; int P3 { get => 3; } int P4 { get => 4; } int P5 { set => System.Console.WriteLine(5); } int P6 { set => System.Console.WriteLine(6); } int P7 { get { return 7;} set {System.Console.WriteLine(71);} } int P8 { get { return 8;} set {System.Console.WriteLine(81);} } } class Base { int P1 => 10; int P3 { get => 30; } int P5 { set => System.Console.WriteLine(50); } int P7 { get { return 70;} set {} } } class Derived : Base, I1 { int P2 => 20; int P4 { get => 40; } int P6 { set => System.Console.WriteLine(60); } int P8 { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1.P1); System.Console.WriteLine(i1.P2); System.Console.WriteLine(i1.P3); System.Console.WriteLine(i1.P4); i1.P5 = 0; i1.P6 = 0; System.Console.WriteLine(i1.P7); i1.P7 = 0; System.Console.WriteLine(i1.P8); i1.P8 = 0; } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidatePropertyImplementation_201(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"1 2 3 4 5 6 7 71 8 81 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidatePropertyImplementation_201(m); }); } private static void ValidatePropertyImplementation_201(ModuleSymbol m) { var p1 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P1"); var p2 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P2"); var p3 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P3"); var p4 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P4"); var p5 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P5"); var p6 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P6"); var p7 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P7"); var p8 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P8"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Same(p1, derived.FindImplementationForInterfaceMember(p1)); Assert.Same(p2, derived.FindImplementationForInterfaceMember(p2)); Assert.Same(p3, derived.FindImplementationForInterfaceMember(p3)); Assert.Same(p4, derived.FindImplementationForInterfaceMember(p4)); Assert.Same(p5, derived.FindImplementationForInterfaceMember(p5)); Assert.Same(p6, derived.FindImplementationForInterfaceMember(p6)); Assert.Same(p7, derived.FindImplementationForInterfaceMember(p7)); Assert.Same(p8, derived.FindImplementationForInterfaceMember(p8)); Assert.Same(p1.GetMethod, derived.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Same(p2.GetMethod, derived.FindImplementationForInterfaceMember(p2.GetMethod)); Assert.Same(p3.GetMethod, derived.FindImplementationForInterfaceMember(p3.GetMethod)); Assert.Same(p4.GetMethod, derived.FindImplementationForInterfaceMember(p4.GetMethod)); Assert.Same(p5.SetMethod, derived.FindImplementationForInterfaceMember(p5.SetMethod)); Assert.Same(p6.SetMethod, derived.FindImplementationForInterfaceMember(p6.SetMethod)); Assert.Same(p7.GetMethod, derived.FindImplementationForInterfaceMember(p7.GetMethod)); Assert.Same(p8.GetMethod, derived.FindImplementationForInterfaceMember(p8.GetMethod)); Assert.Same(p7.SetMethod, derived.FindImplementationForInterfaceMember(p7.SetMethod)); Assert.Same(p8.SetMethod, derived.FindImplementationForInterfaceMember(p8.SetMethod)); } [Fact] public void PropertyImplementation_202() { var source1 = @" interface I1 { int P1 => 1; int P2 => 2; int P3 { get => 3; } int P4 { get => 4; } int P5 { set => System.Console.WriteLine(5); } int P6 { set => System.Console.WriteLine(6); } int P7 { get { return 7;} set {System.Console.WriteLine(71);} } int P8 { get { return 8;} set {System.Console.WriteLine(81);} } } class Base : Test { int P1 => 10; int P3 { get => 30; } int P5 { set => System.Console.WriteLine(50); } int P7 { get { return 70;} set {} } } class Derived : Base, I1 { int P2 => 20; int P4 { get => 40; } int P6 { set => System.Console.WriteLine(60); } int P8 { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1.P1); System.Console.WriteLine(i1.P2); System.Console.WriteLine(i1.P3); System.Console.WriteLine(i1.P4); i1.P5 = 0; i1.P6 = 0; System.Console.WriteLine(i1.P7); i1.P7 = 0; System.Console.WriteLine(i1.P8); i1.P8 = 0; } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidatePropertyImplementation_201(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"1 2 3 4 5 6 7 71 8 81 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidatePropertyImplementation_201(m); }); } [Fact] public void PropertyImplementation_203() { var source1 = @" interface I1 { int P1 => 1; int P2 => 2; int P3 { get => 3; } int P4 { get => 4; } int P5 { set => System.Console.WriteLine(5); } int P6 { set => System.Console.WriteLine(6); } int P7 { get { return 7;} set {} } int P8 { get { return 8;} set {} } } class Base : Test { int P1 => 10; int P3 { get => 30; } int P5 { set => System.Console.WriteLine(50); } int P7 { get { return 70;} set {} } } class Derived : Base, I1 { int P2 => 20; int P4 { get => 40; } int P6 { set => System.Console.WriteLine(60); } int P8 { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1.P1); System.Console.WriteLine(i1.P2); System.Console.WriteLine(i1.P3); System.Console.WriteLine(i1.P4); i1.P5 = 0; i1.P6 = 0; System.Console.WriteLine(i1.P7); i1.P7 = 0; System.Console.WriteLine(i1.P8); i1.P8 = 0; } } class Test : I1 { int I1.P1 => 100; int I1.P2 => 200; int I1.P3 { get => 300; } int I1.P4 { get => 400; } int I1.P5 { set => System.Console.WriteLine(500); } int I1.P6 { set => System.Console.WriteLine(600); } int I1.P7 { get { return 700;} set {System.Console.WriteLine(701);} } int I1.P8 { get { return 800;} set {System.Console.WriteLine(801);} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var p1 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P1"); var p2 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P2"); var p3 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P3"); var p4 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P4"); var p5 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P5"); var p6 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P6"); var p7 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P7"); var p8 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P8"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Equal("System.Int32 Test.I1.P1 { get; }", derived.FindImplementationForInterfaceMember(p1).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P2 { get; }", derived.FindImplementationForInterfaceMember(p2).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P3 { get; }", derived.FindImplementationForInterfaceMember(p3).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P4 { get; }", derived.FindImplementationForInterfaceMember(p4).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P5 { set; }", derived.FindImplementationForInterfaceMember(p5).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P6 { set; }", derived.FindImplementationForInterfaceMember(p6).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P7 { get; set; }", derived.FindImplementationForInterfaceMember(p7).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P8 { get; set; }", derived.FindImplementationForInterfaceMember(p8).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P1.get", derived.FindImplementationForInterfaceMember(p1.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P2.get", derived.FindImplementationForInterfaceMember(p2.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P3.get", derived.FindImplementationForInterfaceMember(p3.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P4.get", derived.FindImplementationForInterfaceMember(p4.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.P5.set", derived.FindImplementationForInterfaceMember(p5.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.P6.set", derived.FindImplementationForInterfaceMember(p6.SetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P7.get", derived.FindImplementationForInterfaceMember(p7.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P8.get", derived.FindImplementationForInterfaceMember(p8.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.P7.set", derived.FindImplementationForInterfaceMember(p7.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.P8.set", derived.FindImplementationForInterfaceMember(p8.SetMethod).ToTestDisplayString()); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"100 200 300 400 500 600 700 701 800 801 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void PropertyImplementation_204() { var source1 = @" interface I1 { int P1 => 1; int P2 => 2; int P3 { get => 3; } int P4 { get => 4; } int P5 { set => System.Console.WriteLine(5); } int P6 { set => System.Console.WriteLine(6); } int P7 { get { return 7;} set {} } int P8 { get { return 8;} set {} } } class Base : Test { new int P1 => 10; new int P3 { get => 30; } new int P5 { set => System.Console.WriteLine(50); } new int P7 { get { return 70;} set {} } } class Derived : Base, I1 { new int P2 => 20; new int P4 { get => 40; } new int P6 { set => System.Console.WriteLine(60); } new int P8 { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1.P1); System.Console.WriteLine(i1.P2); System.Console.WriteLine(i1.P3); System.Console.WriteLine(i1.P4); i1.P5 = 0; i1.P6 = 0; System.Console.WriteLine(i1.P7); i1.P7 = 0; System.Console.WriteLine(i1.P8); i1.P8 = 0; } } class Test : I1 { public int P1 => 100; public int P2 => 200; public int P3 { get => 300; } public int P4 { get => 400; } public int P5 { set => System.Console.WriteLine(500); } public int P6 { set => System.Console.WriteLine(600); } public int P7 { get { return 700;} set {System.Console.WriteLine(701);} } public int P8 { get { return 800;} set {System.Console.WriteLine(801);} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var p1 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P1"); var p2 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P2"); var p3 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P3"); var p4 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P4"); var p5 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P5"); var p6 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P6"); var p7 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P7"); var p8 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P8"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Equal("System.Int32 Test.P1 { get; }", derived.FindImplementationForInterfaceMember(p1).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P2 { get; }", derived.FindImplementationForInterfaceMember(p2).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P3 { get; }", derived.FindImplementationForInterfaceMember(p3).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P4 { get; }", derived.FindImplementationForInterfaceMember(p4).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P5 { set; }", derived.FindImplementationForInterfaceMember(p5).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P6 { set; }", derived.FindImplementationForInterfaceMember(p6).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P7 { get; set; }", derived.FindImplementationForInterfaceMember(p7).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P8 { get; set; }", derived.FindImplementationForInterfaceMember(p8).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P1.get", derived.FindImplementationForInterfaceMember(p1.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P2.get", derived.FindImplementationForInterfaceMember(p2.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P3.get", derived.FindImplementationForInterfaceMember(p3.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P4.get", derived.FindImplementationForInterfaceMember(p4.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.P5.set", derived.FindImplementationForInterfaceMember(p5.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.P6.set", derived.FindImplementationForInterfaceMember(p6.SetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P7.get", derived.FindImplementationForInterfaceMember(p7.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P8.get", derived.FindImplementationForInterfaceMember(p8.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.P7.set", derived.FindImplementationForInterfaceMember(p7.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.P8.set", derived.FindImplementationForInterfaceMember(p8.SetMethod).ToTestDisplayString()); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"100 200 300 400 500 600 700 701 800 801 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void PropertyImplementation_501() { var source1 = @" public interface I1 { int P1 => 1; int P3 { get => 3; } int P5 { set => System.Console.WriteLine(5); } int P7 { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,15): error CS8501: Target runtime doesn't support default interface implementation. // int P1 => 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "1").WithLocation(4, 15), // (6,7): error CS8501: Target runtime doesn't support default interface implementation. // { get => 3; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(6, 7), // (8,7): error CS8501: Target runtime doesn't support default interface implementation. // { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(8, 7), // (11,9): error CS8501: Target runtime doesn't support default interface implementation. // get { return 7;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(11, 9), // (12,9): error CS8501: Target runtime doesn't support default interface implementation. // set {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(12, 9) ); ValidatePropertyImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.P7.set' cannot implement interface member 'I1.P7.set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.set", "I1.P7.set", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P1.get' cannot implement interface member 'I1.P1.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P1.get", "I1.P1.get", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P3.get' cannot implement interface member 'I1.P3.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P3.get", "I1.P3.get", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P5.set' cannot implement interface member 'I1.P5.set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P5.set", "I1.P5.set", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P7.get' cannot implement interface member 'I1.P7.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.get", "I1.P7.get", "Test2").WithLocation(2, 15) ); ValidatePropertyImplementation_501(compilation3.SourceModule, "Test2"); } private static void ValidatePropertyImplementation_501(ModuleSymbol m, string typeName) { var derived = m.GlobalNamespace.GetTypeMember(typeName); var i1 = derived.InterfacesNoUseSiteDiagnostics().Single(); Assert.Equal("I1", i1.ToTestDisplayString()); var p1 = i1.GetMember<PropertySymbol>("P1"); var p3 = i1.GetMember<PropertySymbol>("P3"); var p5 = i1.GetMember<PropertySymbol>("P5"); var p7 = i1.GetMember<PropertySymbol>("P7"); Assert.True(p1.IsVirtual); Assert.True(p3.IsVirtual); Assert.True(p5.IsVirtual); Assert.True(p7.IsVirtual); Assert.False(p1.IsAbstract); Assert.False(p3.IsAbstract); Assert.False(p5.IsAbstract); Assert.False(p7.IsAbstract); Assert.Same(p1, derived.FindImplementationForInterfaceMember(p1)); Assert.Same(p3, derived.FindImplementationForInterfaceMember(p3)); Assert.Same(p5, derived.FindImplementationForInterfaceMember(p5)); Assert.Same(p7, derived.FindImplementationForInterfaceMember(p7)); Assert.True(p1.GetMethod.IsVirtual); Assert.True(p3.GetMethod.IsVirtual); Assert.True(p5.SetMethod.IsVirtual); Assert.True(p7.GetMethod.IsVirtual); Assert.True(p7.SetMethod.IsVirtual); Assert.True(p1.GetMethod.IsMetadataVirtual()); Assert.True(p3.GetMethod.IsMetadataVirtual()); Assert.True(p5.SetMethod.IsMetadataVirtual()); Assert.True(p7.GetMethod.IsMetadataVirtual()); Assert.True(p7.SetMethod.IsMetadataVirtual()); Assert.False(p1.GetMethod.IsAbstract); Assert.False(p3.GetMethod.IsAbstract); Assert.False(p5.SetMethod.IsAbstract); Assert.False(p7.GetMethod.IsAbstract); Assert.False(p7.SetMethod.IsAbstract); Assert.Same(p1.GetMethod, derived.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Same(p3.GetMethod, derived.FindImplementationForInterfaceMember(p3.GetMethod)); Assert.Same(p5.SetMethod, derived.FindImplementationForInterfaceMember(p5.SetMethod)); Assert.Same(p7.GetMethod, derived.FindImplementationForInterfaceMember(p7.GetMethod)); Assert.Same(p7.SetMethod, derived.FindImplementationForInterfaceMember(p7.SetMethod)); } [Fact] public void PropertyImplementation_502() { var source1 = @" public interface I1 { int P1 => 1; int P3 { get => 3; } int P5 { set => System.Console.WriteLine(5); } int P7 { get { return 7;} set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.P7.set' cannot implement interface member 'I1.P7.set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.set", "I1.P7.set", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P1.get' cannot implement interface member 'I1.P1.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P1.get", "I1.P1.get", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P3.get' cannot implement interface member 'I1.P3.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P3.get", "I1.P3.get", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P5.set' cannot implement interface member 'I1.P5.set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P5.set", "I1.P5.set", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P7.get' cannot implement interface member 'I1.P7.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.get", "I1.P7.get", "Test2").WithLocation(2, 15) ); ValidatePropertyImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void PropertyImplementation_503() { var source1 = @" public interface I1 { int P1 => 1; int P3 { get => 3; } int P5 { set => System.Console.WriteLine(5); } int P7 { get { return 7;} set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" public interface I2 { void M2(); } class Test2 : I2 { public void M2() {} } "; var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, targetFramework: TargetFramework.DesktopLatestExtended, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var test2 = compilation3.GetTypeByMetadataName("Test2"); var i1 = compilation3.GetTypeByMetadataName("I1"); Assert.Equal("I1", i1.ToTestDisplayString()); var p1 = i1.GetMember<PropertySymbol>("P1"); var p3 = i1.GetMember<PropertySymbol>("P3"); var p5 = i1.GetMember<PropertySymbol>("P5"); var p7 = i1.GetMember<PropertySymbol>("P7"); Assert.Null(test2.FindImplementationForInterfaceMember(p1)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p5)); Assert.Null(test2.FindImplementationForInterfaceMember(p7)); Assert.Null(test2.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p3.GetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p5.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p7.GetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p7.SetMethod)); compilation3.VerifyDiagnostics(); } [Fact] public void PropertyImplementation_601() { var source1 = @" public interface I1 { int P1 => 1; int P3 { get => 3; } int P5 { set => System.Console.WriteLine(5); } int P7 { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,15): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P1 => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1").WithArguments("default interface implementation", "8.0").WithLocation(4, 15), // (4,15): error CS8701: Target runtime doesn't support default interface implementation. // int P1 => 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "1").WithLocation(4, 15), // (5,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P3 { get => 3; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(5, 14), // (5,14): error CS8701: Target runtime doesn't support default interface implementation. // int P3 { get => 3; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(5, 14), // (6,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P5 { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(6, 14), // (6,14): error CS8701: Target runtime doesn't support default interface implementation. // int P5 { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(6, 14), // (7,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P7 { get { return 7;} set {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(7, 14), // (7,14): error CS8701: Target runtime doesn't support default interface implementation. // int P7 { get { return 7;} set {} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(7, 14), // (7,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P7 { get { return 7;} set {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(7, 31), // (7,31): error CS8701: Target runtime doesn't support default interface implementation. // int P7 { get { return 7;} set {} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(7, 31) ); ValidatePropertyImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.P7.set' cannot implement interface member 'I1.P7.set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.set", "I1.P7.set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P7.set' cannot implement interface member 'I1.P7.set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.set", "I1.P7.set", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P1.get' cannot implement interface member 'I1.P1.get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P1.get", "I1.P1.get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P1.get' cannot implement interface member 'I1.P1.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P1.get", "I1.P1.get", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P3.get' cannot implement interface member 'I1.P3.get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P3.get", "I1.P3.get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P3.get' cannot implement interface member 'I1.P3.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P3.get", "I1.P3.get", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P5.set' cannot implement interface member 'I1.P5.set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P5.set", "I1.P5.set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P5.set' cannot implement interface member 'I1.P5.set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P5.set", "I1.P5.set", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P7.get' cannot implement interface member 'I1.P7.get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.get", "I1.P7.get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P7.get' cannot implement interface member 'I1.P7.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.get", "I1.P7.get", "Test2").WithLocation(2, 15) ); ValidatePropertyImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void PropertyImplementation_701() { var source1 = @" public interface I1 { int P1 => 1; int P3 { get => 3; } int P5 { set => System.Console.WriteLine(5); } int P7 { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,15): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P1 => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1").WithArguments("default interface implementation", "8.0").WithLocation(4, 15), // (5,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P3 { get => 3; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(5, 14), // (6,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P5 { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(6, 14), // (7,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P7 { get { return 7;} set {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(7, 14), // (7,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P7 { get { return 7;} set {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(7, 31) ); ValidatePropertyImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidatePropertyImplementation_501(compilation2.SourceModule, "Test2"); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test2Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test2"); Assert.Equal("I1", test2Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidatePropertyImplementation_501(m, "Test2"); }); var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.P7.set' cannot implement interface member 'I1.P7.set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.set", "I1.P7.set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P1.get' cannot implement interface member 'I1.P1.get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P1.get", "I1.P1.get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P3.get' cannot implement interface member 'I1.P3.get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P3.get", "I1.P3.get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P5.set' cannot implement interface member 'I1.P5.set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P5.set", "I1.P5.set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P7.get' cannot implement interface member 'I1.P7.get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.get", "I1.P7.get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15) ); ValidatePropertyImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void PropertyImplementation_901() { var source1 = @" public interface I1 { static int P1 => 1; static int P3 { get => 3; } static int P5 { set => System.Console.WriteLine(5); } static int P7 { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,16): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static int P1 => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "P1").WithArguments("default interface implementation", "8.0").WithLocation(4, 16), // (5,16): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static int P3 { get => 3; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "P3").WithArguments("default interface implementation", "8.0").WithLocation(5, 16), // (6,16): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static int P5 { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "P5").WithArguments("default interface implementation", "8.0").WithLocation(6, 16), // (7,16): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static int P7 { get { return 7;} set {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "P7").WithArguments("default interface implementation", "8.0").WithLocation(7, 16) ); var derived = compilation1.SourceModule.GlobalNamespace.GetTypeMember("Test1"); var i1 = derived.InterfacesNoUseSiteDiagnostics().Single(); Assert.Equal("I1", i1.ToTestDisplayString()); var p1 = i1.GetMember<PropertySymbol>("P1"); var p3 = i1.GetMember<PropertySymbol>("P3"); var p5 = i1.GetMember<PropertySymbol>("P5"); var p7 = i1.GetMember<PropertySymbol>("P7"); Assert.True(p1.IsStatic); Assert.True(p3.IsStatic); Assert.True(p5.IsStatic); Assert.True(p7.IsStatic); Assert.False(p1.IsVirtual); Assert.False(p3.IsVirtual); Assert.False(p5.IsVirtual); Assert.False(p7.IsVirtual); Assert.False(p1.IsAbstract); Assert.False(p3.IsAbstract); Assert.False(p5.IsAbstract); Assert.False(p7.IsAbstract); Assert.Null(derived.FindImplementationForInterfaceMember(p1)); Assert.Null(derived.FindImplementationForInterfaceMember(p3)); Assert.Null(derived.FindImplementationForInterfaceMember(p5)); Assert.Null(derived.FindImplementationForInterfaceMember(p7)); Assert.True(p1.GetMethod.IsStatic); Assert.True(p3.GetMethod.IsStatic); Assert.True(p5.SetMethod.IsStatic); Assert.True(p7.GetMethod.IsStatic); Assert.True(p7.SetMethod.IsStatic); Assert.False(p1.GetMethod.IsVirtual); Assert.False(p3.GetMethod.IsVirtual); Assert.False(p5.SetMethod.IsVirtual); Assert.False(p7.GetMethod.IsVirtual); Assert.False(p7.SetMethod.IsVirtual); Assert.False(p1.GetMethod.IsMetadataVirtual()); Assert.False(p3.GetMethod.IsMetadataVirtual()); Assert.False(p5.SetMethod.IsMetadataVirtual()); Assert.False(p7.GetMethod.IsMetadataVirtual()); Assert.False(p7.SetMethod.IsMetadataVirtual()); Assert.False(p1.GetMethod.IsAbstract); Assert.False(p3.GetMethod.IsAbstract); Assert.False(p5.SetMethod.IsAbstract); Assert.False(p7.GetMethod.IsAbstract); Assert.False(p7.SetMethod.IsAbstract); Assert.Null(derived.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(derived.FindImplementationForInterfaceMember(p3.GetMethod)); Assert.Null(derived.FindImplementationForInterfaceMember(p5.SetMethod)); Assert.Null(derived.FindImplementationForInterfaceMember(p7.GetMethod)); Assert.Null(derived.FindImplementationForInterfaceMember(p7.SetMethod)); } [Fact] public void IndexerImplementation_101() { var source1 = @" public interface I1 { int this[int i] { get { System.Console.WriteLine(""get P1""); return 0; } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "; ValidateIndexerImplementation_101(source1); } private void ValidateIndexerImplementation_101(string source1) { ValidatePropertyImplementation_101(source1, "this[]", haveGet: true, haveSet: false, accessCode: @" _ = i1[0]; ", expectedOutput: "get P1"); } [Fact] public void IndexerImplementation_102() { var source1 = @" public interface I1 { int this[int i] { get { System.Console.WriteLine(""get P1""); return 0; } set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1[0] = i1[0]; } } "; ValidateIndexerImplementation_102(source1); } private void ValidateIndexerImplementation_102(string source1) { ValidatePropertyImplementation_101(source1, "this[]", haveGet: true, haveSet: true, accessCode: @" i1[0] = i1[0]; ", expectedOutput: @"get P1 set P1"); } [Fact] public void IndexerImplementation_103() { var source1 = @" public interface I1 { int this[int i] { set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } } "; ValidateIndexerImplementation_103(source1); } private void ValidateIndexerImplementation_103(string source1) { ValidatePropertyImplementation_101(source1, "this[]", haveGet: false, haveSet: true, accessCode: @" i1[0] = 1; ", expectedOutput: "set P1"); } [Fact] public void IndexerImplementation_104() { var source1 = @" public interface I1 { int this[int i] => Test1.GetInt(); } class Test1 : I1 { public static int GetInt() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "; ValidateIndexerImplementation_101(source1); } [Fact] public void IndexerImplementation_105() { var source1 = @" public interface I1 { int this[int i] {add; remove;} => 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,22): error CS1014: A get, set or init accessor expected // int this[int i] {add; remove;} => 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "add").WithLocation(4, 22), // (4,27): error CS1014: A get, set or init accessor expected // int this[int i] {add; remove;} => 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "remove").WithLocation(4, 27), // (4,9): error CS0548: 'I1.this[int]': property or indexer must have at least one accessor // int this[int i] {add; remove;} => 0; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I1.this[int]").WithLocation(4, 9), // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // int this[int i] {add; remove;} => 0; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "int this[int i] {add; remove;} => 0;").WithLocation(4, 5) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.this[]"); Assert.True(p1.IsAbstract); Assert.Null(p1.GetMethod); Assert.Null(p1.SetMethod); Assert.True(p1.IsReadOnly); Assert.True(p1.IsWriteOnly); } [Fact] public void IndexerImplementation_106() { var source1 = @" public interface I1 { int this[int i] {get; set;} => 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // int this[int i] {get; set;} => 0; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "int this[int i] {get; set;} => 0;").WithLocation(4, 5) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.this[]"); Assert.True(p1.IsAbstract); Assert.True(p1.GetMethod.IsAbstract); Assert.True(p1.SetMethod.IsAbstract); Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); } [Fact] public void IndexerImplementation_107() { var source1 = @" public interface I1 { int this[int i] {add; remove;} = 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,36): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // int this[int i] {add; remove;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(4, 36), // (4,22): error CS1014: A get, set or init accessor expected // int this[int i] {add; remove;} = 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "add").WithLocation(4, 22), // (4,27): error CS1014: A get, set or init accessor expected // int this[int i] {add; remove;} = 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "remove").WithLocation(4, 27), // (4,9): error CS0548: 'I1.this[int]': property or indexer must have at least one accessor // int this[int i] {add; remove;} = 0; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I1.this[int]").WithLocation(4, 9) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.this[]"); Assert.True(p1.IsAbstract); Assert.Null(p1.GetMethod); Assert.Null(p1.SetMethod); Assert.True(p1.IsReadOnly); Assert.True(p1.IsWriteOnly); } [Fact] public void IndexerImplementation_108() { var source1 = @" public interface I1 { int this[int i] {get; set;} = 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,33): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // int this[int i] {get; set;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(4, 33) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.this[]"); Assert.True(p1.IsAbstract); Assert.True(p1.GetMethod.IsAbstract); Assert.True(p1.SetMethod.IsAbstract); Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); } [Fact] public void IndexerImplementation_109() { var source1 = @" public interface I1 { int this[int i] { get { System.Console.WriteLine(""get P1""); return 0; } set; } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // According to LDM decision captured at https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-04-18.md, // we don't want to allow only one accessor to have an implementation. compilation1.VerifyDiagnostics( // (11,9): error CS0501: 'I1.this[int].set' must declare a body because it is not marked abstract, extern, or partial // set; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.this[int].set") ); var p1 = compilation1.GetMember<PropertySymbol>("I1.this[]"); var getP1 = p1.GetMethod; var setP1 = p1.SetMethod; Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(getP1.IsAbstract); Assert.True(getP1.IsVirtual); Assert.False(setP1.IsAbstract); Assert.True(setP1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(getP1, test1.FindImplementationForInterfaceMember(getP1)); Assert.Same(setP1, test1.FindImplementationForInterfaceMember(setP1)); Assert.True(getP1.IsMetadataVirtual()); Assert.True(setP1.IsMetadataVirtual()); } [Fact] public void IndexerImplementation_110() { var source1 = @" public interface I1 { int this[int i] { get; set => System.Console.WriteLine(""set P1""); } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // According to LDM decision captured at https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-04-18.md, // we don't want to allow only one accessor to have an implementation. compilation1.VerifyDiagnostics( // (6,9): error CS0501: 'I1.this[int].get' must declare a body because it is not marked abstract, extern, or partial // get; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.this[int].get") ); var p1 = compilation1.GetMember<PropertySymbol>("I1.this[]"); var getP1 = p1.GetMethod; var setP1 = p1.SetMethod; Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(getP1.IsAbstract); Assert.True(getP1.IsVirtual); Assert.False(setP1.IsAbstract); Assert.True(setP1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(getP1, test1.FindImplementationForInterfaceMember(getP1)); Assert.Same(setP1, test1.FindImplementationForInterfaceMember(setP1)); Assert.True(getP1.IsMetadataVirtual()); Assert.True(setP1.IsMetadataVirtual()); } [Fact] public void IndexerImplementation_201() { var source1 = @" interface I1 { int this[sbyte i] => 1; int this[byte i] => 2; int this[short i] { get => 3; } int this[ushort i] { get => 4; } int this[int i] { set => System.Console.WriteLine(5); } int this[uint i] { set => System.Console.WriteLine(6); } int this[long i] { get { return 7;} set {System.Console.WriteLine(71);} } int this[ulong i] { get { return 8;} set {System.Console.WriteLine(81);} } } class Base { int this[sbyte i] => 10; int this[short i] { get => 30; } int this[int i] { set => System.Console.WriteLine(50); } int this[long i] { get { return 70;} set {} } } class Derived : Base, I1 { int this[byte i] => 20; int this[ushort i] { get => 40; } int this[uint i] { set => System.Console.WriteLine(60); } int this[ulong i] { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1[(sbyte)0]); System.Console.WriteLine(i1[(byte)0]); System.Console.WriteLine(i1[(short)0]); System.Console.WriteLine(i1[(ushort)0]); i1[(int)0] = 0; i1[(uint)0] = 0; System.Console.WriteLine(i1[(long)0]); i1[(long)0] = 0; System.Console.WriteLine(i1[(ulong)0]); i1[(ulong)0] = 0; } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateIndexerImplementation_201(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"1 2 3 4 5 6 7 71 8 81 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidateIndexerImplementation_201(m); }); } private static void ValidateIndexerImplementation_201(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var indexers = i1.GetMembers("this[]"); var p1 = (PropertySymbol)indexers[0]; var p2 = (PropertySymbol)indexers[1]; var p3 = (PropertySymbol)indexers[2]; var p4 = (PropertySymbol)indexers[3]; var p5 = (PropertySymbol)indexers[4]; var p6 = (PropertySymbol)indexers[5]; var p7 = (PropertySymbol)indexers[6]; var p8 = (PropertySymbol)indexers[7]; var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Same(p1, derived.FindImplementationForInterfaceMember(p1)); Assert.Same(p2, derived.FindImplementationForInterfaceMember(p2)); Assert.Same(p3, derived.FindImplementationForInterfaceMember(p3)); Assert.Same(p4, derived.FindImplementationForInterfaceMember(p4)); Assert.Same(p5, derived.FindImplementationForInterfaceMember(p5)); Assert.Same(p6, derived.FindImplementationForInterfaceMember(p6)); Assert.Same(p7, derived.FindImplementationForInterfaceMember(p7)); Assert.Same(p8, derived.FindImplementationForInterfaceMember(p8)); Assert.Same(p1.GetMethod, derived.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Same(p2.GetMethod, derived.FindImplementationForInterfaceMember(p2.GetMethod)); Assert.Same(p3.GetMethod, derived.FindImplementationForInterfaceMember(p3.GetMethod)); Assert.Same(p4.GetMethod, derived.FindImplementationForInterfaceMember(p4.GetMethod)); Assert.Same(p5.SetMethod, derived.FindImplementationForInterfaceMember(p5.SetMethod)); Assert.Same(p6.SetMethod, derived.FindImplementationForInterfaceMember(p6.SetMethod)); Assert.Same(p7.GetMethod, derived.FindImplementationForInterfaceMember(p7.GetMethod)); Assert.Same(p8.GetMethod, derived.FindImplementationForInterfaceMember(p8.GetMethod)); Assert.Same(p7.SetMethod, derived.FindImplementationForInterfaceMember(p7.SetMethod)); Assert.Same(p8.SetMethod, derived.FindImplementationForInterfaceMember(p8.SetMethod)); } [Fact] public void IndexerImplementation_202() { var source1 = @" interface I1 { int this[sbyte i] => 1; int this[byte i] => 2; int this[short i] { get => 3; } int this[ushort i] { get => 4; } int this[int i] { set => System.Console.WriteLine(5); } int this[uint i] { set => System.Console.WriteLine(6); } int this[long i] { get { return 7;} set {System.Console.WriteLine(71);} } int this[ulong i] { get { return 8;} set {System.Console.WriteLine(81);} } } class Base : Test { int this[sbyte i] => 10; int this[short i] { get => 30; } int this[int i] { set => System.Console.WriteLine(50); } int this[long i] { get { return 70;} set {} } } class Derived : Base, I1 { int this[byte i] => 20; int this[ushort i] { get => 40; } int this[uint i] { set => System.Console.WriteLine(60); } int this[ulong i] { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1[(sbyte)0]); System.Console.WriteLine(i1[(byte)0]); System.Console.WriteLine(i1[(short)0]); System.Console.WriteLine(i1[(ushort)0]); i1[(int)0] = 0; i1[(uint)0] = 0; System.Console.WriteLine(i1[(long)0]); i1[(long)0] = 0; System.Console.WriteLine(i1[(ulong)0]); i1[(ulong)0] = 0; } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateIndexerImplementation_201(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"1 2 3 4 5 6 7 71 8 81 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidateIndexerImplementation_201(m); }); } [Fact] public void IndexerImplementation_203() { var source1 = @" interface I1 { int this[sbyte i] => 1; int this[byte i] => 2; int this[short i] { get => 3; } int this[ushort i] { get => 4; } int this[int i] { set => System.Console.WriteLine(5); } int this[uint i] { set => System.Console.WriteLine(6); } int this[long i] { get { return 7;} set {} } int this[ulong i] { get { return 8;} set {} } } class Base : Test { int this[sbyte i] => 10; int this[short i] { get => 30; } int this[int i] { set => System.Console.WriteLine(50); } int this[long i] { get { return 70;} set {} } } class Derived : Base, I1 { int this[byte i] => 20; int this[ushort i] { get => 40; } int this[uint i] { set => System.Console.WriteLine(60); } int this[ulong i] { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1[(sbyte)0]); System.Console.WriteLine(i1[(byte)0]); System.Console.WriteLine(i1[(short)0]); System.Console.WriteLine(i1[(ushort)0]); i1[(int)0] = 0; i1[(uint)0] = 0; System.Console.WriteLine(i1[(long)0]); i1[(long)0] = 0; System.Console.WriteLine(i1[(ulong)0]); i1[(ulong)0] = 0; } } class Test : I1 { int I1.this[sbyte i] => 100; int I1.this[byte i] => 200; int I1.this[short i] { get => 300; } int I1.this[ushort i] { get => 400; } int I1.this[int i] { set => System.Console.WriteLine(500); } int I1.this[uint i] { set => System.Console.WriteLine(600); } int I1.this[long i] { get { return 700;} set {System.Console.WriteLine(701);} } int I1.this[ulong i] { get { return 800;} set {System.Console.WriteLine(801);} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var indexers = i1.GetMembers("this[]"); var p1 = (PropertySymbol)indexers[0]; var p2 = (PropertySymbol)indexers[1]; var p3 = (PropertySymbol)indexers[2]; var p4 = (PropertySymbol)indexers[3]; var p5 = (PropertySymbol)indexers[4]; var p6 = (PropertySymbol)indexers[5]; var p7 = (PropertySymbol)indexers[6]; var p8 = (PropertySymbol)indexers[7]; var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); string name = m is PEModuleSymbol ? "Item" : "this"; Assert.Equal("System.Int32 Test.I1." + name + "[System.SByte i] { get; }", derived.FindImplementationForInterfaceMember(p1).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1." + name + "[System.Byte i] { get; }", derived.FindImplementationForInterfaceMember(p2).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1." + name + "[System.Int16 i] { get; }", derived.FindImplementationForInterfaceMember(p3).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1." + name + "[System.UInt16 i] { get; }", derived.FindImplementationForInterfaceMember(p4).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1." + name + "[System.Int32 i] { set; }", derived.FindImplementationForInterfaceMember(p5).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1." + name + "[System.UInt32 i] { set; }", derived.FindImplementationForInterfaceMember(p6).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1." + name + "[System.Int64 i] { get; set; }", derived.FindImplementationForInterfaceMember(p7).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1." + name + "[System.UInt64 i] { get; set; }", derived.FindImplementationForInterfaceMember(p8).ToTestDisplayString()); if (m is PEModuleSymbol) { Assert.Equal("System.Int32 Test.I1.get_Item(System.SByte i)", derived.FindImplementationForInterfaceMember(p1.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.get_Item(System.Byte i)", derived.FindImplementationForInterfaceMember(p2.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.get_Item(System.Int16 i)", derived.FindImplementationForInterfaceMember(p3.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.get_Item(System.UInt16 i)", derived.FindImplementationForInterfaceMember(p4.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.set_Item(System.Int32 i, System.Int32 value)", derived.FindImplementationForInterfaceMember(p5.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.set_Item(System.UInt32 i, System.Int32 value)", derived.FindImplementationForInterfaceMember(p6.SetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.get_Item(System.Int64 i)", derived.FindImplementationForInterfaceMember(p7.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.get_Item(System.UInt64 i)", derived.FindImplementationForInterfaceMember(p8.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.set_Item(System.Int64 i, System.Int32 value)", derived.FindImplementationForInterfaceMember(p7.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.set_Item(System.UInt64 i, System.Int32 value)", derived.FindImplementationForInterfaceMember(p8.SetMethod).ToTestDisplayString()); } else { Assert.Equal("System.Int32 Test.I1.this[System.SByte i].get", derived.FindImplementationForInterfaceMember(p1.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.this[System.Byte i].get", derived.FindImplementationForInterfaceMember(p2.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.this[System.Int16 i].get", derived.FindImplementationForInterfaceMember(p3.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.this[System.UInt16 i].get", derived.FindImplementationForInterfaceMember(p4.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.this[System.Int32 i].set", derived.FindImplementationForInterfaceMember(p5.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.this[System.UInt32 i].set", derived.FindImplementationForInterfaceMember(p6.SetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.this[System.Int64 i].get", derived.FindImplementationForInterfaceMember(p7.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.this[System.UInt64 i].get", derived.FindImplementationForInterfaceMember(p8.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.this[System.Int64 i].set", derived.FindImplementationForInterfaceMember(p7.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.this[System.UInt64 i].set", derived.FindImplementationForInterfaceMember(p8.SetMethod).ToTestDisplayString()); } } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"100 200 300 400 500 600 700 701 800 801 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void IndexerImplementation_204() { var source1 = @" interface I1 { int this[sbyte i] => 1; int this[byte i] => 2; int this[short i] { get => 3; } int this[ushort i] { get => 4; } int this[int i] { set => System.Console.WriteLine(5); } int this[uint i] { set => System.Console.WriteLine(6); } int this[long i] { get { return 7;} set {} } int this[ulong i] { get { return 8;} set {} } } class Base : Test { new int this[sbyte i] => 10; new int this[short i] { get => 30; } new int this[int i] { set => System.Console.WriteLine(50); } new int this[long i] { get { return 70;} set {} } } class Derived : Base, I1 { new int this[byte i] => 20; new int this[ushort i] { get => 40; } new int this[uint i] { set => System.Console.WriteLine(60); } new int this[ulong i] { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1[(sbyte)0]); System.Console.WriteLine(i1[(byte)0]); System.Console.WriteLine(i1[(short)0]); System.Console.WriteLine(i1[(ushort)0]); i1[(int)0] = 0; i1[(uint)0] = 0; System.Console.WriteLine(i1[(long)0]); i1[(long)0] = 0; System.Console.WriteLine(i1[(ulong)0]); i1[(ulong)0] = 0; } } class Test : I1 { public int this[sbyte i] => 100; public int this[byte i] => 200; public int this[short i] { get => 300; } public int this[ushort i] { get => 400; } public int this[int i] { set => System.Console.WriteLine(500); } public int this[uint i] { set => System.Console.WriteLine(600); } public int this[long i] { get { return 700;} set {System.Console.WriteLine(701);} } public int this[ulong i] { get { return 800;} set {System.Console.WriteLine(801);} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var indexers = i1.GetMembers("this[]"); var p1 = (PropertySymbol)indexers[0]; var p2 = (PropertySymbol)indexers[1]; var p3 = (PropertySymbol)indexers[2]; var p4 = (PropertySymbol)indexers[3]; var p5 = (PropertySymbol)indexers[4]; var p6 = (PropertySymbol)indexers[5]; var p7 = (PropertySymbol)indexers[6]; var p8 = (PropertySymbol)indexers[7]; var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Equal("System.Int32 Test.this[System.SByte i] { get; }", derived.FindImplementationForInterfaceMember(p1).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.Byte i] { get; }", derived.FindImplementationForInterfaceMember(p2).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.Int16 i] { get; }", derived.FindImplementationForInterfaceMember(p3).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.UInt16 i] { get; }", derived.FindImplementationForInterfaceMember(p4).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.Int32 i] { set; }", derived.FindImplementationForInterfaceMember(p5).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.UInt32 i] { set; }", derived.FindImplementationForInterfaceMember(p6).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.Int64 i] { get; set; }", derived.FindImplementationForInterfaceMember(p7).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.UInt64 i] { get; set; }", derived.FindImplementationForInterfaceMember(p8).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.SByte i].get", derived.FindImplementationForInterfaceMember(p1.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.Byte i].get", derived.FindImplementationForInterfaceMember(p2.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.Int16 i].get", derived.FindImplementationForInterfaceMember(p3.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.UInt16 i].get", derived.FindImplementationForInterfaceMember(p4.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.this[System.Int32 i].set", derived.FindImplementationForInterfaceMember(p5.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.this[System.UInt32 i].set", derived.FindImplementationForInterfaceMember(p6.SetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.Int64 i].get", derived.FindImplementationForInterfaceMember(p7.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.UInt64 i].get", derived.FindImplementationForInterfaceMember(p8.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.this[System.Int64 i].set", derived.FindImplementationForInterfaceMember(p7.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.this[System.UInt64 i].set", derived.FindImplementationForInterfaceMember(p8.SetMethod).ToTestDisplayString()); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"100 200 300 400 500 600 700 701 800 801 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void IndexerImplementation_501() { var source1 = @" public interface I1 { int this[sbyte i] => 1; int this[short i] { get => 3; } int this[int i] { set => System.Console.WriteLine(5); } int this[long i] { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,26): error CS8501: Target runtime doesn't support default interface implementation. // int this[sbyte i] => 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "1").WithLocation(4, 26), // (6,7): error CS8501: Target runtime doesn't support default interface implementation. // { get => 3; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(6, 7), // (8,7): error CS8501: Target runtime doesn't support default interface implementation. // { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(8, 7), // (11,9): error CS8501: Target runtime doesn't support default interface implementation. // get { return 7;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(11, 9), // (12,9): error CS8501: Target runtime doesn't support default interface implementation. // set {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(12, 9) ); ValidateIndexerImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.this[long].set' cannot implement interface member 'I1.this[long].set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].set", "I1.this[long].set", "Test2"), // (2,15): error CS8502: 'I1.this[sbyte].get' cannot implement interface member 'I1.this[sbyte].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[sbyte].get", "I1.this[sbyte].get", "Test2"), // (2,15): error CS8502: 'I1.this[short].get' cannot implement interface member 'I1.this[short].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[short].get", "I1.this[short].get", "Test2"), // (2,15): error CS8502: 'I1.this[int].set' cannot implement interface member 'I1.this[int].set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[int].set", "I1.this[int].set", "Test2"), // (2,15): error CS8502: 'I1.this[long].get' cannot implement interface member 'I1.this[long].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].get", "I1.this[long].get", "Test2") ); ValidateIndexerImplementation_501(compilation3.SourceModule, "Test2"); } private static void ValidateIndexerImplementation_501(ModuleSymbol m, string typeName) { var derived = m.GlobalNamespace.GetTypeMember(typeName); var i1 = derived.InterfacesNoUseSiteDiagnostics().Single(); Assert.Equal("I1", i1.ToTestDisplayString()); var indexers = i1.GetMembers("this[]"); var p1 = (PropertySymbol)indexers[0]; var p3 = (PropertySymbol)indexers[1]; var p5 = (PropertySymbol)indexers[2]; var p7 = (PropertySymbol)indexers[3]; Assert.True(p1.IsVirtual); Assert.True(p3.IsVirtual); Assert.True(p5.IsVirtual); Assert.True(p7.IsVirtual); Assert.False(p1.IsAbstract); Assert.False(p3.IsAbstract); Assert.False(p5.IsAbstract); Assert.False(p7.IsAbstract); Assert.Same(p1, derived.FindImplementationForInterfaceMember(p1)); Assert.Same(p3, derived.FindImplementationForInterfaceMember(p3)); Assert.Same(p5, derived.FindImplementationForInterfaceMember(p5)); Assert.Same(p7, derived.FindImplementationForInterfaceMember(p7)); Assert.True(p1.GetMethod.IsVirtual); Assert.True(p3.GetMethod.IsVirtual); Assert.True(p5.SetMethod.IsVirtual); Assert.True(p7.GetMethod.IsVirtual); Assert.True(p7.SetMethod.IsVirtual); Assert.True(p1.GetMethod.IsMetadataVirtual()); Assert.True(p3.GetMethod.IsMetadataVirtual()); Assert.True(p5.SetMethod.IsMetadataVirtual()); Assert.True(p7.GetMethod.IsMetadataVirtual()); Assert.True(p7.SetMethod.IsMetadataVirtual()); Assert.False(p1.GetMethod.IsAbstract); Assert.False(p3.GetMethod.IsAbstract); Assert.False(p5.SetMethod.IsAbstract); Assert.False(p7.GetMethod.IsAbstract); Assert.False(p7.SetMethod.IsAbstract); Assert.Same(p1.GetMethod, derived.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Same(p3.GetMethod, derived.FindImplementationForInterfaceMember(p3.GetMethod)); Assert.Same(p5.SetMethod, derived.FindImplementationForInterfaceMember(p5.SetMethod)); Assert.Same(p7.GetMethod, derived.FindImplementationForInterfaceMember(p7.GetMethod)); Assert.Same(p7.SetMethod, derived.FindImplementationForInterfaceMember(p7.SetMethod)); } [Fact] public void IndexerImplementation_502() { var source1 = @" public interface I1 { int this[sbyte i] => 1; int this[short i] { get => 3; } int this[int i] { set => System.Console.WriteLine(5); } int this[long i] { get { return 7;} set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.this[short].get' cannot implement interface member 'I1.this[short].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[short].get", "I1.this[short].get", "Test2"), // (2,15): error CS8502: 'I1.this[int].set' cannot implement interface member 'I1.this[int].set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[int].set", "I1.this[int].set", "Test2"), // (2,15): error CS8502: 'I1.this[long].get' cannot implement interface member 'I1.this[long].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].get", "I1.this[long].get", "Test2"), // (2,15): error CS8502: 'I1.this[long].set' cannot implement interface member 'I1.this[long].set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].set", "I1.this[long].set", "Test2"), // (2,15): error CS8502: 'I1.this[sbyte].get' cannot implement interface member 'I1.this[sbyte].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[sbyte].get", "I1.this[sbyte].get", "Test2") ); ValidateIndexerImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void IndexerImplementation_503() { var source1 = @" public interface I1 { int this[sbyte i] => 1; int this[short i] { get => 3; } int this[int i] { set => System.Console.WriteLine(5); } int this[long i] { get { return 7;} set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" public interface I2 { void M2(); } class Test2 : I2 { public void M2() {} } "; var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var test2 = compilation3.GetTypeByMetadataName("Test2"); var i1 = compilation3.GetTypeByMetadataName("I1"); Assert.Equal("I1", i1.ToTestDisplayString()); var indexers = i1.GetMembers("this[]"); var p1 = (PropertySymbol)indexers[0]; var p3 = (PropertySymbol)indexers[1]; var p5 = (PropertySymbol)indexers[2]; var p7 = (PropertySymbol)indexers[3]; Assert.Null(test2.FindImplementationForInterfaceMember(p1)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p5)); Assert.Null(test2.FindImplementationForInterfaceMember(p7)); Assert.Null(test2.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p3.GetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p5.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p7.GetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p7.SetMethod)); compilation3.VerifyDiagnostics(); } [Fact] public void IndexerImplementation_601() { var source1 = @" public interface I1 { int this[sbyte i] => 1; int this[short i] { get => 3; } int this[int i] { set => System.Console.WriteLine(5); } int this[long i] { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,26): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int this[sbyte i] => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1").WithArguments("default interface implementation", "8.0").WithLocation(4, 26), // (4,26): error CS8701: Target runtime doesn't support default interface implementation. // int this[sbyte i] => 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "1").WithLocation(4, 26), // (6,7): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // { get => 3; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(6, 7), // (6,7): error CS8701: Target runtime doesn't support default interface implementation. // { get => 3; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(6, 7), // (8,7): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(8, 7), // (8,7): error CS8701: Target runtime doesn't support default interface implementation. // { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(8, 7), // (11,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // get { return 7;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(11, 9), // (11,9): error CS8701: Target runtime doesn't support default interface implementation. // get { return 7;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(11, 9), // (12,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // set {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(12, 9), // (12,9): error CS8701: Target runtime doesn't support default interface implementation. // set {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(12, 9) ); ValidateIndexerImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.this[long].set' cannot implement interface member 'I1.this[long].set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].set", "I1.this[long].set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.this[long].set' cannot implement interface member 'I1.this[long].set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].set", "I1.this[long].set", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[sbyte].get' cannot implement interface member 'I1.this[sbyte].get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[sbyte].get", "I1.this[sbyte].get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.this[sbyte].get' cannot implement interface member 'I1.this[sbyte].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[sbyte].get", "I1.this[sbyte].get", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[short].get' cannot implement interface member 'I1.this[short].get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[short].get", "I1.this[short].get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.this[short].get' cannot implement interface member 'I1.this[short].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[short].get", "I1.this[short].get", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[int].set' cannot implement interface member 'I1.this[int].set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[int].set", "I1.this[int].set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.this[int].set' cannot implement interface member 'I1.this[int].set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[int].set", "I1.this[int].set", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[long].get' cannot implement interface member 'I1.this[long].get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].get", "I1.this[long].get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.this[long].get' cannot implement interface member 'I1.this[long].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].get", "I1.this[long].get", "Test2").WithLocation(2, 15) ); ValidateIndexerImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void IndexerImplementation_701() { var source1 = @" public interface I1 { int this[sbyte i] => 1; int this[short i] { get => 3; } int this[int i] { set => System.Console.WriteLine(5); } int this[long i] { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,26): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int this[sbyte i] => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1").WithArguments("default interface implementation", "8.0").WithLocation(4, 26), // (6,7): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // { get => 3; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(6, 7), // (8,7): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(8, 7), // (11,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // get { return 7;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(11, 9), // (12,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // set {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(12, 9) ); ValidateIndexerImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateIndexerImplementation_501(compilation2.SourceModule, "Test2"); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test2Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test2"); Assert.Equal("I1", test2Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidateIndexerImplementation_501(m, "Test2"); }); var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.this[long].set' cannot implement interface member 'I1.this[long].set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].set", "I1.this[long].set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[sbyte].get' cannot implement interface member 'I1.this[sbyte].get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[sbyte].get", "I1.this[sbyte].get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[short].get' cannot implement interface member 'I1.this[short].get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[short].get", "I1.this[short].get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[int].set' cannot implement interface member 'I1.this[int].set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[int].set", "I1.this[int].set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[long].get' cannot implement interface member 'I1.this[long].get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].get", "I1.this[long].get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15) ); ValidateIndexerImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void IndexerImplementation_901() { var source1 = @" public interface I1 { static int this[sbyte i] => 1; static int this[short i] { get => 3; } static int this[int i] { set => System.Console.WriteLine(5); } static int this[long i] { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,16): error CS0106: The modifier 'static' is not valid for this item // static int this[sbyte i] => 1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(4, 16), // (4,33): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static int this[sbyte i] => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1").WithArguments("default interface implementation", "8.0").WithLocation(4, 33), // (5,16): error CS0106: The modifier 'static' is not valid for this item // static int this[short i] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(5, 16), // (6,7): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // { get => 3; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(6, 7), // (7,16): error CS0106: The modifier 'static' is not valid for this item // static int this[int i] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(7, 16), // (8,7): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(8, 7), // (9,16): error CS0106: The modifier 'static' is not valid for this item // static int this[long i] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(9, 16), // (11,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // get { return 7;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(11, 9), // (12,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // set {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(12, 9) ); ValidateIndexerImplementation_501(compilation1.SourceModule, "Test1"); } [Fact] public void EventImplementation_101() { var source1 = @" public interface I1 { event System.Action E1 { add { System.Console.WriteLine(""add E1""); } } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (4,25): error CS0065: 'I1.E1': event property must have both add and remove accessors // event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 25) }, haveAdd: true, haveRemove: false); } private void ValidateEventImplementation_101(string source1, DiagnosticDescription[] expected, bool haveAdd, bool haveRemove) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics(expected); ValidateEventImplementationTest1_101(compilation1.SourceModule, haveAdd, haveRemove); var source2 = @" class Test2 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate2(ModuleSymbol m) { ValidateEventImplementationTest2_101(m, haveAdd, haveRemove); } Validate2(compilation2.SourceModule); compilation2.VerifyDiagnostics(); Assert.NotEmpty(expected); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); } private static void ValidateEventImplementationTest1_101(ModuleSymbol m, bool haveAdd, bool haveRemove) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var e1 = i1.GetMember<EventSymbol>("E1"); var addE1 = e1.AddMethod; var rmvE1 = e1.RemoveMethod; if (haveAdd) { ValidateAccessor(addE1); } else { Assert.Null(addE1); } if (haveRemove) { ValidateAccessor(rmvE1); } else { Assert.Null(rmvE1); } void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } Assert.False(e1.IsAbstract); Assert.True(e1.IsVirtual); Assert.False(e1.IsSealed); Assert.False(e1.IsStatic); Assert.False(e1.IsExtern); Assert.False(e1.IsOverride); Assert.Equal(Accessibility.Public, e1.DeclaredAccessibility); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); if (m is PEModuleSymbol peModule) { int rva; if (haveAdd) { peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)addE1).Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); } if (haveRemove) { peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)rmvE1).Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); } } var test1 = m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Assert.Same(e1, test1.FindImplementationForInterfaceMember(e1)); if (haveAdd) { Assert.Same(addE1, test1.FindImplementationForInterfaceMember(addE1)); } if (haveRemove) { Assert.Same(rmvE1, test1.FindImplementationForInterfaceMember(rmvE1)); } } private static void ValidateEventImplementationTest2_101(ModuleSymbol m, bool haveAdd, bool haveRemove) { var test2 = m.GlobalNamespace.GetTypeMember("Test2"); Assert.Equal("I1", test2.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); var e1 = test2.InterfacesNoUseSiteDiagnostics().Single().GetMember<EventSymbol>("E1"); Assert.Same(e1, test2.FindImplementationForInterfaceMember(e1)); if (haveAdd) { var addP1 = e1.AddMethod; Assert.Same(addP1, test2.FindImplementationForInterfaceMember(addP1)); } if (haveRemove) { var rmvP1 = e1.RemoveMethod; Assert.Same(rmvP1, test2.FindImplementationForInterfaceMember(rmvP1)); } } [Fact] public void EventImplementation_102() { var source1 = @" public interface I1 { event System.Action E1 { add => System.Console.WriteLine(""add E1""); remove => System.Console.WriteLine(""remove E1""); } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.E1 += null; i1.E1 -= null; } } "; ValidateEventImplementation_102(source1); } private void ValidateEventImplementation_102(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { ValidateEventImplementationTest1_101(m, haveAdd: true, haveRemove: true); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"add E1 remove E1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { I1 i1 = new Test2(); i1.E1 += null; i1.E1 -= null; } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate2(ModuleSymbol m) { ValidateEventImplementationTest2_101(m, haveAdd: true, haveRemove: true); } Validate2(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"add E1 remove E1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate2(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"add E1 remove E1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); } [Fact] public void EventImplementation_103() { var source1 = @" public interface I1 { event System.Action E1 { remove { System.Console.WriteLine(""remove E1""); } } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (4,25): error CS0065: 'I1.E1': event property must have both add and remove accessors // event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 25) }, haveAdd: false, haveRemove: true); } [Fact] public void EventImplementation_104() { var source1 = @" public interface I1 { event System.Action E1 { add; } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (6,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 12), // (4,25): error CS0065: 'I1.E1': event property must have both add and remove accessors // event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 25) }, haveAdd: true, haveRemove: false); } [Fact] public void EventImplementation_105() { var source1 = @" public interface I1 { event System.Action E1 { remove; } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (6,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 15), // (4,25): error CS0065: 'I1.E1': event property must have both add and remove accessors // event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 25) }, haveAdd: false, haveRemove: true); } [Fact] public void EventImplementation_106() { var source1 = @" public interface I1 { event System.Action E1 { } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (4,25): error CS0065: 'I1.E1': event property must have both add and remove accessors // event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 25) }, haveAdd: false, haveRemove: false); } [Fact] public void EventImplementation_107() { var source1 = @" public interface I1 { event System.Action E1 { add; remove; } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (6,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 12), // (7,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(7, 15) }, haveAdd: true, haveRemove: true); } [Fact] public void EventImplementation_108() { var source1 = @" public interface I1 { event System.Action E1 { get; set; } => 0; } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (8,7): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration // } => 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(8, 7), // (6,9): error CS1055: An add or remove accessor expected // get; Diagnostic(ErrorCode.ERR_AddOrRemoveExpected, "get").WithLocation(6, 9), // (7,9): error CS1055: An add or remove accessor expected // set; Diagnostic(ErrorCode.ERR_AddOrRemoveExpected, "set").WithLocation(7, 9), // (4,25): error CS0065: 'I1.E1': event property must have both add and remove accessors // event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1") }, haveAdd: false, haveRemove: false); } [Fact] public void EventImplementation_109() { var source1 = @" public interface I1 { event System.Action E1 { add => throw null; remove; } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (7,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(7, 15) }, haveAdd: true, haveRemove: true); } [Fact] public void EventImplementation_110() { var source1 = @" public interface I1 { event System.Action E1 { add; remove => throw null; } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (6,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 12) }, haveAdd: true, haveRemove: true); } [Fact] public void EventImplementation_201() { var source1 = @" interface I1 { event System.Action E7 { add {System.Console.WriteLine(""add E7"");} remove {System.Console.WriteLine(""remove E7"");} } event System.Action E8 { add {System.Console.WriteLine(""add E8"");} remove {System.Console.WriteLine(""remove E8"");} } } class Base { event System.Action E7; } class Derived : Base, I1 { event System.Action E8 { add {} remove {} } static void Main() { I1 i1 = new Derived(); i1.E7 += null; i1.E7 -= null; i1.E8 += null; i1.E8 -= null; } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (10,25): warning CS0067: The event 'Base.E7' is never used // event System.Action E7; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E7").WithArguments("Base.E7").WithLocation(10, 25) ); ValidateEventImplementation_201(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"add E7 remove E7 add E8 remove E8", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidateEventImplementation_201(m); }); } private static void ValidateEventImplementation_201(ModuleSymbol m) { var e7 = m.GlobalNamespace.GetMember<EventSymbol>("I1.E7"); var e8 = m.GlobalNamespace.GetMember<EventSymbol>("I1.E8"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Same(e7, derived.FindImplementationForInterfaceMember(e7)); Assert.Same(e8, derived.FindImplementationForInterfaceMember(e8)); Assert.Same(e7.AddMethod, derived.FindImplementationForInterfaceMember(e7.AddMethod)); Assert.Same(e8.AddMethod, derived.FindImplementationForInterfaceMember(e8.AddMethod)); Assert.Same(e7.RemoveMethod, derived.FindImplementationForInterfaceMember(e7.RemoveMethod)); Assert.Same(e8.RemoveMethod, derived.FindImplementationForInterfaceMember(e8.RemoveMethod)); } [Fact] public void EventImplementation_202() { var source1 = @" interface I1 { event System.Action E7 { add {System.Console.WriteLine(""add E7"");} remove {System.Console.WriteLine(""remove E7"");} } event System.Action E8 { add {System.Console.WriteLine(""add E8"");} remove {System.Console.WriteLine(""remove E8"");} } } class Base : Test { event System.Action E7; } class Derived : Base, I1 { event System.Action E8 { add {} remove {} } static void Main() { I1 i1 = new Derived(); i1.E7 += null; i1.E7 -= null; i1.E8 += null; i1.E8 -= null; } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (10,25): warning CS0067: The event 'Base.E7' is never used // event System.Action E7; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E7").WithArguments("Base.E7").WithLocation(10, 25) ); ValidateEventImplementation_201(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"add E7 remove E7 add E8 remove E8", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidateEventImplementation_201(m); }); } [Fact] public void EventImplementation_203() { var source1 = @" interface I1 { event System.Action E7 { add {} remove {} } event System.Action E8 { add {} remove {} } } class Base : Test { event System.Action E7; } class Derived : Base, I1 { event System.Action E8 { add {} remove {} } static void Main() { I1 i1 = new Derived(); i1.E7 += null; i1.E7 -= null; i1.E8 += null; i1.E8 -= null; } } class Test : I1 { event System.Action I1.E7 { add {System.Console.WriteLine(""add E7"");} remove {System.Console.WriteLine(""remove E7"");} } event System.Action I1.E8 { add {System.Console.WriteLine(""add E8"");} remove {System.Console.WriteLine(""remove E8"");} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (10,25): warning CS0067: The event 'Base.E7' is never used // event System.Action E7; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E7").WithArguments("Base.E7").WithLocation(10, 25) ); void Validate(ModuleSymbol m) { var e7 = m.GlobalNamespace.GetMember<EventSymbol>("I1.E7"); var e8 = m.GlobalNamespace.GetMember<EventSymbol>("I1.E8"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Equal("event System.Action Test.I1.E7", derived.FindImplementationForInterfaceMember(e7).ToTestDisplayString()); Assert.Equal("event System.Action Test.I1.E8", derived.FindImplementationForInterfaceMember(e8).ToTestDisplayString()); Assert.Equal("void Test.I1.E7.add", derived.FindImplementationForInterfaceMember(e7.AddMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.E8.add", derived.FindImplementationForInterfaceMember(e8.AddMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.E7.remove", derived.FindImplementationForInterfaceMember(e7.RemoveMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.E8.remove", derived.FindImplementationForInterfaceMember(e8.RemoveMethod).ToTestDisplayString()); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"add E7 remove E7 add E8 remove E8", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void EventImplementation_204() { var source1 = @" interface I1 { event System.Action E7 { add {} remove {} } event System.Action E8 { add {} remove {} } } class Base : Test { new event System.Action E7; } class Derived : Base, I1 { new event System.Action E8 { add {} remove {} } static void Main() { I1 i1 = new Derived(); i1.E7 += null; i1.E7 -= null; i1.E8 += null; i1.E8 -= null; } } class Test : I1 { public event System.Action E7 { add {System.Console.WriteLine(""add E7"");} remove {System.Console.WriteLine(""remove E7"");} } public event System.Action E8 { add {System.Console.WriteLine(""add E8"");} remove {System.Console.WriteLine(""remove E8"");} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (10,29): warning CS0067: The event 'Base.E7' is never used // new event System.Action E7; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E7").WithArguments("Base.E7").WithLocation(10, 29) ); void Validate(ModuleSymbol m) { var e7 = m.GlobalNamespace.GetMember<EventSymbol>("I1.E7"); var e8 = m.GlobalNamespace.GetMember<EventSymbol>("I1.E8"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Equal("event System.Action Test.E7", derived.FindImplementationForInterfaceMember(e7).ToTestDisplayString()); Assert.Equal("event System.Action Test.E8", derived.FindImplementationForInterfaceMember(e8).ToTestDisplayString()); Assert.Equal("void Test.E7.add", derived.FindImplementationForInterfaceMember(e7.AddMethod).ToTestDisplayString()); Assert.Equal("void Test.E8.add", derived.FindImplementationForInterfaceMember(e8.AddMethod).ToTestDisplayString()); Assert.Equal("void Test.E7.remove", derived.FindImplementationForInterfaceMember(e7.RemoveMethod).ToTestDisplayString()); Assert.Equal("void Test.E8.remove", derived.FindImplementationForInterfaceMember(e8.RemoveMethod).ToTestDisplayString()); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"add E7 remove E7 add E8 remove E8", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void EventImplementation_501() { var source1 = @" public interface I1 { event System.Action E7 { add {} remove {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (6,9): error CS8501: Target runtime doesn't support default interface implementation. // add {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(6, 9), // (7,9): error CS8501: Target runtime doesn't support default interface implementation. // remove {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(7, 9) ); ValidateEventImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.E7.remove' cannot implement interface member 'I1.E7.remove' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.remove", "I1.E7.remove", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.E7.add' cannot implement interface member 'I1.E7.add' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.add", "I1.E7.add", "Test2").WithLocation(2, 15) ); ValidateEventImplementation_501(compilation3.SourceModule, "Test2"); } private static void ValidateEventImplementation_501(ModuleSymbol m, string typeName) { var derived = m.GlobalNamespace.GetTypeMember(typeName); var i1 = derived.InterfacesNoUseSiteDiagnostics().Single(); Assert.Equal("I1", i1.ToTestDisplayString()); var e7 = i1.GetMember<EventSymbol>("E7"); Assert.True(e7.IsVirtual); Assert.False(e7.IsAbstract); Assert.Same(e7, derived.FindImplementationForInterfaceMember(e7)); Assert.True(e7.AddMethod.IsVirtual); Assert.True(e7.RemoveMethod.IsVirtual); Assert.True(e7.AddMethod.IsMetadataVirtual()); Assert.True(e7.RemoveMethod.IsMetadataVirtual()); Assert.False(e7.AddMethod.IsAbstract); Assert.False(e7.RemoveMethod.IsAbstract); Assert.Same(e7.AddMethod, derived.FindImplementationForInterfaceMember(e7.AddMethod)); Assert.Same(e7.RemoveMethod, derived.FindImplementationForInterfaceMember(e7.RemoveMethod)); } [Fact] public void EventImplementation_502() { var source1 = @" public interface I1 { event System.Action E7 { add {} remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, targetFramework: TargetFramework.DesktopLatestExtended, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.E7.remove' cannot implement interface member 'I1.E7.remove' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.remove", "I1.E7.remove", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.E7.add' cannot implement interface member 'I1.E7.add' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.add", "I1.E7.add", "Test2").WithLocation(2, 15) ); ValidateEventImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void EventImplementation_503() { var source1 = @" public interface I1 { event System.Action E7 { add {} remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" public interface I2 { void M2(); } class Test2 : I2 { public void M2() {} } "; var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var test2 = compilation3.GetTypeByMetadataName("Test2"); var i1 = compilation3.GetTypeByMetadataName("I1"); Assert.Equal("I1", i1.ToTestDisplayString()); var e7 = i1.GetMember<EventSymbol>("E7"); Assert.Null(test2.FindImplementationForInterfaceMember(e7)); Assert.Null(test2.FindImplementationForInterfaceMember(e7.AddMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(e7.RemoveMethod)); compilation3.VerifyDiagnostics(); } [Fact] public void EventImplementation_601() { var source1 = @" public interface I1 { event System.Action E7 { add {} remove {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (6,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // add {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(6, 9), // (6,9): error CS8701: Target runtime doesn't support default interface implementation. // add {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(6, 9), // (7,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // remove {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(7, 9), // (7,9): error CS8701: Target runtime doesn't support default interface implementation. // remove {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(7, 9) ); ValidateEventImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.E7.remove' cannot implement interface member 'I1.E7.remove' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.remove", "I1.E7.remove", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.E7.remove' cannot implement interface member 'I1.E7.remove' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.remove", "I1.E7.remove", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.E7.add' cannot implement interface member 'I1.E7.add' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.add", "I1.E7.add", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.E7.add' cannot implement interface member 'I1.E7.add' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.add", "I1.E7.add", "Test2").WithLocation(2, 15) ); ValidateEventImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void EventImplementation_701() { var source1 = @" public interface I1 { event System.Action E7 { add {} remove {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (6,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // add {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(6, 9), // (7,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // remove {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(7, 9) ); ValidateEventImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateEventImplementation_501(compilation2.SourceModule, "Test2"); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test2Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test2"); Assert.Equal("I1", test2Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidateEventImplementation_501(m, "Test2"); }); var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.E7.remove' cannot implement interface member 'I1.E7.remove' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.remove", "I1.E7.remove", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.E7.add' cannot implement interface member 'I1.E7.add' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.add", "I1.E7.add", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15) ); ValidateEventImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void EventImplementation_901() { var source1 = @" public interface I1 { static event System.Action E7 { add {} remove {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static event System.Action E7 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "E7").WithArguments("default interface implementation", "8.0").WithLocation(4, 32) ); var derived = compilation1.GlobalNamespace.GetTypeMember("Test1"); var i1 = derived.InterfacesNoUseSiteDiagnostics().Single(); Assert.Equal("I1", i1.ToTestDisplayString()); var e7 = i1.GetMember<EventSymbol>("E7"); Assert.False(e7.IsVirtual); Assert.False(e7.IsAbstract); Assert.True(e7.IsStatic); Assert.Null(derived.FindImplementationForInterfaceMember(e7)); Assert.False(e7.AddMethod.IsVirtual); Assert.False(e7.RemoveMethod.IsVirtual); Assert.False(e7.AddMethod.IsMetadataVirtual()); Assert.False(e7.RemoveMethod.IsMetadataVirtual()); Assert.False(e7.AddMethod.IsAbstract); Assert.False(e7.RemoveMethod.IsAbstract); Assert.True(e7.AddMethod.IsStatic); Assert.True(e7.RemoveMethod.IsStatic); Assert.Null(derived.FindImplementationForInterfaceMember(e7.AddMethod)); Assert.Null(derived.FindImplementationForInterfaceMember(e7.RemoveMethod)); } [Fact] public void BaseIsNotAllowed_01() { var source1 = @" public interface I1 { void M1() { base.GetHashCode(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (6,9): error CS0174: A base class is required for a 'base' reference // base.GetHashCode(); Diagnostic(ErrorCode.ERR_NoBaseClass, "base").WithLocation(6, 9) ); } [Fact] public void ThisIsAllowed_01() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""I1.M1""); } int P1 { get { System.Console.WriteLine(""I1.get_P1""); return 0; } set => System.Console.WriteLine(""I1.set_P1""); } event System.Action E1 { add => System.Console.WriteLine(""I1.add_E1""); remove => System.Console.WriteLine(""I1.remove_E1""); } } public interface I2 : I1 { void M2() { System.Console.WriteLine(""I2.M2""); System.Console.WriteLine(this.GetHashCode()); this.M1(); this.P1 = this.P1; this.E1 += null; this.E1 -= null; this.M3(); this.P3 = this.P3; this.E3 += null; this.E3 -= null; } int P2 { get { System.Console.WriteLine(""I2.get_P2""); System.Console.WriteLine(this.GetHashCode()); this.M1(); this.P1 = this.P1; this.E1 += null; this.E1 -= null; this.M3(); this.P3 = this.P3; this.E3 += null; this.E3 -= null; return 0; } set { System.Console.WriteLine(""I2.set_P2""); System.Console.WriteLine(this.GetHashCode()); this.M1(); this.P1 = this.P1; this.E1 += null; this.E1 -= null; this.M3(); this.P3 = this.P3; this.E3 += null; this.E3 -= null; } } event System.Action E2 { add { System.Console.WriteLine(""I2.add_E2""); System.Console.WriteLine(this.GetHashCode()); this.M1(); this.P1 = this.P1; this.E1 += null; this.E1 -= null; this.M3(); this.P3 = this.P3; this.E3 += null; this.E3 -= null; } remove { System.Console.WriteLine(""I2.remove_E2""); System.Console.WriteLine(this.GetHashCode()); this.M1(); this.P1 = this.P1; this.E1 += null; this.E1 -= null; this.M3(); this.P3 = this.P3; this.E3 += null; this.E3 -= null; } } void M3() { System.Console.WriteLine(""I2.M3""); } int P3 { get { System.Console.WriteLine(""I2.get_P3""); return 0; } set => System.Console.WriteLine(""I2.set_P3""); } event System.Action E3 { add => System.Console.WriteLine(""I2.add_E3""); remove => System.Console.WriteLine(""I2.remove_E3""); } } class Test1 : I2 { static void Main() { I2 x = new Test1(); x.M2(); x.P2 = x.P2; x.E2 += null; x.E2 -= null; } public override int GetHashCode() { return 123; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.get_P2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.set_P2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.add_E2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.remove_E2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 ", verify: VerifyOnMonoOrCoreClr); } [Fact] public void ThisIsAllowed_02() { var source1 = @" public interface I1 { public int F1; } public interface I2 : I1 { void M2() { this.F1 = this.F2; } int P2 { get { this.F1 = this.F2; return 0; } set { this.F1 = this.F2; } } event System.Action E2 { add { this.F1 = this.F2; } remove { this.F1 = this.F2; } } public int F2; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,16): error CS0525: Interfaces cannot contain fields // public int F1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F1").WithLocation(4, 16), // (39,16): error CS0525: Interfaces cannot contain fields // public int F2; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F2").WithLocation(39, 16) ); } [Fact] public void ImplicitThisIsAllowed_01() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""I1.M1""); } int P1 { get { System.Console.WriteLine(""I1.get_P1""); return 0; } set => System.Console.WriteLine(""I1.set_P1""); } event System.Action E1 { add => System.Console.WriteLine(""I1.add_E1""); remove => System.Console.WriteLine(""I1.remove_E1""); } } public interface I2 : I1 { void M2() { System.Console.WriteLine(""I2.M2""); System.Console.WriteLine(GetHashCode()); M1(); P1 = P1; E1 += null; E1 -= null; M3(); P3 = P3; E3 += null; E3 -= null; } int P2 { get { System.Console.WriteLine(""I2.get_P2""); System.Console.WriteLine(GetHashCode()); M1(); P1 = P1; E1 += null; E1 -= null; M3(); P3 = P3; E3 += null; E3 -= null; return 0; } set { System.Console.WriteLine(""I2.set_P2""); System.Console.WriteLine(GetHashCode()); M1(); P1 = P1; E1 += null; E1 -= null; M3(); P3 = P3; E3 += null; E3 -= null; } } event System.Action E2 { add { System.Console.WriteLine(""I2.add_E2""); System.Console.WriteLine(GetHashCode()); M1(); P1 = P1; E1 += null; E1 -= null; M3(); P3 = P3; E3 += null; E3 -= null; } remove { System.Console.WriteLine(""I2.remove_E2""); System.Console.WriteLine(GetHashCode()); M1(); P1 = P1; E1 += null; E1 -= null; M3(); P3 = P3; E3 += null; E3 -= null; } } void M3() { System.Console.WriteLine(""I2.M3""); } int P3 { get { System.Console.WriteLine(""I2.get_P3""); return 0; } set => System.Console.WriteLine(""I2.set_P3""); } event System.Action E3 { add => System.Console.WriteLine(""I2.add_E3""); remove => System.Console.WriteLine(""I2.remove_E3""); } } class Test1 : I2 { static void Main() { I2 x = new Test1(); x.M2(); x.P2 = x.P2; x.E2 += null; x.E2 -= null; } public override int GetHashCode() { return 123; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.get_P2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.set_P2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.add_E2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.remove_E2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 ", verify: VerifyOnMonoOrCoreClr); } [Fact] public void ImplicitThisIsAllowed_02() { var source1 = @" public interface I1 { public int F1; } public interface I2 : I1 { void M2() { F1 = F2; } int P2 { get { F1 = F2; return 0; } set { F1 = F2; } } event System.Action E2 { add { F1 = F2; } remove { F1 = F2; } } public int F2; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,16): error CS0525: Interfaces cannot contain fields // public int F1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F1").WithLocation(4, 16), // (39,16): error CS0525: Interfaces cannot contain fields // public int F2; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F2").WithLocation(39, 16) ); } [Fact] public void MethodModifiers_01() { var source1 = @" public interface I1 { public void M01(); protected void M02(); protected internal void M03(); internal void M04(); private void M05(); static void M06(); virtual void M07(); sealed void M08(); override void M09(); abstract void M10(); extern void M11(); async void M12(); private protected void M13(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (12,19): error CS0106: The modifier 'override' is not valid for this item // override void M09(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(12, 19), // (15,16): error CS1994: The 'async' modifier can only be used in methods that have a body. // async void M12(); Diagnostic(ErrorCode.ERR_BadAsyncLacksBody, "M12").WithLocation(15, 16), // (8,18): error CS0501: 'I1.M05()' must declare a body because it is not marked abstract, extern, or partial // private void M05(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M05").WithArguments("I1.M05()").WithLocation(8, 18), // (9,17): error CS0501: 'I1.M06()' must declare a body because it is not marked abstract, extern, or partial // static void M06(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M06").WithArguments("I1.M06()").WithLocation(9, 17), // (10,18): error CS0501: 'I1.M07()' must declare a body because it is not marked abstract, extern, or partial // virtual void M07(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M07").WithArguments("I1.M07()").WithLocation(10, 18), // (11,17): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // sealed void M08(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(11, 17), // (14,17): warning CS0626: Method, operator, or accessor 'I1.M11()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void M11(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M11").WithArguments("I1.M11()").WithLocation(14, 17) ); ValidateSymbolsMethodModifiers_01(compilation1); } private static void ValidateSymbolsMethodModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.False(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Equal(Accessibility.Public, m01.DeclaredAccessibility); var m02 = i1.GetMember<MethodSymbol>("M02"); Assert.True(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.True(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.False(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Equal(Accessibility.Protected, m02.DeclaredAccessibility); var m03 = i1.GetMember<MethodSymbol>("M03"); Assert.True(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.True(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.False(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, m03.DeclaredAccessibility); var m04 = i1.GetMember<MethodSymbol>("M04"); Assert.True(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.True(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.False(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Equal(Accessibility.Internal, m04.DeclaredAccessibility); var m05 = i1.GetMember<MethodSymbol>("M05"); Assert.False(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.False(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.False(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Equal(Accessibility.Private, m05.DeclaredAccessibility); var m06 = i1.GetMember<MethodSymbol>("M06"); Assert.False(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.False(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Equal(Accessibility.Public, m06.DeclaredAccessibility); var m07 = i1.GetMember<MethodSymbol>("M07"); Assert.False(m07.IsAbstract); Assert.True(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.False(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Equal(Accessibility.Public, m07.DeclaredAccessibility); var m08 = i1.GetMember<MethodSymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.False(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Equal(Accessibility.Public, m08.DeclaredAccessibility); var m09 = i1.GetMember<MethodSymbol>("M09"); Assert.True(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.True(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.False(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Equal(Accessibility.Public, m09.DeclaredAccessibility); var m10 = i1.GetMember<MethodSymbol>("M10"); Assert.True(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.True(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.False(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Equal(Accessibility.Public, m10.DeclaredAccessibility); var m11 = i1.GetMember<MethodSymbol>("M11"); Assert.False(m11.IsAbstract); Assert.True(m11.IsVirtual); Assert.True(m11.IsMetadataVirtual()); Assert.False(m11.IsSealed); Assert.False(m11.IsStatic); Assert.True(m11.IsExtern); Assert.False(m11.IsAsync); Assert.False(m11.IsOverride); Assert.Equal(Accessibility.Public, m11.DeclaredAccessibility); var m12 = i1.GetMember<MethodSymbol>("M12"); Assert.True(m12.IsAbstract); Assert.False(m12.IsVirtual); Assert.True(m12.IsMetadataVirtual()); Assert.False(m12.IsSealed); Assert.False(m12.IsStatic); Assert.False(m12.IsExtern); Assert.True(m12.IsAsync); Assert.False(m12.IsOverride); Assert.Equal(Accessibility.Public, m12.DeclaredAccessibility); var m13 = i1.GetMember<MethodSymbol>("M13"); Assert.True(m13.IsAbstract); Assert.False(m13.IsVirtual); Assert.True(m13.IsMetadataVirtual()); Assert.False(m13.IsSealed); Assert.False(m13.IsStatic); Assert.False(m13.IsExtern); Assert.False(m13.IsAsync); Assert.False(m13.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, m13.DeclaredAccessibility); } [Fact] public void MethodModifiers_02() { var source1 = @" public interface I1 { public void M01(); protected void M02(); protected internal void M03(); internal void M04(); private void M05(); static void M06(); virtual void M07(); sealed void M08(); override void M09(); abstract void M10(); extern void M11(); async void M12(); private protected void M13(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,17): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("public", "7.3", "8.0").WithLocation(4, 17), // (5,20): error CS8703: The modifier 'protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // protected void M02(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("protected", "7.3", "8.0").WithLocation(5, 20), // (6,29): error CS8703: The modifier 'protected internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // protected internal void M03(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("protected internal", "7.3", "8.0").WithLocation(6, 29), // (7,19): error CS8503: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal void M04(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("internal", "7.3", "8.0").WithLocation(7, 19), // (8,18): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private void M05(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("private", "7.3", "8.0").WithLocation(8, 18), // (9,17): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static void M06(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("static", "7.3", "8.0").WithLocation(9, 17), // (10,18): error CS8503: The modifier 'virtual' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual void M07(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("virtual", "7.3", "8.0").WithLocation(10, 18), // (11,17): error CS8503: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // sealed void M08(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "8.0").WithLocation(11, 17), // (12,19): error CS0106: The modifier 'override' is not valid for this item // override void M09(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(12, 19), // (13,19): error CS8503: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // abstract void M10(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("abstract", "7.3", "8.0").WithLocation(13, 19), // (14,17): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern void M11(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M11").WithArguments("extern", "7.3", "8.0").WithLocation(14, 17), // (15,16): error CS8503: The modifier 'async' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // async void M12(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M12").WithArguments("async", "7.3", "8.0").WithLocation(15, 16), // (15,16): error CS1994: The 'async' modifier can only be used in methods that have a body. // async void M12(); Diagnostic(ErrorCode.ERR_BadAsyncLacksBody, "M12").WithLocation(15, 16), // (8,18): error CS0501: 'I1.M05()' must declare a body because it is not marked abstract, extern, or partial // private void M05(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M05").WithArguments("I1.M05()").WithLocation(8, 18), // (9,17): error CS0501: 'I1.M06()' must declare a body because it is not marked abstract, extern, or partial // static void M06(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M06").WithArguments("I1.M06()").WithLocation(9, 17), // (10,18): error CS0501: 'I1.M07()' must declare a body because it is not marked abstract, extern, or partial // virtual void M07(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M07").WithArguments("I1.M07()").WithLocation(10, 18), // (11,17): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // sealed void M08(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(11, 17), // (14,17): warning CS0626: Method, operator, or accessor 'I1.M11()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void M11(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M11").WithArguments("I1.M11()").WithLocation(14, 17), // (16,28): error CS8703: The modifier 'private protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private protected void M13(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M13").WithArguments("private protected", "7.3", "8.0").WithLocation(16, 28) ); ValidateSymbolsMethodModifiers_01(compilation1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (5,20): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected void M02(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "M02").WithLocation(5, 20), // (6,29): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal void M03(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "M03").WithLocation(6, 29), // (8,18): error CS0501: 'I1.M05()' must declare a body because it is not marked abstract, extern, or partial // private void M05(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M05").WithArguments("I1.M05()").WithLocation(8, 18), // (9,17): error CS0501: 'I1.M06()' must declare a body because it is not marked abstract, extern, or partial // static void M06(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M06").WithArguments("I1.M06()").WithLocation(9, 17), // (10,18): error CS0501: 'I1.M07()' must declare a body because it is not marked abstract, extern, or partial // virtual void M07(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M07").WithArguments("I1.M07()").WithLocation(10, 18), // (11,17): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // sealed void M08(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(11, 17), // (12,19): error CS0106: The modifier 'override' is not valid for this item // override void M09(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(12, 19), // (14,17): error CS8701: Target runtime doesn't support default interface implementation. // extern void M11(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M11").WithLocation(14, 17), // (14,17): warning CS0626: Method, operator, or accessor 'I1.M11()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void M11(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M11").WithArguments("I1.M11()").WithLocation(14, 17), // (15,16): error CS1994: The 'async' modifier can only be used in methods that have a body. // async void M12(); Diagnostic(ErrorCode.ERR_BadAsyncLacksBody, "M12").WithLocation(15, 16), // (16,28): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected void M13(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "M13").WithLocation(16, 28) ); ValidateSymbolsMethodModifiers_01(compilation2); } [Fact] [WorkItem(33083, "https://github.com/dotnet/roslyn/issues/33083")] public void MethodModifiers_03() { var source1 = @" public interface I1 { public virtual void M1() { System.Console.WriteLine(""M1""); } } "; ValidateMethodImplementation_011(source1); } [Fact] public void MethodModifiers_04() { var source1 = @" public interface I1 { public abstract void M1(); void M2(); } class Test1 : I1 { public void M1() { System.Console.WriteLine(""M1""); } public void M2() { System.Console.WriteLine(""M2""); } static void Main() { I1 x = new Test1(); x.M1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: @"M1 M2", symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); foreach (var methodName in new[] { "M1", "M2" }) { var m1 = i1.GetMember<MethodSymbol>(methodName); Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Same(test1.GetMember(methodName), test1.FindImplementationForInterfaceMember(m1)); } } } [Fact] public void MethodModifiers_05() { var source1 = @" public interface I1 { public abstract void M1(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3); compilation1.VerifyDiagnostics( // (4,26): error CS8503: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract void M1(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M1").WithArguments("abstract", "7.3", "8.0").WithLocation(4, 26), // (4,26): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract void M1(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M1").WithArguments("public", "7.3", "8.0").WithLocation(4, 26) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); } [Fact] public void MethodModifiers_06() { var source1 = @" public interface I1 { public static void M1() { System.Console.WriteLine(""M1""); } internal static void M2() { System.Console.WriteLine(""M2""); M3(); } private static void M3() { System.Console.WriteLine(""M3""); } } class Test1 : I1 { static void Main() { I1.M1(); I1.M2(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2 M3", symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); foreach (var tuple in new[] { (name: "M1", access: Accessibility.Public), (name: "M2", access: Accessibility.Internal), (name: "M3", access: Accessibility.Private) }) { var m1 = i1.GetMember<MethodSymbol>(tuple.name); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.True(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(tuple.access, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); } } } [Fact] public void MethodModifiers_07() { var source1 = @" public interface I1 { abstract static void M1(); virtual static void M2() { } sealed static void M3() { } static void M4() { } } class Test1 : I1 { void I1.M4() {} void I1.M1() {} void I1.M2() {} void I1.M3() {} } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static void M3() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M3").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (6,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M2() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M2").WithArguments("virtual").WithLocation(6, 25), // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M1(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M1").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (21,13): error CS0539: 'Test1.M4()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M4() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M4").WithArguments("Test1.M4()").WithLocation(21, 13), // (22,13): error CS0539: 'Test1.M1()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M1() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M1").WithArguments("Test1.M1()").WithLocation(22, 13), // (23,13): error CS0539: 'Test1.M2()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M2() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M2").WithArguments("Test1.M2()").WithLocation(23, 13), // (24,13): error CS0539: 'Test1.M3()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M3() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M3").WithArguments("Test1.M3()").WithLocation(24, 13), // (19,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M1()").WithLocation(19, 15), // (27,15): error CS0535: 'Test2' does not implement interface member 'I1.M1()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M1()").WithLocation(27, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.True(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.False(m2.IsAbstract); Assert.False(m2.IsVirtual); Assert.False(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.True(m2.IsStatic); Assert.False(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m2)); var m3 = i1.GetMember<MethodSymbol>("M3"); Assert.False(m3.IsAbstract); Assert.False(m3.IsVirtual); Assert.False(m3.IsMetadataVirtual()); Assert.False(m3.IsSealed); Assert.True(m3.IsStatic); Assert.False(m3.IsExtern); Assert.False(m3.IsAsync); Assert.False(m3.IsOverride); Assert.Equal(Accessibility.Public, m3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m3)); } [Fact] public void MethodModifiers_08() { var source1 = @" public interface I1 { private void M1() { System.Console.WriteLine(""M1""); } void M4() { System.Console.WriteLine(""M4""); M1(); } } class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M4(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M4 M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); } } [Fact] public void MethodModifiers_09() { var source1 = @" public interface I1 { abstract private void M1(); virtual private void M2() { } sealed private void M3() { } } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (10,25): error CS0238: 'I1.M3()' cannot be sealed because it is not an override // sealed private void M3() Diagnostic(ErrorCode.ERR_SealedNonOverride, "M3").WithArguments("I1.M3()").WithLocation(10, 25), // (6,26): error CS0621: 'I1.M2()': virtual or abstract members cannot be private // virtual private void M2() Diagnostic(ErrorCode.ERR_VirtualPrivate, "M2").WithArguments("I1.M2()").WithLocation(6, 26), // (4,27): error CS0621: 'I1.M1()': virtual or abstract members cannot be private // abstract private void M1(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "M1").WithArguments("I1.M1()").WithLocation(4, 27), // (15,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M1()").WithLocation(15, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.False(m2.IsAbstract); Assert.True(m2.IsVirtual); Assert.True(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.False(m2.IsStatic); Assert.False(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility); Assert.Same(m2, test1.FindImplementationForInterfaceMember(m2)); var m3 = i1.GetMember<MethodSymbol>("M3"); Assert.False(m3.IsAbstract); Assert.False(m3.IsVirtual); Assert.False(m3.IsMetadataVirtual()); Assert.True(m3.IsSealed); Assert.False(m3.IsStatic); Assert.False(m3.IsExtern); Assert.False(m3.IsAsync); Assert.False(m3.IsOverride); Assert.Equal(Accessibility.Private, m3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m3)); } [Fact] public void MethodModifiers_10_01() { var source1 = @" public interface I1 { internal abstract void M1(); void M2() {M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (9,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(9, 15) ); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.Internal); compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.Internal)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.Internal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.Internal); var source3 = @" class Test2 : I1 { } "; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 15) ); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.Internal); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.Internal)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.Internal); var compilation5 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.M1()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M1()").WithLocation(2, 15) ); ValidateI1M1NotImplemented(compilation5, "Test2"); } } private static void ValidateI1M1NotImplemented(CSharpCompilation compilation, string className) { var test2 = compilation.GetTypeByMetadataName(className); var i1 = compilation.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.Null(test2.FindImplementationForInterfaceMember(m1)); } private static void ValidateMethodModifiersImplicit_10(ModuleSymbol m, Accessibility accessibility) { ValidateMethodModifiers_10(m, implementedByBase: false, isExplicit: false, accessibility); } private static void ValidateMethodModifiersExplicit_10(ModuleSymbol m, Accessibility accessibility) { ValidateMethodModifiers_10(m, implementedByBase: false, isExplicit: true, accessibility); } private static void ValidateMethodModifiersImplicitInTest2_10(ModuleSymbol m, Accessibility accessibility) { ValidateMethodModifiers_10(m, implementedByBase: true, isExplicit: false, accessibility); } private static void ValidateMethodModifiersExplicitInTest2_10(ModuleSymbol m, Accessibility accessibility) { ValidateMethodModifiers_10(m, implementedByBase: true, isExplicit: true, accessibility); } private static void ValidateMethodModifiers_10(ModuleSymbol m, bool implementedByBase, bool isExplicit, Accessibility accessibility) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var m1 = i1.GetMember<MethodSymbol>("M1"); ValidateMethodModifiers_10(m1, accessibility); var implementation = (implementedByBase ? test1.BaseTypeNoUseSiteDiagnostics : test1).GetMember<MethodSymbol>((isExplicit ? "I1." : "") + "M1"); Assert.NotNull(implementation); Assert.Same(implementation, test1.FindImplementationForInterfaceMember(m1)); Assert.True(implementation.IsMetadataVirtual()); } private static void ValidateMethodModifiers_10(MethodSymbol m1, Accessibility accessibility) { Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(accessibility, m1.DeclaredAccessibility); } [Fact] public void MethodModifiers_10_02() { var source1 = @" public interface I1 { internal abstract void M1(); } public class TestHelper { public static void CallM1(I1 x) {x.M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallM1(new Test1()); } public virtual void M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.Internal, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 15) ); } private void ValidateMethodModifiers_10_02(string source1, string source2, Accessibility accessibility, params DiagnosticDescription[] expectedIn9) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expectedIn9); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, accessibility); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "Test1.M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, accessibility)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, accessibility); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), accessibility); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expectedIn9); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, accessibility); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "Test1.M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, accessibility)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, accessibility); } } [Fact] public void MethodModifiers_10_03() { var source1 = @" public interface I1 { internal abstract void M1(); } public class TestHelper { public static void CallM1(I1 x) {x.M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallM1(new Test1()); } void I1.M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersExplicit_10(m, Accessibility.Internal)); ValidateMethodModifiersExplicit_10(compilation1.SourceModule, Accessibility.Internal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.Internal); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation3.VerifyDiagnostics( // (9,13): error CS0122: 'I1.M1()' is inaccessible due to its protection level // void I1.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.M1()").WithLocation(9, 13) ); ValidateMethodModifiersExplicit_10(compilation3.SourceModule, Accessibility.Internal); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation4.VerifyDiagnostics( // (9,13): error CS0122: 'I1.M1()' is inaccessible due to its protection level // void I1.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.M1()").WithLocation(9, 13) ); ValidateMethodModifiersExplicit_10(compilation4.SourceModule, Accessibility.Internal); } [Fact] public void MethodModifiers_10_04() { var source1 = @" public interface I1 { internal abstract void M1(); } public class TestHelper { public static void CallM1(I1 x) {x.M1();} } public class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2.M1""); } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallM1(new Test1()); } public void M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.Internal, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void MethodModifiers_10_05() { var source1 = @" public interface I1 { internal abstract void M1(); } public class TestHelper { public static void CallM1(I1 x) {x.M1();} } public class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2.M1""); } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallM1(new Test1()); } public virtual void M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.Internal, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void MethodModifiers_10_06() { var source1 = @" public interface I1 { internal abstract void M1(); } public class TestHelper { public static void CallM1(I1 x) {x.M1();} } public class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2.M1""); } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallM1(new Test3()); } public abstract void M1(); } class Test3 : Test1 { public override void M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.Internal, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void MethodModifiers_10_07() { var source1 = @" public interface I1 { internal abstract void M1(); } public class TestHelper { public static void CallM1(I1 x) {x.M1();} } public class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2.M1""); } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallM1(new Test1()); } public void M1() { System.Console.WriteLine(""Test1.M1""); } } public interface I2 { void M1(); } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.Internal, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void MethodModifiers_10_08() { var source1 = @" public interface I1 { internal abstract void M1(); } public class TestHelper { public static void CallM1(I1 x) {x.M1();} } public class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2.M1""); } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallM1(new Test1()); } public virtual int M1() { System.Console.WriteLine(""Test1.M1""); return 0; } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: "Test2.M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersExplicitInTest2_10(m, Accessibility.Internal)); ValidateMethodModifiersExplicitInTest2_10(compilation1.SourceModule, Accessibility.Internal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.Internal); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation3, expectedOutput: "Test2.M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersExplicitInTest2_10(m, Accessibility.Internal)); ValidateMethodModifiersExplicitInTest2_10(compilation3.SourceModule, Accessibility.Internal); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation4, expectedOutput: "Test2.M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersExplicitInTest2_10(m, Accessibility.Internal)); ValidateMethodModifiersExplicitInTest2_10(compilation4.SourceModule, Accessibility.Internal); } [Fact] public void MethodModifiers_10_09() { var source1 = @" public interface I1 { internal abstract void M1(); void M2() {M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public virtual int M1() { System.Console.WriteLine(""M1""); return 0; } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (9,15): error CS0738: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implement 'I1.M1()' because it does not have the matching return type of 'void'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "void").WithLocation(9, 15) ); ValidateI1M1NotImplemented(compilation1, "Test1"); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.Internal); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implement 'I1.M1()' because it does not have the matching return type of 'void'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "void").WithLocation(2, 15) ); ValidateI1M1NotImplemented(compilation3, "Test1"); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics( // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implement 'I1.M1()' because it does not have the matching return type of 'void'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "void").WithLocation(2, 15) ); ValidateI1M1NotImplemented(compilation4, "Test1"); } [Fact] public void MethodModifiers_10_10() { var source1 = @" public interface I1 { internal abstract void M1(); void M2() {M1();} } "; var source2 = @" class Test2 : I1 { public void M1() { System.Console.WriteLine(""M1""); } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,15): error CS8704: 'Test2' does not implement interface member 'I1.M1()'. 'Test2.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.M1()", "Test2.M1()", "9.0", "10.0").WithLocation(9, 15) ); ValidateMethodModifiersImplicitInTest2_10(compilation1.SourceModule, Accessibility.Internal); compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicitInTest2_10(m, Accessibility.Internal)).VerifyDiagnostics(); ValidateMethodModifiersImplicitInTest2_10(compilation1.SourceModule, Accessibility.Internal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.Internal); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (2,15): error CS8704: 'Test2' does not implement interface member 'I1.M1()'. 'Test2.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.M1()", "Test2.M1()", "9.0", "10.0").WithLocation(2, 15) ); ValidateMethodModifiersImplicitInTest2_10(compilation3.SourceModule, Accessibility.Internal); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicitInTest2_10(m, Accessibility.Internal)).VerifyDiagnostics(); ValidateMethodModifiersImplicitInTest2_10(compilation3.SourceModule, Accessibility.Internal); } } [Fact] public void MethodModifiers_10_11() { var source1 = @" public interface I1 { internal abstract void M1(); void M2() {M1();} } public class Test2 : I1 { public void M1() { System.Console.WriteLine(""M1""); } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp, assemblyName: "MethodModifiers_10_11"); compilation2.VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicitInTest2_10(m, Accessibility.Internal)).VerifyDiagnostics(); ValidateMethodModifiersImplicitInTest2_10(compilation3.SourceModule, Accessibility.Internal); compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicitInTest2_10(m, Accessibility.Internal)).VerifyDiagnostics(); ValidateMethodModifiersImplicitInTest2_10(compilation3.SourceModule, Accessibility.Internal); } [Fact] public void MethodModifiers_11() { var source1 = @" public interface I1 { internal abstract void M1(); } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M1()").WithLocation(7, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Internal, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); } [Fact] public void MethodModifiers_12() { var source1 = @" public interface I1 { public sealed void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M1(); } public void M1() { System.Console.WriteLine(""Test1.M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); } CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); } [Fact] public void MethodModifiers_13() { var source1 = @" public interface I1 { public sealed void M1() { System.Console.WriteLine(""M1""); } abstract sealed void M2(); virtual sealed void M3() { } public sealed void M4(); } class Test1 : I1 { void I1.M1() {} void I1.M2() {} void I1.M3() {} void I1.M4() {} } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (15,24): error CS0501: 'I1.M4()' must declare a body because it is not marked abstract, extern, or partial // public sealed void M4(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M4").WithArguments("I1.M4()").WithLocation(15, 24), // (9,26): error CS0238: 'I1.M2()' cannot be sealed because it is not an override // abstract sealed void M2(); Diagnostic(ErrorCode.ERR_SealedNonOverride, "M2").WithArguments("I1.M2()").WithLocation(9, 26), // (11,25): error CS0238: 'I1.M3()' cannot be sealed because it is not an override // virtual sealed void M3() Diagnostic(ErrorCode.ERR_SealedNonOverride, "M3").WithArguments("I1.M3()").WithLocation(11, 25), // (23,13): error CS0539: 'Test1.M4()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M4() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M4").WithArguments("Test1.M4()").WithLocation(23, 13), // (20,13): error CS0539: 'Test1.M1()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M1() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M1").WithArguments("Test1.M1()").WithLocation(20, 13), // (21,13): error CS0539: 'Test1.M2()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M2() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M2").WithArguments("Test1.M2()").WithLocation(21, 13), // (22,13): error CS0539: 'Test1.M3()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M3() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M3").WithArguments("Test1.M3()").WithLocation(22, 13) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); Assert.Null(test2.FindImplementationForInterfaceMember(m1)); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.True(m2.IsAbstract); Assert.False(m2.IsVirtual); Assert.True(m2.IsMetadataVirtual()); Assert.True(m2.IsSealed); Assert.False(m2.IsStatic); Assert.False(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m2)); Assert.Null(test2.FindImplementationForInterfaceMember(m2)); var m3 = i1.GetMember<MethodSymbol>("M3"); Assert.False(m3.IsAbstract); Assert.True(m3.IsVirtual); Assert.True(m3.IsMetadataVirtual()); Assert.True(m3.IsSealed); Assert.False(m3.IsStatic); Assert.False(m3.IsExtern); Assert.False(m3.IsAsync); Assert.False(m3.IsOverride); Assert.Equal(Accessibility.Public, m3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m3)); Assert.Null(test2.FindImplementationForInterfaceMember(m3)); var m4 = i1.GetMember<MethodSymbol>("M4"); Assert.False(m4.IsAbstract); Assert.False(m4.IsVirtual); Assert.False(m4.IsMetadataVirtual()); Assert.False(m4.IsSealed); Assert.False(m4.IsStatic); Assert.False(m4.IsExtern); Assert.False(m4.IsAsync); Assert.False(m4.IsOverride); Assert.Equal(Accessibility.Public, m4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m4)); Assert.Null(test2.FindImplementationForInterfaceMember(m4)); } [Fact] public void MethodModifiers_14() { var source1 = @" public interface I1 { abstract virtual void M2(); virtual abstract void M3() { } } class Test1 : I1 { void I1.M2() {} void I1.M3() {} } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (6,27): error CS0500: 'I1.M3()' cannot declare a body because it is marked abstract // virtual abstract void M3() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M3").WithArguments("I1.M3()").WithLocation(6, 27), // (6,27): error CS0503: The abstract method 'I1.M3()' cannot be marked virtual // virtual abstract void M3() Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "M3").WithArguments("method", "I1.M3()").WithLocation(6, 27), // (4,27): error CS0503: The abstract method 'I1.M2()' cannot be marked virtual // abstract virtual void M2(); Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "M2").WithArguments("method", "I1.M2()").WithLocation(4, 27), // (17,15): error CS0535: 'Test2' does not implement interface member 'I1.M3()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M3()").WithLocation(17, 15), // (17,15): error CS0535: 'Test2' does not implement interface member 'I1.M2()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M2()").WithLocation(17, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var i1 = compilation1.GetTypeByMetadataName("I1"); foreach (var methodName in new[] { "M2", "M3" }) { var m2 = i1.GetMember<MethodSymbol>(methodName); Assert.True(m2.IsAbstract); Assert.True(m2.IsVirtual); Assert.True(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.False(m2.IsStatic); Assert.False(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility); Assert.Same(test1.GetMember("I1." + methodName), test1.FindImplementationForInterfaceMember(m2)); Assert.Null(test2.FindImplementationForInterfaceMember(m2)); } } [Fact] public void MethodModifiers_15() { var source1 = @" public interface I1 { extern void M1(); virtual extern void M2(); static extern void M3(); private extern void M4(); extern sealed void M5(); } class Test1 : I1 { } class Test2 : I1 { void I1.M1() {} void I1.M2() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test2 = m.GlobalNamespace.GetTypeMember("Test2"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); bool isSource = !(m is PEModuleSymbol); Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.Equal(isSource, m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); Assert.Same(test2.GetMember("I1.M1"), test2.FindImplementationForInterfaceMember(m1)); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.False(m2.IsAbstract); Assert.True(m2.IsVirtual); Assert.True(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.False(m2.IsStatic); Assert.Equal(isSource, m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility); Assert.Same(m2, test1.FindImplementationForInterfaceMember(m2)); Assert.Same(test2.GetMember("I1.M2"), test2.FindImplementationForInterfaceMember(m2)); var m3 = i1.GetMember<MethodSymbol>("M3"); Assert.False(m3.IsAbstract); Assert.False(m3.IsVirtual); Assert.False(m3.IsMetadataVirtual()); Assert.False(m3.IsSealed); Assert.True(m3.IsStatic); Assert.Equal(isSource, m3.IsExtern); Assert.False(m3.IsAsync); Assert.False(m3.IsOverride); Assert.Equal(Accessibility.Public, m3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m3)); Assert.Null(test2.FindImplementationForInterfaceMember(m3)); var m4 = i1.GetMember<MethodSymbol>("M4"); Assert.False(m4.IsAbstract); Assert.False(m4.IsVirtual); Assert.False(m4.IsMetadataVirtual()); Assert.False(m4.IsSealed); Assert.False(m4.IsStatic); Assert.Equal(isSource, m4.IsExtern); Assert.False(m4.IsAsync); Assert.False(m4.IsOverride); Assert.Equal(Accessibility.Private, m4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m4)); Assert.Null(test2.FindImplementationForInterfaceMember(m4)); var m5 = i1.GetMember<MethodSymbol>("M5"); Assert.False(m5.IsAbstract); Assert.False(m5.IsVirtual); Assert.False(m5.IsMetadataVirtual()); Assert.False(m5.IsSealed); Assert.False(m5.IsStatic); Assert.Equal(isSource, m5.IsExtern); Assert.False(m5.IsAsync); Assert.False(m5.IsOverride); Assert.Equal(Accessibility.Public, m5.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m5)); Assert.Null(test2.FindImplementationForInterfaceMember(m5)); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (4,17): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern void M1(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M1").WithArguments("extern", "7.3", "8.0").WithLocation(4, 17), // (5,25): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern void M2(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M2").WithArguments("extern", "7.3", "8.0").WithLocation(5, 25), // (5,25): error CS8503: The modifier 'virtual' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern void M2(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M2").WithArguments("virtual", "7.3", "8.0").WithLocation(5, 25), // (6,24): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static extern void M3(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M3").WithArguments("static", "7.3", "8.0").WithLocation(6, 24), // (6,24): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static extern void M3(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M3").WithArguments("extern", "7.3", "8.0").WithLocation(6, 24), // (7,25): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern void M4(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M4").WithArguments("private", "7.3", "8.0").WithLocation(7, 25), // (7,25): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern void M4(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M4").WithArguments("extern", "7.3", "8.0").WithLocation(7, 25), // (8,24): error CS8503: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed void M5(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M5").WithArguments("sealed", "7.3", "8.0").WithLocation(8, 24), // (8,24): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed void M5(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M5").WithArguments("extern", "7.3", "8.0").WithLocation(8, 24), // (4,17): warning CS0626: Method, operator, or accessor 'I1.M1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void M1(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M1").WithArguments("I1.M1()").WithLocation(4, 17), // (5,25): warning CS0626: Method, operator, or accessor 'I1.M2()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern void M2(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M2").WithArguments("I1.M2()").WithLocation(5, 25), // (6,24): warning CS0626: Method, operator, or accessor 'I1.M3()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern void M3(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M3").WithArguments("I1.M3()").WithLocation(6, 24), // (7,25): warning CS0626: Method, operator, or accessor 'I1.M4()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern void M4(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M4").WithArguments("I1.M4()").WithLocation(7, 25), // (8,24): warning CS0626: Method, operator, or accessor 'I1.M5()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed void M5(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M5").WithArguments("I1.M5()").WithLocation(8, 24) ); Validate(compilation2.SourceModule); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (4,17): error CS8501: Target runtime doesn't support default interface implementation. // extern void M1(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(4, 17), // (5,25): error CS8501: Target runtime doesn't support default interface implementation. // virtual extern void M2(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M2").WithLocation(5, 25), // (6,24): error CS8701: Target runtime doesn't support default interface implementation. // static extern void M3(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M3").WithLocation(6, 24), // (7,25): error CS8501: Target runtime doesn't support default interface implementation. // private extern void M4(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M4").WithLocation(7, 25), // (8,24): error CS8501: Target runtime doesn't support default interface implementation. // extern sealed void M5(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M5").WithLocation(8, 24), // (4,17): warning CS0626: Method, operator, or accessor 'I1.M1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void M1(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M1").WithArguments("I1.M1()").WithLocation(4, 17), // (5,25): warning CS0626: Method, operator, or accessor 'I1.M2()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern void M2(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M2").WithArguments("I1.M2()").WithLocation(5, 25), // (6,24): warning CS0626: Method, operator, or accessor 'I1.M3()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern void M3(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M3").WithArguments("I1.M3()").WithLocation(6, 24), // (7,25): warning CS0626: Method, operator, or accessor 'I1.M4()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern void M4(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M4").WithArguments("I1.M4()").WithLocation(7, 25), // (8,24): warning CS0626: Method, operator, or accessor 'I1.M5()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed void M5(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M5").WithArguments("I1.M5()").WithLocation(8, 24) ); Validate(compilation3.SourceModule); } [Fact] public void MethodModifiers_16() { var source1 = @" public interface I1 { abstract extern void M1(); extern void M2() {} static extern void M3(); private extern void M4(); extern sealed void M5(); } class Test1 : I1 { } class Test2 : I1 { void I1.M1() {} void I1.M2() {} void I1.M3() {} void I1.M4() {} void I1.M5() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,26): error CS0180: 'I1.M1()' cannot be both extern and abstract // abstract extern void M1(); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M1").WithArguments("I1.M1()").WithLocation(4, 26), // (5,17): error CS0179: 'I1.M2()' cannot be extern and declare a body // extern void M2() {} Diagnostic(ErrorCode.ERR_ExternHasBody, "M2").WithArguments("I1.M2()").WithLocation(5, 17), // (11,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M1()").WithLocation(11, 15), // (19,13): error CS0539: 'Test2.M3()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M3() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M3").WithArguments("Test2.M3()").WithLocation(19, 13), // (20,13): error CS0539: 'Test2.M4()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M4() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M4").WithArguments("Test2.M4()").WithLocation(20, 13), // (21,13): error CS0539: 'Test2.M5()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M5() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M5").WithArguments("Test2.M5()").WithLocation(21, 13), // (6,24): warning CS0626: Method, operator, or accessor 'I1.M3()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern void M3(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M3").WithArguments("I1.M3()").WithLocation(6, 24), // (7,25): warning CS0626: Method, operator, or accessor 'I1.M4()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern void M4(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M4").WithArguments("I1.M4()").WithLocation(7, 25), // (8,24): warning CS0626: Method, operator, or accessor 'I1.M5()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed void M5(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M5").WithArguments("I1.M5()").WithLocation(8, 24) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.True(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); Assert.Same(test2.GetMember("I1.M1"), test2.FindImplementationForInterfaceMember(m1)); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.False(m2.IsAbstract); Assert.True(m2.IsVirtual); Assert.True(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.False(m2.IsStatic); Assert.True(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility); Assert.Same(m2, test1.FindImplementationForInterfaceMember(m2)); Assert.Same(test2.GetMember("I1.M2"), test2.FindImplementationForInterfaceMember(m2)); var m3 = i1.GetMember<MethodSymbol>("M3"); Assert.Null(test2.FindImplementationForInterfaceMember(m3)); var m4 = i1.GetMember<MethodSymbol>("M4"); Assert.Null(test2.FindImplementationForInterfaceMember(m4)); var m5 = i1.GetMember<MethodSymbol>("M5"); Assert.Null(test2.FindImplementationForInterfaceMember(m5)); } [Fact] public void MethodModifiers_17() { var source1 = @" public interface I1 { abstract void M1() {} abstract private void M2() {} abstract static void M3() {} static extern void M4() {} override sealed void M5() {} } class Test1 : I1 { } class Test2 : I1 { void I1.M1() {} void I1.M2() {} void I1.M3() {} void I1.M4() {} void I1.M5() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,19): error CS0500: 'I1.M1()' cannot declare a body because it is marked abstract // abstract void M1() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M1").WithArguments("I1.M1()").WithLocation(4, 19), // (5,27): error CS0500: 'I1.M2()' cannot declare a body because it is marked abstract // abstract private void M2() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M2").WithArguments("I1.M2()").WithLocation(5, 27), // (6,26): error CS0500: 'I1.M3()' cannot declare a body because it is marked abstract // abstract static void M3() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M3").WithArguments("I1.M3()").WithLocation(6, 26), // (7,24): error CS0179: 'I1.M4()' cannot be extern and declare a body // static extern void M4() {} Diagnostic(ErrorCode.ERR_ExternHasBody, "M4").WithArguments("I1.M4()").WithLocation(7, 24), // (8,26): error CS0106: The modifier 'override' is not valid for this item // override sealed void M5() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "M5").WithArguments("override").WithLocation(8, 26), // (5,27): error CS0621: 'I1.M2()': virtual or abstract members cannot be private // abstract private void M2() {} Diagnostic(ErrorCode.ERR_VirtualPrivate, "M2").WithArguments("I1.M2()").WithLocation(5, 27), // (6,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M3() {} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M3").WithArguments("abstract", "9.0", "preview").WithLocation(6, 26), // (11,15): error CS0535: 'Test1' does not implement interface member 'I1.M2()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M2()").WithLocation(11, 15), // (11,15): error CS0535: 'Test1' does not implement interface member 'I1.M3()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M3()").WithLocation(11, 15), // (11,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M1()").WithLocation(11, 15), // (18,13): error CS0122: 'I1.M2()' is inaccessible due to its protection level // void I1.M2() {} Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("I1.M2()").WithLocation(18, 13), // (19,13): error CS0539: 'Test2.M3()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M3() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M3").WithArguments("Test2.M3()").WithLocation(19, 13), // (20,13): error CS0539: 'Test2.M4()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M4() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M4").WithArguments("Test2.M4()").WithLocation(20, 13), // (21,13): error CS0539: 'Test2.M5()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M5() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M5").WithArguments("Test2.M5()").WithLocation(21, 13), // (15,15): error CS0535: 'Test2' does not implement interface member 'I1.M3()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M3()").WithLocation(15, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); Assert.Same(test2.GetMember("I1.M1"), test2.FindImplementationForInterfaceMember(m1)); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.True(m2.IsAbstract); Assert.False(m2.IsVirtual); Assert.True(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.False(m2.IsStatic); Assert.False(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m2)); Assert.Same(test2.GetMember("I1.M2"), test2.FindImplementationForInterfaceMember(m2)); var m3 = i1.GetMember<MethodSymbol>("M3"); Assert.True(m3.IsAbstract); Assert.False(m3.IsVirtual); Assert.True(m3.IsMetadataVirtual()); Assert.False(m3.IsSealed); Assert.True(m3.IsStatic); Assert.False(m3.IsExtern); Assert.False(m3.IsAsync); Assert.False(m3.IsOverride); Assert.Equal(Accessibility.Public, m3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m3)); Assert.Null(test2.FindImplementationForInterfaceMember(m3)); var m4 = i1.GetMember<MethodSymbol>("M4"); Assert.False(m4.IsAbstract); Assert.False(m4.IsVirtual); Assert.False(m4.IsMetadataVirtual()); Assert.False(m4.IsSealed); Assert.True(m4.IsStatic); Assert.True(m4.IsExtern); Assert.False(m4.IsAsync); Assert.False(m4.IsOverride); Assert.Equal(Accessibility.Public, m4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m4)); Assert.Null(test2.FindImplementationForInterfaceMember(m4)); var m5 = i1.GetMember<MethodSymbol>("M5"); Assert.False(m5.IsAbstract); Assert.False(m5.IsVirtual); Assert.False(m5.IsMetadataVirtual()); Assert.False(m5.IsSealed); Assert.False(m5.IsStatic); Assert.False(m5.IsExtern); Assert.False(m5.IsAsync); Assert.False(m5.IsOverride); Assert.Equal(Accessibility.Public, m5.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m5)); Assert.Null(test2.FindImplementationForInterfaceMember(m5)); } [Fact] [WorkItem(34658, "https://github.com/dotnet/roslyn/issues/34658")] public void MethodModifiers_18() { var source1 = @" using System.Threading; using System.Threading.Tasks; public interface I1 { public static async Task M1() { await Task.Factory.StartNew(() => System.Console.WriteLine(""M1"")); } } class Test1 : I1 { static void Main() { I1.M1().Wait(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.True(m1.IsStatic); Assert.False(m1.IsExtern); Assert.Equal(!(m is PEModuleSymbol), m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); } } [Fact] public void MethodModifiers_20() { var source1 = @" public interface I1 { internal void M1() { System.Console.WriteLine(""M1""); } void M2() {M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var m1 = i1.GetMember<MethodSymbol>("M1"); ValidateMethod(m1); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); } void ValidateMethod(MethodSymbol m1) { Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Internal, m1.DeclaredAccessibility); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); ValidateMethod(m1); } var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation3.SourceModule); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation4, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation4.SourceModule); } [Fact] public void MethodModifiers_21() { var source1 = @" public interface I1 { private static void M1() {} internal static void M2() {} public static void M3() {} static void M4() {} } class Test1 { static void Main() { I1.M1(); I1.M2(); I1.M3(); I1.M4(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (17,12): error CS0122: 'I1.M1()' is inaccessible due to its protection level // I1.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.M1()").WithLocation(17, 12) ); var source2 = @" class Test2 { static void Main() { I1.M1(); I1.M2(); I1.M3(); I1.M4(); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,12): error CS0122: 'I1.M1()' is inaccessible due to its protection level // I1.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.M1()").WithLocation(6, 12), // (7,12): error CS0122: 'I1.M2()' is inaccessible due to its protection level // I1.M2(); Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("I1.M2()").WithLocation(7, 12) ); } [Fact] public void MethodModifiers_22() { var source1 = @" public partial interface I1 { static partial void M1(); [Test2(1)] static partial void M2(); static partial void Main() { M1(); M2(); new System.Action(M2).Invoke(); } } public partial interface I1 { [Test2(2)] static partial void M2() { System.Console.WriteLine(""M2""); } static partial void Main(); } class Test1 : I1 { } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)] class Test2 : System.Attribute { public Test2(int x) {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M2 M2"); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.True(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); Assert.True(m1.IsPartialMethod()); Assert.Null(m1.PartialImplementationPart); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.False(m2.IsAbstract); Assert.False(m2.IsVirtual); Assert.False(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.True(m2.IsStatic); Assert.False(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility); Assert.True(m2.IsPartialMethod()); Assert.Equal(2, m2.GetAttributes().Length); Assert.Equal("Test2(1)", m2.GetAttributes()[0].ToString()); Assert.Equal("Test2(2)", m2.GetAttributes()[1].ToString()); var m2Impl = m2.PartialImplementationPart; Assert.False(m2Impl.IsAbstract); Assert.False(m2Impl.IsVirtual); Assert.False(m2Impl.IsMetadataVirtual()); Assert.False(m2Impl.IsSealed); Assert.True(m2Impl.IsStatic); Assert.False(m2Impl.IsExtern); Assert.False(m2Impl.IsAsync); Assert.False(m2Impl.IsOverride); Assert.Equal(Accessibility.Private, m2Impl.DeclaredAccessibility); Assert.True(m2Impl.IsPartialMethod()); Assert.Same(m2, m2Impl.PartialDefinitionPart); Assert.Equal(2, m2Impl.GetAttributes().Length); Assert.Equal("Test2(1)", m2Impl.GetAttributes()[0].ToString()); Assert.Equal("Test2(2)", m2Impl.GetAttributes()[1].ToString()); } [Fact] public void MethodModifiers_23() { var source1 = @" public partial interface I1 { partial void M1(); [Test2(1)] partial void M2(); void M3() { M1(); M2(); new System.Action(M2).Invoke(); } } public partial interface I1 { [Test2(2)] partial void M2() { System.Console.WriteLine(""M2""); } } class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M3(); } } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)] class Test2 : System.Attribute { public Test2(int x) {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M2 M2", verify: VerifyOnMonoOrCoreClr); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); Assert.True(m1.IsPartialMethod()); Assert.Null(m1.PartialImplementationPart); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.False(m2.IsAbstract); Assert.False(m2.IsVirtual); Assert.False(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.False(m2.IsStatic); Assert.False(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility); Assert.True(m2.IsPartialMethod()); Assert.Equal(2, m2.GetAttributes().Length); Assert.Equal("Test2(1)", m2.GetAttributes()[0].ToString()); Assert.Equal("Test2(2)", m2.GetAttributes()[1].ToString()); var m2Impl = m2.PartialImplementationPart; Assert.False(m2Impl.IsAbstract); Assert.False(m2Impl.IsVirtual); Assert.False(m2Impl.IsMetadataVirtual()); Assert.False(m2Impl.IsSealed); Assert.False(m2Impl.IsStatic); Assert.False(m2Impl.IsExtern); Assert.False(m2Impl.IsAsync); Assert.False(m2Impl.IsOverride); Assert.Equal(Accessibility.Private, m2Impl.DeclaredAccessibility); Assert.True(m2Impl.IsPartialMethod()); Assert.Same(m2, m2Impl.PartialDefinitionPart); Assert.Equal(2, m2Impl.GetAttributes().Length); Assert.Equal("Test2(1)", m2Impl.GetAttributes()[0].ToString()); Assert.Equal("Test2(2)", m2Impl.GetAttributes()[1].ToString()); } [Fact] public void MethodModifiers_24() { var source1 = @" public partial interface I1 { static partial void M1(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3); compilation1.VerifyDiagnostics( // (4,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static partial void M1(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M1").WithArguments("static", "7.3", "8.0").WithLocation(4, 25), // (4,25): error CS8703: The modifier 'partial' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static partial void M1(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M1").WithArguments("partial", "7.3", "8.0").WithLocation(4, 25) ); } [Fact] public void MethodModifiers_25() { var source1 = @" public partial interface I1 { partial void M1(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,18): error CS8703: The modifier 'partial' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // partial void M1(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M1").WithArguments("partial", "7.3", "8.0").WithLocation(4, 18) ); } [Fact] public void MethodModifiers_26() { var source1 = @" public partial interface I1 { static partial int M1(); public static partial void M2(); internal static partial void M3(); private static partial void M4(); static partial void M5(out int x); static partial void M6(); static void M7() {} static partial void M8() {} static partial void M9(); static partial void M10(); } public partial interface I1 { static void M6() {} static partial void M7(); static partial void M8() {} static partial void M9(); static extern partial void M10(); protected static partial void M11(); protected internal static partial void M12(); private protected static partial void M13(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularWithExtendedPartialMethods, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS8794: Partial method 'I1.M1()' must have accessibility modifiers because it has a non-void return type. // static partial int M1(); Diagnostic(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, "M1").WithArguments("I1.M1()").WithLocation(4, 24), // (5,32): error CS8793: Partial method 'I1.M2()' must have an implementation part because it has accessibility modifiers. // public static partial void M2(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M2").WithArguments("I1.M2()").WithLocation(5, 32), // (6,34): error CS8793: Partial method 'I1.M3()' must have an implementation part because it has accessibility modifiers. // internal static partial void M3(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M3").WithArguments("I1.M3()").WithLocation(6, 34), // (7,33): error CS8793: Partial method 'I1.M4()' must have an implementation part because it has accessibility modifiers. // private static partial void M4(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M4").WithArguments("I1.M4()").WithLocation(7, 33), // (8,25): error CS8795: Partial method 'I1.M5(out int)' must have accessibility modifiers because it has 'out' parameters. // static partial void M5(out int x); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M5").WithArguments("I1.M5(out int)").WithLocation(8, 25), // (11,25): error CS0759: No defining declaration found for implementing declaration of partial method 'I1.M8()' // static partial void M8() {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M8").WithArguments("I1.M8()").WithLocation(11, 25), // (18,17): error CS0111: Type 'I1' already defines a member called 'M6' with the same parameter types // static void M6() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M6").WithArguments("M6", "I1").WithLocation(18, 17), // (19,25): error CS0111: Type 'I1' already defines a member called 'M7' with the same parameter types // static partial void M7(); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M7").WithArguments("M7", "I1").WithLocation(19, 25), // (20,25): error CS0757: A partial method may not have multiple implementing declarations // static partial void M8() {} Diagnostic(ErrorCode.ERR_PartialMethodOnlyOneActual, "M8").WithLocation(20, 25), // (20,25): error CS0111: Type 'I1' already defines a member called 'M8' with the same parameter types // static partial void M8() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M8").WithArguments("M8", "I1").WithLocation(20, 25), // (21,25): error CS0756: A partial method may not have multiple defining declarations // static partial void M9(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyOneLatent, "M9").WithLocation(21, 25), // (21,25): error CS0111: Type 'I1' already defines a member called 'M9' with the same parameter types // static partial void M9(); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M9").WithArguments("M9", "I1").WithLocation(21, 25), // (22,32): error CS8796: Partial method 'I1.M10()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // static extern partial void M10(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "M10").WithArguments("I1.M10()").WithLocation(22, 32), // (23,35): error CS8793: Partial method 'I1.M11()' must have an implementation part because it has accessibility modifiers. // protected static partial void M11(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M11").WithArguments("I1.M11()").WithLocation(23, 35), // (24,44): error CS8793: Partial method 'I1.M12()' must have an implementation part because it has accessibility modifiers. // protected internal static partial void M12(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M12").WithArguments("I1.M12()").WithLocation(24, 44), // (25,43): error CS8793: Partial method 'I1.M13()' must have an implementation part because it has accessibility modifiers. // private protected static partial void M13(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M13").WithArguments("I1.M13()").WithLocation(25, 43) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularWithExtendedPartialMethods, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (4,24): error CS8794: Partial method 'I1.M1()' must have accessibility modifiers because it has a non-void return type. // static partial int M1(); Diagnostic(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, "M1").WithArguments("I1.M1()").WithLocation(4, 24), // (5,32): error CS8793: Partial method 'I1.M2()' must have an implementation part because it has accessibility modifiers. // public static partial void M2(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M2").WithArguments("I1.M2()").WithLocation(5, 32), // (6,34): error CS8793: Partial method 'I1.M3()' must have an implementation part because it has accessibility modifiers. // internal static partial void M3(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M3").WithArguments("I1.M3()").WithLocation(6, 34), // (7,33): error CS8793: Partial method 'I1.M4()' must have an implementation part because it has accessibility modifiers. // private static partial void M4(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M4").WithArguments("I1.M4()").WithLocation(7, 33), // (8,25): error CS8795: Partial method 'I1.M5(out int)' must have accessibility modifiers because it has 'out' parameters. // static partial void M5(out int x); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M5").WithArguments("I1.M5(out int)").WithLocation(8, 25), // (10,17): error CS8701: Target runtime doesn't support default interface implementation. // static void M7() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M7").WithLocation(10, 17), // (11,25): error CS8701: Target runtime doesn't support default interface implementation. // static partial void M8() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M8").WithLocation(11, 25), // (11,25): error CS0759: No defining declaration found for implementing declaration of partial method 'I1.M8()' // static partial void M8() {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M8").WithArguments("I1.M8()").WithLocation(11, 25), // (18,17): error CS8701: Target runtime doesn't support default interface implementation. // static void M6() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M6").WithLocation(18, 17), // (18,17): error CS0111: Type 'I1' already defines a member called 'M6' with the same parameter types // static void M6() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M6").WithArguments("M6", "I1").WithLocation(18, 17), // (19,25): error CS0111: Type 'I1' already defines a member called 'M7' with the same parameter types // static partial void M7(); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M7").WithArguments("M7", "I1").WithLocation(19, 25), // (20,25): error CS8701: Target runtime doesn't support default interface implementation. // static partial void M8() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M8").WithLocation(20, 25), // (20,25): error CS0757: A partial method may not have multiple implementing declarations // static partial void M8() {} Diagnostic(ErrorCode.ERR_PartialMethodOnlyOneActual, "M8").WithLocation(20, 25), // (20,25): error CS0111: Type 'I1' already defines a member called 'M8' with the same parameter types // static partial void M8() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M8").WithArguments("M8", "I1").WithLocation(20, 25), // (21,25): error CS0756: A partial method may not have multiple defining declarations // static partial void M9(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyOneLatent, "M9").WithLocation(21, 25), // (21,25): error CS0111: Type 'I1' already defines a member called 'M9' with the same parameter types // static partial void M9(); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M9").WithArguments("M9", "I1").WithLocation(21, 25), // (22,32): error CS8701: Target runtime doesn't support default interface implementation. // static extern partial void M10(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M10").WithLocation(22, 32), // (22,32): error CS8796: Partial method 'I1.M10()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // static extern partial void M10(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "M10").WithArguments("I1.M10()").WithLocation(22, 32), // (23,35): error CS8793: Partial method 'I1.M11()' must have an implementation part because it has accessibility modifiers. // protected static partial void M11(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M11").WithArguments("I1.M11()").WithLocation(23, 35), // (24,44): error CS8793: Partial method 'I1.M12()' must have an implementation part because it has accessibility modifiers. // protected internal static partial void M12(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M12").WithArguments("I1.M12()").WithLocation(24, 44), // (25,43): error CS8793: Partial method 'I1.M13()' must have an implementation part because it has accessibility modifiers. // private protected static partial void M13(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M13").WithArguments("I1.M13()").WithLocation(25, 43) ); } [Fact] public void MethodModifiers_27() { var source1 = @" partial interface I1 : I2 { sealed partial void M1(); abstract partial void M2(); virtual partial void M3(); partial void M4(); partial void M5(); partial void M6(); partial void I2.M7(); } partial interface I1 : I2 { sealed partial void M4() {} abstract partial void M5(); virtual partial void M6() {} partial void I2.M7() {} } interface I2 { void M7(); partial void M8(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularWithExtendedPartialMethods, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,25): error CS8796: Partial method 'I1.M1()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // sealed partial void M1(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "M1").WithArguments("I1.M1()").WithLocation(4, 25), // (5,27): error CS0750: A partial method cannot have the 'abstract' modifier // abstract partial void M2(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M2").WithLocation(5, 27), // (6,26): error CS8796: Partial method 'I1.M3()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // virtual partial void M3(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "M3").WithArguments("I1.M3()").WithLocation(6, 26), // (10,21): error CS0754: A partial method may not explicitly implement an interface method // partial void I2.M7(); Diagnostic(ErrorCode.ERR_PartialMethodNotExplicit, "M7").WithLocation(10, 21), // (15,25): error CS8796: Partial method 'I1.M4()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // sealed partial void M4() {} Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "M4").WithArguments("I1.M4()").WithLocation(15, 25), // (15,25): error CS8798: Both partial method declarations must have identical combinations of 'virtual', 'override', 'sealed', and 'new' modifiers. // sealed partial void M4() {} Diagnostic(ErrorCode.ERR_PartialMethodExtendedModDifference, "M4").WithLocation(15, 25), // (16,27): error CS0750: A partial method cannot have the 'abstract' modifier // abstract partial void M5(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M5").WithLocation(16, 27), // (16,27): error CS0756: A partial method may not have multiple defining declarations // abstract partial void M5(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyOneLatent, "M5").WithLocation(16, 27), // (16,27): error CS0111: Type 'I1' already defines a member called 'M5' with the same parameter types // abstract partial void M5(); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M5").WithArguments("M5", "I1").WithLocation(16, 27), // (17,26): error CS8796: Partial method 'I1.M6()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // virtual partial void M6() {} Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "M6").WithArguments("I1.M6()").WithLocation(17, 26), // (17,26): error CS8798: Both partial method declarations must have identical combinations of 'virtual', 'override', 'sealed', and 'new' modifiers. // virtual partial void M6() {} Diagnostic(ErrorCode.ERR_PartialMethodExtendedModDifference, "M6").WithLocation(17, 26), // (19,21): error CS0754: A partial method may not explicitly implement an interface method // partial void I2.M7() {} Diagnostic(ErrorCode.ERR_PartialMethodNotExplicit, "M7").WithLocation(19, 21), // (25,18): error CS0751: A partial method must be declared within a partial type // partial void M8(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M8").WithLocation(25, 18) ); } [Fact] public void MethodModifiers_28() { var source1 = @" partial interface I1 { partial void M1(); class C : I1 { void I1.M1() {} } } public partial interface I1 { partial void M1() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,17): error CS0539: 'I1.C.M1()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M1() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M1").WithArguments("I1.C.M1()").WithLocation(8, 17) ); } [Fact] public void MethodModifiers_29() { var source1 = @" public partial interface I1 { partial void M1(); static partial void M2(); void M3() { new System.Action(M1).Invoke(); new System.Action(M2).Invoke(); } partial static void M4(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,27): error CS0762: Cannot create delegate from method 'I1.M1()' because it is a partial method without an implementing declaration // new System.Action(M1).Invoke(); Diagnostic(ErrorCode.ERR_PartialMethodToDelegate, "M1").WithArguments("I1.M1()").WithLocation(9, 27), // (10,27): error CS0762: Cannot create delegate from method 'I1.M2()' because it is a partial method without an implementing declaration // new System.Action(M2).Invoke(); Diagnostic(ErrorCode.ERR_PartialMethodToDelegate, "M2").WithArguments("I1.M2()").WithLocation(10, 27), // (13,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static void M4(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(13, 5) ); } [Fact] public void MethodModifiers_30() { var source1 = @" public partial interface I1 { static partial void Main(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1) ); } [Fact] public void MethodModifiers_31() { var source1 = @" public partial interface I1 { static partial void M1<T>() where T : struct; static partial void M1<T>() {} static partial void M2(params int[] x); static partial void M2(int[] x) {} static partial void M3(); partial void M3() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,25): error CS0761: Partial method declarations of 'I1.M1<T>()' have inconsistent constraints for type parameter 'T' // static partial void M1<T>() {} Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "M1").WithArguments("I1.M1<T>()", "T").WithLocation(5, 25), // (8,25): error CS0758: Both partial method declarations must use a params parameter or neither may use a params parameter // static partial void M2(int[] x) {} Diagnostic(ErrorCode.ERR_PartialMethodParamsDifference, "M2").WithLocation(8, 25), // (11,18): error CS0763: Both partial method declarations must be static or neither may be static // partial void M3() {} Diagnostic(ErrorCode.ERR_PartialMethodStaticDifference, "M3").WithLocation(11, 18) ); } [Fact] public void MethodModifiers_32() { var source1 = @" partial interface I1 { partial void M1(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics(); var source2 = @" partial interface I1 { partial void M1() {} } "; var compilation2 = CreateCompilation(source1 + source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,18): error CS8701: Target runtime doesn't support default interface implementation. // partial void M1() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(9, 18) ); } [Fact] public void MethodModifiers_33() { var source0 = @" public interface I1 { protected static void M1() { System.Console.WriteLine(""M1""); } protected internal static void M2() { System.Console.WriteLine(""M2""); } private protected static void M3() { System.Console.WriteLine(""M3""); } } "; var source1 = @" class Test1 : I1 { static void Main() { I1.M1(); I1.M2(); I1.M3(); } } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2 M3", symbolValidator: validate, verify: VerifyOnMonoOrCoreClr); validate(compilation1.SourceModule); var source2 = @" class Test1 { static void Main() { I1.M2(); } } "; var compilation2 = CreateCompilation(source0 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M2", verify: VerifyOnMonoOrCoreClr); var compilation3 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); var source3 = @" class Test1 : I1 { static void Main() { I1.M1(); I1.M2(); } } "; var source4 = @" class Test1 { static void Main() { I1.M1(); I1.M2(); I1.M3(); } } "; foreach (var reference in new[] { compilation3.ToMetadataReference(), compilation3.EmitToImageReference() }) { var compilation4 = CreateCompilation(source3, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2", verify: VerifyOnMonoOrCoreClr); var compilation5 = CreateCompilation(source4, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (6,12): error CS0122: 'I1.M1()' is inaccessible due to its protection level // I1.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.M1()").WithLocation(6, 12), // (7,12): error CS0122: 'I1.M2()' is inaccessible due to its protection level // I1.M2(); Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("I1.M2()").WithLocation(7, 12), // (8,12): error CS0122: 'I1.M3()' is inaccessible due to its protection level // I1.M3(); Diagnostic(ErrorCode.ERR_BadAccess, "M3").WithArguments("I1.M3()").WithLocation(8, 12) ); var compilation6 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (8,12): error CS0122: 'I1.M3()' is inaccessible due to its protection level // I1.M3(); Diagnostic(ErrorCode.ERR_BadAccess, "M3").WithArguments("I1.M3()").WithLocation(8, 12) ); } void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); foreach (var tuple in new[] { (name: "M1", access: Accessibility.Protected), (name: "M2", access: Accessibility.ProtectedOrInternal), (name: "M3", access: Accessibility.ProtectedAndInternal) }) { var m1 = i1.GetMember<MethodSymbol>(tuple.name); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.True(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(tuple.access, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); } } } [Fact] public void MethodModifiers_34() { var source1 = @" public interface I1 { protected abstract void M1(); public void M2() => M1(); } "; var source21 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M1(); } public void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source21 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var expected = new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 15), // (7,11): error CS1540: Cannot access protected member 'I1.M1()' via a qualifier of type 'I1'; the qualifier must be of type 'Test1' (or derived from it) // x.M1(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M1").WithArguments("I1.M1()", "I1", "Test1").WithLocation(7, 11) }; compilation1.VerifyDiagnostics(expected); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.Protected); var source22 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public void M1() { System.Console.WriteLine(""M1""); } } "; compilation1 = CreateCompilation(source22 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.Protected)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.Protected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.Protected); var source3 = @" class Test2 : I1 { } "; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source21, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.Protected); compilation3 = CreateCompilation(source22, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.Protected)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.Protected); var compilation5 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.M1()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M1()").WithLocation(2, 15) ); ValidateI1M1NotImplemented(compilation5, "Test2"); } } [Fact] public void MethodModifiers_35() { var source1 = @" public interface I1 { protected internal abstract void M1(); public void M2() => M1(); } "; var source21 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M1(); } public virtual void M1() { System.Console.WriteLine(""M1""); } } "; var source22 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public virtual void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source21 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 15) ); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.ProtectedOrInternal); compilation1 = CreateCompilation(source21 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.ProtectedOrInternal)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.ProtectedOrInternal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.ProtectedOrInternal); var source3 = @" class Test2 : I1 { } "; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source21, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 15), // (7,11): error CS1540: Cannot access protected member 'I1.M1()' via a qualifier of type 'I1'; the qualifier must be of type 'Test1' (or derived from it) // x.M1(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M1").WithArguments("I1.M1()", "I1", "Test1").WithLocation(7, 11) ); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.ProtectedOrInternal); compilation3 = CreateCompilation(source22, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.ProtectedOrInternal)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.ProtectedOrInternal); var compilation5 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.M1()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M1()").WithLocation(2, 15) ); ValidateI1M1NotImplemented(compilation5, "Test2"); } } [Fact] public void MethodModifiers_36() { var source1 = @" public interface I1 { private protected abstract void M1(); public void M2() => M1(); } "; var source21 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M1(); } public void M1() { System.Console.WriteLine(""M1""); } } "; var source22 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source21 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 15), // (7,11): error CS1540: Cannot access protected member 'I1.M1()' via a qualifier of type 'I1'; the qualifier must be of type 'Test1' (or derived from it) // x.M1(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M1").WithArguments("I1.M1()", "I1", "Test1").WithLocation(7, 11) ); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.ProtectedAndInternal); compilation1 = CreateCompilation(source22 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.ProtectedAndInternal)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.ProtectedAndInternal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.ProtectedAndInternal); var source3 = @" class Test2 : I1 { } "; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source21, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 15), // (7,11): error CS0122: 'I1.M1()' is inaccessible due to its protection level // x.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.M1()").WithLocation(7, 11) ); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.ProtectedAndInternal); compilation3 = CreateCompilation(source22, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.ProtectedAndInternal)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.ProtectedAndInternal); var compilation5 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.M1()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M1()").WithLocation(2, 15) ); ValidateI1M1NotImplemented(compilation5, "Test2"); } } [Fact] public void MethodModifiers_37() { var source1 = @" public interface I1 { protected abstract void M1(); static void M2(I1 x) => x.M1(); } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); I1.M2(x); } void I1.M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersExplicit_10(m, Accessibility.Protected)); ValidateMethodModifiersExplicit_10(compilation1.SourceModule, Accessibility.Protected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.Protected); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.StandardLatest); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: "M1", symbolValidator: (m) => ValidateMethodModifiersExplicit_10(m, Accessibility.Protected)); ValidateMethodModifiersExplicit_10(compilation3.SourceModule, Accessibility.Protected); } } [Fact] public void MethodModifiers_38() { var source1 = @" public interface I1 { protected internal abstract void M1(); static void M2(I1 x) => x.M1(); } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); I1.M2(x); } void I1.M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersExplicit_10(m, Accessibility.ProtectedOrInternal)); ValidateMethodModifiersExplicit_10(compilation1.SourceModule, Accessibility.ProtectedOrInternal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.ProtectedOrInternal); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.StandardLatest); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: "M1", symbolValidator: (m) => ValidateMethodModifiersExplicit_10(m, Accessibility.ProtectedOrInternal)); ValidateMethodModifiersExplicit_10(compilation3.SourceModule, Accessibility.ProtectedOrInternal); } } [Fact] public void MethodModifiers_39() { var source1 = @" public interface I1 { private protected abstract void M1(); static void M2(I1 x) => x.M1(); } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); I1.M2(x); } void I1.M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersExplicit_10(m, Accessibility.ProtectedAndInternal)); ValidateMethodModifiersExplicit_10(compilation1.SourceModule, Accessibility.ProtectedAndInternal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.ProtectedAndInternal); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.StandardLatest); compilation3.VerifyDiagnostics( // (10,13): error CS0122: 'I1.M1()' is inaccessible due to its protection level // void I1.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.M1()").WithLocation(10, 13) ); ValidateMethodModifiersExplicit_10(compilation3.SourceModule, Accessibility.ProtectedAndInternal); } } [Fact] public void MethodModifiers_40() { var source1 = @" public interface I1 { protected abstract void M1(); public void M2() => M1(); } public class Test2 : I1 { void I1.M1() { } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.M2(); } public void M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.Protected, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void MethodModifiers_41() { var source1 = @" public interface I1 { protected internal abstract void M1(); public void M2() => M1(); } public class Test2 : I1 { void I1.M1() { } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.M2(); } public void M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.ProtectedOrInternal, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void MethodModifiers_42() { var source1 = @" public interface I1 { private protected abstract void M1(); public void M2() => M1(); } public class Test2 : I1 { void I1.M1() { } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.M2(); } public virtual void M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.ProtectedAndInternal, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void MethodModifiers_43() { var source1 = @" public interface I1 { protected void M1() { System.Console.WriteLine(""M1""); } void M2() {M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate1); validate1(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); validateMethod(m1); } foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate1); validate1(compilation3.SourceModule); } void validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var m1 = i1.GetMember<MethodSymbol>("M1"); validateMethod(m1); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); } void validateMethod(MethodSymbol m1) { Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Protected, m1.DeclaredAccessibility); } } [Fact] public void MethodModifiers_44() { var source1 = @" public interface I1 { protected internal void M1() { System.Console.WriteLine(""M1""); } void M2() {M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate1); validate1(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); validateMethod(m1); } foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate1); validate1(compilation3.SourceModule); } void validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var m1 = i1.GetMember<MethodSymbol>("M1"); validateMethod(m1); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); } void validateMethod(MethodSymbol m1) { Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, m1.DeclaredAccessibility); } } [Fact] public void MethodModifiers_45() { var source1 = @" public interface I1 { private protected void M1() { System.Console.WriteLine(""M1""); } void M2() {M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate1); validate1(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); validateMethod(m1); } foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate1); validate1(compilation3.SourceModule); } void validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var m1 = i1.GetMember<MethodSymbol>("M1"); validateMethod(m1); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); } void validateMethod(MethodSymbol m1) { Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, m1.DeclaredAccessibility); } } [Fact] public void ImplicitThisIsAllowed_03() { var source1 = @" public interface I1 { public int F1; void M1() { System.Console.WriteLine(""I1.M1""); } int P1 { get { System.Console.WriteLine(""I1.get_P1""); return 0; } set => System.Console.WriteLine(""I1.set_P1""); } event System.Action E1 { add => System.Console.WriteLine(""I1.add_E1""); remove => System.Console.WriteLine(""I1.remove_E1""); } public interface I2 : I1 { void M2() { M1(); P1 = P1; E1 += null; E1 -= null; F1 = 0; } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,16): error CS0525: Interfaces cannot contain fields // public int F1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F1").WithLocation(4, 16) ); } [Fact] public void ImplicitThisIsAllowed_04() { var source1 = @" public interface I1 { public int F1; void M1() { System.Console.WriteLine(""I1.M1""); } int P1 { get { System.Console.WriteLine(""I1.get_P1""); return 0; } set => System.Console.WriteLine(""I1.set_P1""); } event System.Action E1 { add => System.Console.WriteLine(""I1.add_E1""); remove => System.Console.WriteLine(""I1.remove_E1""); } public interface I2 { void M2() { M1(); P1 = P1; E1 += null; E1 -= null; F1 = 0; } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,16): error CS0525: Interfaces cannot contain fields // public int F1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F1").WithLocation(4, 16), // (31,13): error CS0120: An object reference is required for the non-static field, method, or property 'I1.M1()' // M1(); Diagnostic(ErrorCode.ERR_ObjectRequired, "M1").WithArguments("I1.M1()").WithLocation(31, 13), // (32,13): error CS0120: An object reference is required for the non-static field, method, or property 'I1.P1' // P1 = P1; Diagnostic(ErrorCode.ERR_ObjectRequired, "P1").WithArguments("I1.P1").WithLocation(32, 13), // (32,18): error CS0120: An object reference is required for the non-static field, method, or property 'I1.P1' // P1 = P1; Diagnostic(ErrorCode.ERR_ObjectRequired, "P1").WithArguments("I1.P1").WithLocation(32, 18), // (33,13): error CS0120: An object reference is required for the non-static field, method, or property 'I1.E1' // E1 += null; Diagnostic(ErrorCode.ERR_ObjectRequired, "E1").WithArguments("I1.E1").WithLocation(33, 13), // (34,13): error CS0120: An object reference is required for the non-static field, method, or property 'I1.E1' // E1 -= null; Diagnostic(ErrorCode.ERR_ObjectRequired, "E1").WithArguments("I1.E1").WithLocation(34, 13), // (35,13): error CS0120: An object reference is required for the non-static field, method, or property 'I1.F1' // F1 = 0; Diagnostic(ErrorCode.ERR_ObjectRequired, "F1").WithArguments("I1.F1").WithLocation(35, 13) ); } [Fact] public void ImplicitThisIsAllowed_05() { var source1 = @" public class C1 { public int F1; void M1() { System.Console.WriteLine(""I1.M1""); } int P1 { get { System.Console.WriteLine(""I1.get_P1""); return 0; } set => System.Console.WriteLine(""I1.set_P1""); } event System.Action E1 { add => System.Console.WriteLine(""I1.add_E1""); remove => System.Console.WriteLine(""I1.remove_E1""); } public interface I2 { void M2() { M1(); P1 = P1; E1 += null; E1 -= null; F1 = 0; } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (31,13): error CS0120: An object reference is required for the non-static field, method, or property 'C1.M1()' // M1(); Diagnostic(ErrorCode.ERR_ObjectRequired, "M1").WithArguments("C1.M1()").WithLocation(31, 13), // (32,13): error CS0120: An object reference is required for the non-static field, method, or property 'C1.P1' // P1 = P1; Diagnostic(ErrorCode.ERR_ObjectRequired, "P1").WithArguments("C1.P1").WithLocation(32, 13), // (32,18): error CS0120: An object reference is required for the non-static field, method, or property 'C1.P1' // P1 = P1; Diagnostic(ErrorCode.ERR_ObjectRequired, "P1").WithArguments("C1.P1").WithLocation(32, 18), // (33,13): error CS0120: An object reference is required for the non-static field, method, or property 'C1.E1' // E1 += null; Diagnostic(ErrorCode.ERR_ObjectRequired, "E1").WithArguments("C1.E1").WithLocation(33, 13), // (34,13): error CS0120: An object reference is required for the non-static field, method, or property 'C1.E1' // E1 -= null; Diagnostic(ErrorCode.ERR_ObjectRequired, "E1").WithArguments("C1.E1").WithLocation(34, 13), // (35,13): error CS0120: An object reference is required for the non-static field, method, or property 'C1.F1' // F1 = 0; Diagnostic(ErrorCode.ERR_ObjectRequired, "F1").WithArguments("C1.F1").WithLocation(35, 13) ); } [Fact] public void PropertyModifiers_01() { var source1 = @" public interface I1 { public int P01 {get; set;} protected int P02 {get;} protected internal int P03 {set;} internal int P04 {get;} private int P05 {set;} static int P06 {get;} virtual int P07 {set;} sealed int P08 {get;} override int P09 {set;} abstract int P10 {get;} extern int P11 {get; set;} int P12 { public get; set;} int P13 { get; protected set;} int P14 { protected internal get; set;} int P15 { get; internal set;} int P16 { private get; set;} int P17 { private get;} private protected int P18 {get;} int P19 { get; private protected set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (8,22): error CS0501: 'I1.P05.set' must declare a body because it is not marked abstract, extern, or partial // private int P05 {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.P05.set").WithLocation(8, 22), // (10,22): error CS0501: 'I1.P07.set' must declare a body because it is not marked abstract, extern, or partial // virtual int P07 {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.P07.set").WithLocation(10, 22), // (11,21): error CS0501: 'I1.P08.get' must declare a body because it is not marked abstract, extern, or partial // sealed int P08 {get;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.P08.get").WithLocation(11, 21), // (12,18): error CS0106: The modifier 'override' is not valid for this item // override int P09 {set;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "P09").WithArguments("override").WithLocation(12, 18), // (16,22): error CS0273: The accessibility modifier of the 'I1.P12.get' accessor must be more restrictive than the property or indexer 'I1.P12' // int P12 { public get; set;} Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("I1.P12.get", "I1.P12").WithLocation(16, 22), // (20,23): error CS0442: 'I1.P16.get': abstract properties cannot have private accessors // int P16 { private get; set;} Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I1.P16.get").WithLocation(20, 23), // (21,9): error CS0276: 'I1.P17': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int P17 { private get;} Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P17").WithArguments("I1.P17").WithLocation(21, 9), // (14,21): warning CS0626: Method, operator, or accessor 'I1.P11.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.P11.get").WithLocation(14, 21), // (14,26): warning CS0626: Method, operator, or accessor 'I1.P11.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I1.P11.set").WithLocation(14, 26) ); ValidateSymbolsPropertyModifiers_01(compilation1); } private static void ValidateSymbolsPropertyModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var p01 = i1.GetMember<PropertySymbol>("P01"); Assert.True(p01.IsAbstract); Assert.False(p01.IsVirtual); Assert.False(p01.IsSealed); Assert.False(p01.IsStatic); Assert.False(p01.IsExtern); Assert.False(p01.IsOverride); Assert.Equal(Accessibility.Public, p01.DeclaredAccessibility); ValidateP01Accessor(p01.GetMethod); ValidateP01Accessor(p01.SetMethod); void ValidateP01Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } var p02 = i1.GetMember<PropertySymbol>("P02"); var p02get = p02.GetMethod; Assert.True(p02.IsAbstract); Assert.False(p02.IsVirtual); Assert.False(p02.IsSealed); Assert.False(p02.IsStatic); Assert.False(p02.IsExtern); Assert.False(p02.IsOverride); Assert.Equal(Accessibility.Protected, p02.DeclaredAccessibility); Assert.True(p02get.IsAbstract); Assert.False(p02get.IsVirtual); Assert.True(p02get.IsMetadataVirtual()); Assert.False(p02get.IsSealed); Assert.False(p02get.IsStatic); Assert.False(p02get.IsExtern); Assert.False(p02get.IsAsync); Assert.False(p02get.IsOverride); Assert.Equal(Accessibility.Protected, p02get.DeclaredAccessibility); var p03 = i1.GetMember<PropertySymbol>("P03"); var p03set = p03.SetMethod; Assert.True(p03.IsAbstract); Assert.False(p03.IsVirtual); Assert.False(p03.IsSealed); Assert.False(p03.IsStatic); Assert.False(p03.IsExtern); Assert.False(p03.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, p03.DeclaredAccessibility); Assert.True(p03set.IsAbstract); Assert.False(p03set.IsVirtual); Assert.True(p03set.IsMetadataVirtual()); Assert.False(p03set.IsSealed); Assert.False(p03set.IsStatic); Assert.False(p03set.IsExtern); Assert.False(p03set.IsAsync); Assert.False(p03set.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, p03set.DeclaredAccessibility); var p04 = i1.GetMember<PropertySymbol>("P04"); var p04get = p04.GetMethod; Assert.True(p04.IsAbstract); Assert.False(p04.IsVirtual); Assert.False(p04.IsSealed); Assert.False(p04.IsStatic); Assert.False(p04.IsExtern); Assert.False(p04.IsOverride); Assert.Equal(Accessibility.Internal, p04.DeclaredAccessibility); Assert.True(p04get.IsAbstract); Assert.False(p04get.IsVirtual); Assert.True(p04get.IsMetadataVirtual()); Assert.False(p04get.IsSealed); Assert.False(p04get.IsStatic); Assert.False(p04get.IsExtern); Assert.False(p04get.IsAsync); Assert.False(p04get.IsOverride); Assert.Equal(Accessibility.Internal, p04get.DeclaredAccessibility); var p05 = i1.GetMember<PropertySymbol>("P05"); var p05set = p05.SetMethod; Assert.False(p05.IsAbstract); Assert.False(p05.IsVirtual); Assert.False(p05.IsSealed); Assert.False(p05.IsStatic); Assert.False(p05.IsExtern); Assert.False(p05.IsOverride); Assert.Equal(Accessibility.Private, p05.DeclaredAccessibility); Assert.False(p05set.IsAbstract); Assert.False(p05set.IsVirtual); Assert.False(p05set.IsMetadataVirtual()); Assert.False(p05set.IsSealed); Assert.False(p05set.IsStatic); Assert.False(p05set.IsExtern); Assert.False(p05set.IsAsync); Assert.False(p05set.IsOverride); Assert.Equal(Accessibility.Private, p05set.DeclaredAccessibility); var p06 = i1.GetMember<PropertySymbol>("P06"); var p06get = p06.GetMethod; Assert.False(p06.IsAbstract); Assert.False(p06.IsVirtual); Assert.False(p06.IsSealed); Assert.True(p06.IsStatic); Assert.False(p06.IsExtern); Assert.False(p06.IsOverride); Assert.Equal(Accessibility.Public, p06.DeclaredAccessibility); Assert.False(p06get.IsAbstract); Assert.False(p06get.IsVirtual); Assert.False(p06get.IsMetadataVirtual()); Assert.False(p06get.IsSealed); Assert.True(p06get.IsStatic); Assert.False(p06get.IsExtern); Assert.False(p06get.IsAsync); Assert.False(p06get.IsOverride); Assert.Equal(Accessibility.Public, p06get.DeclaredAccessibility); var p07 = i1.GetMember<PropertySymbol>("P07"); var p07set = p07.SetMethod; Assert.False(p07.IsAbstract); Assert.True(p07.IsVirtual); Assert.False(p07.IsSealed); Assert.False(p07.IsStatic); Assert.False(p07.IsExtern); Assert.False(p07.IsOverride); Assert.Equal(Accessibility.Public, p07.DeclaredAccessibility); Assert.False(p07set.IsAbstract); Assert.True(p07set.IsVirtual); Assert.True(p07set.IsMetadataVirtual()); Assert.False(p07set.IsSealed); Assert.False(p07set.IsStatic); Assert.False(p07set.IsExtern); Assert.False(p07set.IsAsync); Assert.False(p07set.IsOverride); Assert.Equal(Accessibility.Public, p07set.DeclaredAccessibility); var p08 = i1.GetMember<PropertySymbol>("P08"); var p08get = p08.GetMethod; Assert.False(p08.IsAbstract); Assert.False(p08.IsVirtual); Assert.False(p08.IsSealed); Assert.False(p08.IsStatic); Assert.False(p08.IsExtern); Assert.False(p08.IsOverride); Assert.Equal(Accessibility.Public, p08.DeclaredAccessibility); Assert.False(p08get.IsAbstract); Assert.False(p08get.IsVirtual); Assert.False(p08get.IsMetadataVirtual()); Assert.False(p08get.IsSealed); Assert.False(p08get.IsStatic); Assert.False(p08get.IsExtern); Assert.False(p08get.IsAsync); Assert.False(p08get.IsOverride); Assert.Equal(Accessibility.Public, p08get.DeclaredAccessibility); var p09 = i1.GetMember<PropertySymbol>("P09"); var p09set = p09.SetMethod; Assert.True(p09.IsAbstract); Assert.False(p09.IsVirtual); Assert.False(p09.IsSealed); Assert.False(p09.IsStatic); Assert.False(p09.IsExtern); Assert.False(p09.IsOverride); Assert.Equal(Accessibility.Public, p09.DeclaredAccessibility); Assert.True(p09set.IsAbstract); Assert.False(p09set.IsVirtual); Assert.True(p09set.IsMetadataVirtual()); Assert.False(p09set.IsSealed); Assert.False(p09set.IsStatic); Assert.False(p09set.IsExtern); Assert.False(p09set.IsAsync); Assert.False(p09set.IsOverride); Assert.Equal(Accessibility.Public, p09set.DeclaredAccessibility); var p10 = i1.GetMember<PropertySymbol>("P10"); var p10get = p10.GetMethod; Assert.True(p10.IsAbstract); Assert.False(p10.IsVirtual); Assert.False(p10.IsSealed); Assert.False(p10.IsStatic); Assert.False(p10.IsExtern); Assert.False(p10.IsOverride); Assert.Equal(Accessibility.Public, p10.DeclaredAccessibility); Assert.True(p10get.IsAbstract); Assert.False(p10get.IsVirtual); Assert.True(p10get.IsMetadataVirtual()); Assert.False(p10get.IsSealed); Assert.False(p10get.IsStatic); Assert.False(p10get.IsExtern); Assert.False(p10get.IsAsync); Assert.False(p10get.IsOverride); Assert.Equal(Accessibility.Public, p10get.DeclaredAccessibility); var p11 = i1.GetMember<PropertySymbol>("P11"); Assert.False(p11.IsAbstract); Assert.True(p11.IsVirtual); Assert.False(p11.IsSealed); Assert.False(p11.IsStatic); Assert.True(p11.IsExtern); Assert.False(p11.IsOverride); Assert.Equal(Accessibility.Public, p11.DeclaredAccessibility); ValidateP11Accessor(p11.GetMethod); ValidateP11Accessor(p11.SetMethod); void ValidateP11Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } var p12 = i1.GetMember<PropertySymbol>("P12"); Assert.True(p12.IsAbstract); Assert.False(p12.IsVirtual); Assert.False(p12.IsSealed); Assert.False(p12.IsStatic); Assert.False(p12.IsExtern); Assert.False(p12.IsOverride); Assert.Equal(Accessibility.Public, p12.DeclaredAccessibility); ValidateP12Accessor(p12.GetMethod); ValidateP12Accessor(p12.SetMethod); void ValidateP12Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } var p13 = i1.GetMember<PropertySymbol>("P13"); Assert.True(p13.IsAbstract); Assert.False(p13.IsVirtual); Assert.False(p13.IsSealed); Assert.False(p13.IsStatic); Assert.False(p13.IsExtern); Assert.False(p13.IsOverride); Assert.Equal(Accessibility.Public, p13.DeclaredAccessibility); ValidateP13Accessor(p13.GetMethod, Accessibility.Public); ValidateP13Accessor(p13.SetMethod, Accessibility.Protected); void ValidateP13Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p14 = i1.GetMember<PropertySymbol>("P14"); Assert.True(p14.IsAbstract); Assert.False(p14.IsVirtual); Assert.False(p14.IsSealed); Assert.False(p14.IsStatic); Assert.False(p14.IsExtern); Assert.False(p14.IsOverride); Assert.Equal(Accessibility.Public, p14.DeclaredAccessibility); ValidateP14Accessor(p14.GetMethod, Accessibility.ProtectedOrInternal); ValidateP14Accessor(p14.SetMethod, Accessibility.Public); void ValidateP14Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p15 = i1.GetMember<PropertySymbol>("P15"); Assert.True(p15.IsAbstract); Assert.False(p15.IsVirtual); Assert.False(p15.IsSealed); Assert.False(p15.IsStatic); Assert.False(p15.IsExtern); Assert.False(p15.IsOverride); Assert.Equal(Accessibility.Public, p15.DeclaredAccessibility); ValidateP15Accessor(p15.GetMethod, Accessibility.Public); ValidateP15Accessor(p15.SetMethod, Accessibility.Internal); void ValidateP15Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p16 = i1.GetMember<PropertySymbol>("P16"); Assert.True(p16.IsAbstract); Assert.False(p16.IsVirtual); Assert.False(p16.IsSealed); Assert.False(p16.IsStatic); Assert.False(p16.IsExtern); Assert.False(p16.IsOverride); Assert.Equal(Accessibility.Public, p16.DeclaredAccessibility); ValidateP16Accessor(p16.GetMethod, Accessibility.Private); ValidateP16Accessor(p16.SetMethod, Accessibility.Public); void ValidateP16Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p17 = i1.GetMember<PropertySymbol>("P17"); var p17get = p17.GetMethod; Assert.True(p17.IsAbstract); Assert.False(p17.IsVirtual); Assert.False(p17.IsSealed); Assert.False(p17.IsStatic); Assert.False(p17.IsExtern); Assert.False(p17.IsOverride); Assert.Equal(Accessibility.Public, p17.DeclaredAccessibility); Assert.True(p17get.IsAbstract); Assert.False(p17get.IsVirtual); Assert.True(p17get.IsMetadataVirtual()); Assert.False(p17get.IsSealed); Assert.False(p17get.IsStatic); Assert.False(p17get.IsExtern); Assert.False(p17get.IsAsync); Assert.False(p17get.IsOverride); Assert.Equal(Accessibility.Private, p17get.DeclaredAccessibility); var p18 = i1.GetMember<PropertySymbol>("P18"); var p18get = p18.GetMethod; Assert.True(p18.IsAbstract); Assert.False(p18.IsVirtual); Assert.False(p18.IsSealed); Assert.False(p18.IsStatic); Assert.False(p18.IsExtern); Assert.False(p18.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, p18.DeclaredAccessibility); Assert.True(p18get.IsAbstract); Assert.False(p18get.IsVirtual); Assert.True(p18get.IsMetadataVirtual()); Assert.False(p18get.IsSealed); Assert.False(p18get.IsStatic); Assert.False(p18get.IsExtern); Assert.False(p18get.IsAsync); Assert.False(p18get.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, p18get.DeclaredAccessibility); var p19 = i1.GetMember<PropertySymbol>("P19"); Assert.True(p19.IsAbstract); Assert.False(p19.IsVirtual); Assert.False(p19.IsSealed); Assert.False(p19.IsStatic); Assert.False(p19.IsExtern); Assert.False(p19.IsOverride); Assert.Equal(Accessibility.Public, p19.DeclaredAccessibility); ValidateP13Accessor(p19.GetMethod, Accessibility.Public); ValidateP13Accessor(p19.SetMethod, Accessibility.ProtectedAndInternal); } [Fact] public void PropertyModifiers_02() { var source1 = @" public interface I1 { public int P01 {get; set;} protected int P02 {get;} protected internal int P03 {set;} internal int P04 {get;} private int P05 {set;} static int P06 {get;} virtual int P07 {set;} sealed int P08 {get;} override int P09 {set;} abstract int P10 {get;} extern int P11 {get; set;} int P12 { public get; set;} int P13 { get; protected set;} int P14 { protected internal get; set;} int P15 { get; internal set;} int P16 { private get; set;} int P17 { private get;} private protected int P18 {get;} int P19 { get; private protected set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,16): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public int P01 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("public", "7.3", "8.0").WithLocation(4, 16), // (5,19): error CS8703: The modifier 'protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // protected int P02 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P02").WithArguments("protected", "7.3", "8.0").WithLocation(5, 19), // (6,28): error CS8703: The modifier 'protected internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // protected internal int P03 {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P03").WithArguments("protected internal", "7.3", "8.0").WithLocation(6, 28), // (7,18): error CS8503: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal int P04 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P04").WithArguments("internal", "7.3", "8.0").WithLocation(7, 18), // (8,17): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private int P05 {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P05").WithArguments("private", "7.3", "8.0").WithLocation(8, 17), // (8,22): error CS0501: 'I1.P05.set' must declare a body because it is not marked abstract, extern, or partial // private int P05 {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.P05.set").WithLocation(8, 22), // (9,16): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static int P06 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P06").WithArguments("static", "7.3", "8.0").WithLocation(9, 16), // (10,17): error CS8503: The modifier 'virtual' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual int P07 {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P07").WithArguments("virtual", "7.3", "8.0").WithLocation(10, 17), // (10,22): error CS0501: 'I1.P07.set' must declare a body because it is not marked abstract, extern, or partial // virtual int P07 {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.P07.set").WithLocation(10, 22), // (11,16): error CS8503: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // sealed int P08 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P08").WithArguments("sealed", "7.3", "8.0").WithLocation(11, 16), // (11,21): error CS0501: 'I1.P08.get' must declare a body because it is not marked abstract, extern, or partial // sealed int P08 {get;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.P08.get").WithLocation(11, 21), // (12,18): error CS0106: The modifier 'override' is not valid for this item // override int P09 {set;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "P09").WithArguments("override").WithLocation(12, 18), // (13,18): error CS8503: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // abstract int P10 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P10").WithArguments("abstract", "7.3", "8.0").WithLocation(13, 18), // (14,16): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern int P11 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P11").WithArguments("extern", "7.3", "8.0").WithLocation(14, 16), // (16,22): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // int P12 { public get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("public", "7.3", "8.0").WithLocation(16, 22), // (16,22): error CS0273: The accessibility modifier of the 'I1.P12.get' accessor must be more restrictive than the property or indexer 'I1.P12' // int P12 { public get; set;} Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("I1.P12.get", "I1.P12").WithLocation(16, 22), // (17,30): error CS8703: The modifier 'protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // int P13 { get; protected set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("protected", "7.3", "8.0").WithLocation(17, 30), // (18,34): error CS8703: The modifier 'protected internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // int P14 { protected internal get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("protected internal", "7.3", "8.0").WithLocation(18, 34), // (19,29): error CS8503: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // int P15 { get; internal set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("internal", "7.3", "8.0").WithLocation(19, 29), // (20,23): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // int P16 { private get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("private", "7.3", "8.0").WithLocation(20, 23), // (20,23): error CS0442: 'I1.P16.get': abstract properties cannot have private accessors // int P16 { private get; set;} Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I1.P16.get").WithLocation(20, 23), // (21,23): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // int P17 { private get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("private", "7.3", "8.0").WithLocation(21, 23), // (21,9): error CS0276: 'I1.P17': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int P17 { private get;} Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P17").WithArguments("I1.P17").WithLocation(21, 9), // (23,27): error CS8703: The modifier 'private protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private protected int P18 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P18").WithArguments("private protected", "7.3", "8.0").WithLocation(23, 27), // (24,38): error CS8703: The modifier 'private protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // int P19 { get; private protected set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("private protected", "7.3", "8.0").WithLocation(24, 38), // (14,21): warning CS0626: Method, operator, or accessor 'I1.P11.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.P11.get").WithLocation(14, 21), // (14,26): warning CS0626: Method, operator, or accessor 'I1.P11.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I1.P11.set").WithLocation(14, 26) ); ValidateSymbolsPropertyModifiers_01(compilation1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (5,19): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected int P02 {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P02").WithLocation(5, 19), // (6,28): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal int P03 {set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P03").WithLocation(6, 28), // (8,22): error CS0501: 'I1.P05.set' must declare a body because it is not marked abstract, extern, or partial // private int P05 {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.P05.set").WithLocation(8, 22), // (9,21): error CS8701: Target runtime doesn't support default interface implementation. // static int P06 {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(9, 21), // (10,22): error CS0501: 'I1.P07.set' must declare a body because it is not marked abstract, extern, or partial // virtual int P07 {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.P07.set").WithLocation(10, 22), // (11,21): error CS0501: 'I1.P08.get' must declare a body because it is not marked abstract, extern, or partial // sealed int P08 {get;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.P08.get").WithLocation(11, 21), // (12,18): error CS0106: The modifier 'override' is not valid for this item // override int P09 {set;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "P09").WithArguments("override").WithLocation(12, 18), // (14,21): error CS8701: Target runtime doesn't support default interface implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(14, 21), // (14,21): warning CS0626: Method, operator, or accessor 'I1.P11.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.P11.get").WithLocation(14, 21), // (14,26): error CS8701: Target runtime doesn't support default interface implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(14, 26), // (14,26): warning CS0626: Method, operator, or accessor 'I1.P11.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I1.P11.set").WithLocation(14, 26), // (16,22): error CS0273: The accessibility modifier of the 'I1.P12.get' accessor must be more restrictive than the property or indexer 'I1.P12' // int P12 { public get; set;} Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("I1.P12.get", "I1.P12").WithLocation(16, 22), // (17,30): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // int P13 { get; protected set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "set").WithLocation(17, 30), // (18,34): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // int P14 { protected internal get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "get").WithLocation(18, 34), // (20,23): error CS0442: 'I1.P16.get': abstract properties cannot have private accessors // int P16 { private get; set;} Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I1.P16.get").WithLocation(20, 23), // (21,9): error CS0276: 'I1.P17': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int P17 { private get;} Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P17").WithArguments("I1.P17").WithLocation(21, 9), // (23,27): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected int P18 {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P18").WithLocation(23, 27), // (24,38): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // int P19 { get; private protected set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "set").WithLocation(24, 38) ); ValidateSymbolsPropertyModifiers_01(compilation2); } [Fact] public void PropertyModifiers_03() { ValidatePropertyImplementation_101(@" public interface I1 { public virtual int P1 { get { System.Console.WriteLine(""get P1""); return 0; } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "); ValidatePropertyImplementation_101(@" public interface I1 { public virtual int P1 { get => Test1.GetP1(); } } class Test1 : I1 { public static int GetP1() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "); ValidatePropertyImplementation_101(@" public interface I1 { public virtual int P1 => Test1.GetP1(); } class Test1 : I1 { public static int GetP1() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "); ValidatePropertyImplementation_102(@" public interface I1 { public virtual int P1 { get { System.Console.WriteLine(""get P1""); return 0; } set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.P1 = i1.P1; } } "); ValidatePropertyImplementation_102(@" public interface I1 { public virtual int P1 { get => Test1.GetP1(); set => System.Console.WriteLine(""set P1""); } } class Test1 : I1 { public static int GetP1() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); i1.P1 = i1.P1; } } "); ValidatePropertyImplementation_103(@" public interface I1 { public virtual int P1 { set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } } "); ValidatePropertyImplementation_103(@" public interface I1 { public virtual int P1 { set => System.Console.WriteLine(""set P1""); } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } } "); } [Fact] public void PropertyModifiers_04() { var source1 = @" public interface I1 { public virtual int P1 { get; } = 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics( // (4,24): error CS8053: Instance properties in interfaces cannot have initializers. // public virtual int P1 { get; } = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P1").WithArguments("I1.P1").WithLocation(4, 24), // (4,29): error CS0501: 'I1.P1.get' must declare a body because it is not marked abstract, extern, or partial // public virtual int P1 { get; } = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.P1.get").WithLocation(4, 29) ); ValidatePropertyModifiers_04(compilation1, "P1"); } private static void ValidatePropertyModifiers_04(CSharpCompilation compilation1, string propertyName) { var i1 = compilation1.GlobalNamespace.GetTypeMember("I1"); var p1 = i1.GetMember<PropertySymbol>(propertyName); var p1get = p1.GetMethod; Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.False(p1get.IsAbstract); Assert.True(p1get.IsVirtual); Assert.True(p1get.IsMetadataVirtual()); Assert.False(p1get.IsSealed); Assert.False(p1get.IsStatic); Assert.False(p1get.IsExtern); Assert.False(p1get.IsAsync); Assert.False(p1get.IsOverride); Assert.Equal(Accessibility.Public, p1get.DeclaredAccessibility); } [Fact] public void PropertyModifiers_05() { var source1 = @" public interface I1 { public abstract int P1 {get; set;} } public interface I2 { int P2 {get; set;} } class Test1 : I1 { public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set => System.Console.WriteLine(""set_P1""); } } class Test2 : I2 { public int P2 { get { System.Console.WriteLine(""get_P2""); return 0; } set => System.Console.WriteLine(""set_P2""); } static void Main() { I1 x = new Test1(); x.P1 = x.P1; I2 y = new Test2(); y.P2 = y.P2; } } "; ValidatePropertyModifiers_05(source1); } private void ValidatePropertyModifiers_05(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: @"get_P1 set_P1 get_P2 set_P2", symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { for (int i = 1; i <= 2; i++) { var test1 = m.GlobalNamespace.GetTypeMember("Test" + i); var i1 = m.GlobalNamespace.GetTypeMember("I" + i); var p1 = GetSingleProperty(i1); var test1P1 = GetSingleProperty(test1); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Same(test1P1, test1.FindImplementationForInterfaceMember(p1)); ValidateAccessor(p1.GetMethod, test1P1.GetMethod); ValidateAccessor(p1.SetMethod, test1P1.SetMethod); void ValidateAccessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(implementation, test1.FindImplementationForInterfaceMember(accessor)); } } } } private static PropertySymbol GetSingleProperty(NamedTypeSymbol container) { return container.GetMembers().OfType<PropertySymbol>().Single(); } private static PropertySymbol GetSingleProperty(CSharpCompilation compilation, string containerName) { return GetSingleProperty(compilation.GetTypeByMetadataName(containerName)); } private static PropertySymbol GetSingleProperty(ModuleSymbol m, string containerName) { return GetSingleProperty(m.GlobalNamespace.GetTypeMember(containerName)); } [Fact] public void PropertyModifiers_06() { var source1 = @" public interface I1 { public abstract int P1 {get; set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3); compilation1.VerifyDiagnostics( // (4,25): error CS8503: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract int P1 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("abstract", "7.3", "8.0").WithLocation(4, 25), // (4,25): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract int P1 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("public", "7.3", "8.0").WithLocation(4, 25) ); ValidatePropertyModifiers_06(compilation1, "P1"); } private static void ValidatePropertyModifiers_06(CSharpCompilation compilation1, string propertyName) { var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMember<PropertySymbol>(propertyName); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); ValidateAccessor(p1.GetMethod); ValidateAccessor(p1.SetMethod); void ValidateAccessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } } [Fact] public void PropertyModifiers_07() { var source1 = @" public interface I1 { public static int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } internal static int P2 { get { System.Console.WriteLine(""get_P2""); return P3; } set { System.Console.WriteLine(""set_P2""); P3 = value; } } private static int P3 { get => Test1.GetP3(); set => System.Console.WriteLine(""set_P3""); } internal static int P4 => Test1.GetP4(); internal static int P5 { get { System.Console.WriteLine(""get_P5""); return 0; } } internal static int P6 { get => Test1.GetP6(); } internal static int P7 { set { System.Console.WriteLine(""set_P7""); } } internal static int P8 { set => System.Console.WriteLine(""set_P8""); } } class Test1 : I1 { static void Main() { I1.P1 = I1.P1; I1.P2 = I1.P2; var x = I1.P4; x = I1.P5; x = I1.P6; I1.P7 = x; I1.P8 = x; } public static int GetP3() { System.Console.WriteLine(""get_P3""); return 0; } public static int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } public static int GetP6() { System.Console.WriteLine(""get_P6""); return 0; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 get_P3 set_P2 set_P3 get_P4 get_P5 get_P6 set_P7 set_P8", symbolValidator: Validate); Validate(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (6,9): error CS8701: Target runtime doesn't support default interface implementation. // get Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(6, 9), // (11,9): error CS8701: Target runtime doesn't support default interface implementation. // set Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(11, 9), // (19,9): error CS8701: Target runtime doesn't support default interface implementation. // get Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(19, 9), // (24,9): error CS8701: Target runtime doesn't support default interface implementation. // set Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(24, 9), // (33,9): error CS8701: Target runtime doesn't support default interface implementation. // get => Test1.GetP3(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(33, 9), // (34,9): error CS8701: Target runtime doesn't support default interface implementation. // set => System.Console.WriteLine("set_P3"); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(34, 9), // (37,31): error CS8701: Target runtime doesn't support default interface implementation. // internal static int P4 => Test1.GetP4(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "Test1.GetP4()").WithLocation(37, 31), // (41,9): error CS8701: Target runtime doesn't support default interface implementation. // get Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(41, 9), // (50,9): error CS8701: Target runtime doesn't support default interface implementation. // get => Test1.GetP6(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(50, 9), // (55,9): error CS8701: Target runtime doesn't support default interface implementation. // set Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(55, 9), // (63,9): error CS8701: Target runtime doesn't support default interface implementation. // set => System.Console.WriteLine("set_P8"); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(63, 9) ); Validate(compilation2.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); foreach (var tuple in new[] { (name: "P1", access: Accessibility.Public), (name: "P2", access: Accessibility.Internal), (name: "P3", access: Accessibility.Private), (name: "P4", access: Accessibility.Internal), (name: "P5", access: Accessibility.Internal), (name: "P6", access: Accessibility.Internal), (name: "P7", access: Accessibility.Internal), (name: "P8", access: Accessibility.Internal)}) { var p1 = i1.GetMember<PropertySymbol>(tuple.name); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.True(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(tuple.access, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); switch (tuple.name) { case "P7": case "P8": Assert.Null(p1.GetMethod); ValidateAccessor(p1.SetMethod); break; case "P4": case "P5": case "P6": Assert.Null(p1.SetMethod); ValidateAccessor(p1.GetMethod); break; default: ValidateAccessor(p1.GetMethod); ValidateAccessor(p1.SetMethod); break; } void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(tuple.access, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } } [Fact] public void PropertyModifiers_08() { var source1 = @" public interface I1 { abstract static int P1 {get;} virtual static int P2 {set {}} sealed static int P3 => 0; static int P4 {get;} = 0; } class Test1 : I1 { int I1.P1 => 0; int I1.P2 {set {}} int I1.P3 => 0; int I1.P4 {set {}} } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P1 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("abstract", "9.0", "preview").WithLocation(4, 25), // (6,24): error CS0112: A static member cannot be marked as 'virtual' // virtual static int P2 {set {}} Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P2").WithArguments("virtual").WithLocation(6, 24), // (8,23): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static int P3 => 0; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P3").WithArguments("sealed", "9.0", "preview").WithLocation(8, 23), // (13,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(13, 15), // (15,12): error CS0539: 'Test1.P1' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.P1 => 0; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("Test1.P1").WithLocation(15, 12), // (16,12): error CS0539: 'Test1.P2' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.P2 {set {}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P2").WithArguments("Test1.P2").WithLocation(16, 12), // (17,12): error CS0539: 'Test1.P3' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.P3 => 0; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test1.P3").WithLocation(17, 12), // (18,12): error CS0539: 'Test1.P4' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.P4 {set {}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P4").WithArguments("Test1.P4").WithLocation(18, 12), // (21,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(21, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMember<PropertySymbol>("P1"); var p1get = p1.GetMethod; Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.True(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.True(p1get.IsAbstract); Assert.False(p1get.IsVirtual); Assert.True(p1get.IsMetadataVirtual()); Assert.False(p1get.IsSealed); Assert.True(p1get.IsStatic); Assert.False(p1get.IsExtern); Assert.False(p1get.IsAsync); Assert.False(p1get.IsOverride); Assert.Equal(Accessibility.Public, p1get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1get)); var p2 = i1.GetMember<PropertySymbol>("P2"); var p2set = p2.SetMethod; Assert.False(p2.IsAbstract); Assert.False(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.True(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2)); Assert.False(p2set.IsAbstract); Assert.False(p2set.IsVirtual); Assert.False(p2set.IsMetadataVirtual()); Assert.False(p2set.IsSealed); Assert.True(p2set.IsStatic); Assert.False(p2set.IsExtern); Assert.False(p2set.IsAsync); Assert.False(p2set.IsOverride); Assert.Equal(Accessibility.Public, p2set.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2set)); var p3 = i1.GetMember<PropertySymbol>("P3"); var p3get = p3.GetMethod; Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.False(p3.IsSealed); Assert.True(p3.IsStatic); Assert.False(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); Assert.False(p3get.IsAbstract); Assert.False(p3get.IsVirtual); Assert.False(p3get.IsMetadataVirtual()); Assert.False(p3get.IsSealed); Assert.True(p3get.IsStatic); Assert.False(p3get.IsExtern); Assert.False(p3get.IsAsync); Assert.False(p3get.IsOverride); Assert.Equal(Accessibility.Public, p3get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3get)); } [Fact] public void PropertyModifiers_09() { var source1 = @" public interface I1 { private int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } } sealed void M() { var x = P1; } } public interface I2 { private int P2 { get { System.Console.WriteLine(""get_P2""); return 0; } set { System.Console.WriteLine(""set_P2""); } } sealed void M() { P2 = P2; } } public interface I3 { private int P3 { set { System.Console.WriteLine(""set_P3""); } } sealed void M() { P3 = 0; } } public interface I4 { private int P4 { get => GetP4(); } private int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } sealed void M() { var x = P4; } } public interface I5 { private int P5 { get => GetP5(); set => System.Console.WriteLine(""set_P5""); } private int GetP5() { System.Console.WriteLine(""get_P5""); return 0; } sealed void M() { P5 = P5; } } public interface I6 { private int P6 { set => System.Console.WriteLine(""set_P6""); } sealed void M() { P6 = 0; } } public interface I7 { private int P7 => GetP7(); private int GetP7() { System.Console.WriteLine(""get_P7""); return 0; } sealed void M() { var x = P7; } } class Test1 : I1, I2, I3, I4, I5, I6, I7 { static void Main() { I1 x1 = new Test1(); x1.M(); I2 x2 = new Test1(); x2.M(); I3 x3 = new Test1(); x3.M(); I4 x4 = new Test1(); x4.M(); I5 x5 = new Test1(); x5.M(); I6 x6 = new Test1(); x6.M(); I7 x7 = new Test1(); x7.M(); } } "; ValidatePropertyModifiers_09(source1); } private void ValidatePropertyModifiers_09(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 get_P2 set_P2 set_P3 get_P4 get_P5 set_P5 set_P6 get_P7 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); for (int i = 1; i <= 7; i++) { var i1 = m.GlobalNamespace.GetTypeMember("I" + i); var p1 = GetSingleProperty(i1); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Private, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); switch (i) { case 3: case 6: Assert.Null(p1.GetMethod); ValidateAccessor(p1.SetMethod); break; case 1: case 4: case 7: Assert.Null(p1.SetMethod); ValidateAccessor(p1.GetMethod); break; default: ValidateAccessor(p1.GetMethod); ValidateAccessor(p1.SetMethod); break; } void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } } [Fact] public void PropertyModifiers_10() { var source1 = @" public interface I1 { abstract private int P1 { get; } virtual private int P2 => 0; sealed private int P3 { get => 0; set {} } private int P4 {get;} = 0; } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics( // (4,26): error CS0621: 'I1.P1': virtual or abstract members cannot be private // abstract private int P1 { get; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "P1").WithArguments("I1.P1").WithLocation(4, 26), // (6,25): error CS0621: 'I1.P2': virtual or abstract members cannot be private // virtual private int P2 => 0; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P2").WithArguments("I1.P2").WithLocation(6, 25), // (8,24): error CS0238: 'I1.P3' cannot be sealed because it is not an override // sealed private int P3 Diagnostic(ErrorCode.ERR_SealedNonOverride, "P3").WithArguments("I1.P3").WithLocation(8, 24), // (14,17): error CS8053: Instance properties in interfaces cannot have initializers. // private int P4 {get;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P4").WithArguments("I1.P4").WithLocation(14, 17), // (14,21): error CS0501: 'I1.P4.get' must declare a body because it is not marked abstract, extern, or partial // private int P4 {get;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.P4.get").WithLocation(14, 21), // (17,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(17, 15) ); ValidatePropertyModifiers_10(compilation1); } private static void ValidatePropertyModifiers_10(CSharpCompilation compilation1) { var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMembers().OfType<PropertySymbol>().ElementAt(0); var p1get = p1.GetMethod; Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Private, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.True(p1get.IsAbstract); Assert.False(p1get.IsVirtual); Assert.True(p1get.IsMetadataVirtual()); Assert.False(p1get.IsSealed); Assert.False(p1get.IsStatic); Assert.False(p1get.IsExtern); Assert.False(p1get.IsAsync); Assert.False(p1get.IsOverride); Assert.Equal(Accessibility.Private, p1get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1get)); var p2 = i1.GetMembers().OfType<PropertySymbol>().ElementAt(1); var p2get = p2.GetMethod; Assert.False(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Private, p2.DeclaredAccessibility); Assert.Same(p2, test1.FindImplementationForInterfaceMember(p2)); Assert.False(p2get.IsAbstract); Assert.True(p2get.IsVirtual); Assert.True(p2get.IsMetadataVirtual()); Assert.False(p2get.IsSealed); Assert.False(p2get.IsStatic); Assert.False(p2get.IsExtern); Assert.False(p2get.IsAsync); Assert.False(p2get.IsOverride); Assert.Equal(Accessibility.Private, p2get.DeclaredAccessibility); Assert.Same(p2get, test1.FindImplementationForInterfaceMember(p2get)); var p3 = i1.GetMembers().OfType<PropertySymbol>().ElementAt(2); Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.True(p3.IsSealed); Assert.False(p3.IsStatic); Assert.False(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Private, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.GetMethod); ValidateP3Accessor(p3.SetMethod); void ValidateP3Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.True(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } var p4 = i1.GetMembers().OfType<PropertySymbol>().ElementAt(3); var p4get = p4.GetMethod; Assert.False(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.False(p4.IsStatic); Assert.False(p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Private, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); Assert.False(p4get.IsAbstract); Assert.False(p4get.IsVirtual); Assert.False(p4get.IsMetadataVirtual()); Assert.False(p4get.IsSealed); Assert.False(p4get.IsStatic); Assert.False(p4get.IsExtern); Assert.False(p4get.IsAsync); Assert.False(p4get.IsOverride); Assert.Equal(Accessibility.Private, p4get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4get)); } [Fact] public void PropertyModifiers_11_01() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} sealed void Test() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_01(source1, source2, Accessibility.Internal, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } private void ValidatePropertyModifiers_11_01(string source1, string source2, Accessibility accessibility, DiagnosticDescription[] expected1, params DiagnosticDescription[] expected2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected1); ValidatePropertyModifiers_11(compilation1.SourceModule, accessibility); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidatePropertyModifiers_11(m, accessibility)).VerifyDiagnostics(); ValidatePropertyModifiers_11(compilation1.SourceModule, accessibility); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var p1 = GetSingleProperty(i1); var p1get = p1.GetMethod; var p1set = p1.SetMethod; ValidatePropertyModifiers_11(p1, accessibility); ValidatePropertyAccessorModifiers_11(p1get, accessibility); ValidatePropertyAccessorModifiers_11(p1set, accessibility); } var source3 = @" class Test2 : I1 { } "; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected1); ValidatePropertyModifiers_11(compilation3.SourceModule, accessibility); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidatePropertyModifiers_11(m, accessibility)).VerifyDiagnostics(); ValidatePropertyModifiers_11(compilation3.SourceModule, accessibility); var compilation5 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics(expected2); ValidatePropertyNotImplemented_11(compilation5, "Test2"); } } private static void ValidatePropertyModifiers_11(ModuleSymbol m, Accessibility accessibility) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var p1 = GetSingleProperty(i1); var test1P1 = GetSingleProperty(test1); var p1get = p1.GetMethod; var p1set = p1.SetMethod; ValidatePropertyModifiers_11(p1, accessibility); ValidatePropertyAccessorModifiers_11(p1get, accessibility); ValidatePropertyAccessorModifiers_11(p1set, accessibility); Assert.Same(test1P1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test1P1.GetMethod, test1.FindImplementationForInterfaceMember(p1get)); Assert.Same(test1P1.SetMethod, test1.FindImplementationForInterfaceMember(p1set)); } private static void ValidatePropertyModifiers_11(PropertySymbol p1, Accessibility accessibility) { Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(accessibility, p1.DeclaredAccessibility); } private static void ValidatePropertyAccessorModifiers_11(MethodSymbol m1, Accessibility accessibility) { Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(accessibility, m1.DeclaredAccessibility); } private static void ValidatePropertyNotImplemented_11(CSharpCompilation compilation, string className) { var test2 = compilation.GetTypeByMetadataName(className); var i1 = compilation.GetTypeByMetadataName("I1"); var p1 = GetSingleProperty(i1); Assert.Null(test2.FindImplementationForInterfaceMember(p1)); Assert.Null(test2.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p1.SetMethod)); } [Fact] public void PropertyModifiers_11_02() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) ); } private void ValidatePropertyModifiers_11_02(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); ValidatePropertyImplementation_11(compilation1.SourceModule); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidatePropertyImplementation_11(m)).VerifyDiagnostics(); ValidatePropertyImplementation_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected); ValidatePropertyImplementation_11(compilation3.SourceModule); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidatePropertyImplementation_11(m)).VerifyDiagnostics(); ValidatePropertyImplementation_11(compilation3.SourceModule); } } private static void ValidatePropertyImplementation_11(ModuleSymbol m) { ValidatePropertyImplementation_11(m, implementedByBase: false); } private static void ValidatePropertyImplementationByBase_11(ModuleSymbol m) { ValidatePropertyImplementation_11(m, implementedByBase: true); } private static void ValidatePropertyImplementation_11(ModuleSymbol m, bool implementedByBase) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var p1 = GetSingleProperty(i1); var test1P1 = GetSingleProperty(implementedByBase ? test1.BaseTypeNoUseSiteDiagnostics : test1); var p1get = p1.GetMethod; var p1set = p1.SetMethod; Assert.Same(test1P1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test1P1.GetMethod, test1.FindImplementationForInterfaceMember(p1get)); Assert.Same(test1P1.SetMethod, test1.FindImplementationForInterfaceMember(p1set)); var i2 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I2").SingleOrDefault(); Assert.True(test1P1.GetMethod.IsMetadataVirtual()); Assert.True(test1P1.SetMethod.IsMetadataVirtual()); } [Fact] public void PropertyModifiers_11_03() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.Standard, // (9,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // int I1.P1 Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(9, 12) ); } private void ValidatePropertyModifiers_11_03(string source1, string source2, TargetFramework targetFramework, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, targetFramework: targetFramework, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: !(targetFramework == TargetFramework.Standard || ExecutionConditionUtil.IsMonoOrCoreClr) ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementation_11); ValidatePropertyImplementation_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: targetFramework, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, targetFramework: targetFramework, parseOptions: TestOptions.Regular); compilation3.VerifyDiagnostics(expected); if (expected.Length == 0) { CompileAndVerify(compilation3, expectedOutput: !(targetFramework == TargetFramework.Standard || ExecutionConditionUtil.IsMonoOrCoreClr) ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementation_11); } ValidatePropertyImplementation_11(compilation3.SourceModule); } } [Fact] public void PropertyModifiers_11_04() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_11_05() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_11_06() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test3()); } public abstract int P1 {get; set;} } class Test3 : Test1 { public override int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_11_07() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallP1(new Test1()); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int P1 {get; set;} } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_11_08() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_08(source1, source2); } private void ValidatePropertyModifiers_11_08(string source1, string source2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: @"Test2.get_P1 Test2.set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationByBase_11); ValidatePropertyImplementationByBase_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation3, expectedOutput: @"Test2.get_P1 Test2.set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationByBase_11); ValidatePropertyImplementationByBase_11(compilation3.SourceModule); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation4, expectedOutput: @"Test2.get_P1 Test2.set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationByBase_11); ValidatePropertyImplementationByBase_11(compilation4.SourceModule); } [Fact] public void PropertyModifiers_11_09() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_09(source1, source2, // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.P1'. 'Test1.P1' cannot implement 'I1.P1' because it does not have the matching return type of 'int'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.P1", "Test1.P1", "int").WithLocation(2, 15) ); } private void ValidatePropertyModifiers_11_09(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics(expected); ValidatePropertyNotImplemented_11(compilation1, "Test1"); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation3.VerifyDiagnostics(expected); ValidatePropertyNotImplemented_11(compilation3, "Test1"); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation4.VerifyDiagnostics(expected); ValidatePropertyNotImplemented_11(compilation4, "Test1"); } [Fact] public void PropertyModifiers_11_10() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} sealed void Test() { P1 = P1; } } "; var source2 = @" public class Test2 : I1 { public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_10(source1, source2, // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.set'. 'Test2.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.set", "Test2.P1.set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.get'. 'Test2.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.get", "Test2.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } private void ValidatePropertyModifiers_11_10(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(expected); ValidatePropertyImplementationByBase_11(compilation1.SourceModule); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidatePropertyImplementationByBase_11(m)).VerifyDiagnostics(); ValidatePropertyImplementationByBase_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(expected); ValidatePropertyImplementationByBase_11(compilation3.SourceModule); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidatePropertyImplementationByBase_11(m)).VerifyDiagnostics(); ValidatePropertyImplementationByBase_11(compilation3.SourceModule); } } [Fact] public void PropertyModifiers_11_11() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} sealed void Test() { P1 = P1; } } public class Test2 : I1 { public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_11(source1, source2, // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.get'. 'Test2.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.get", "Test2.P1.get", "9.0", "10.0").WithLocation(11, 22), // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.set'. 'Test2.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.set", "Test2.P1.set", "9.0", "10.0").WithLocation(11, 22) ); } private void ValidatePropertyModifiers_11_11(string source1, string source2, params DiagnosticDescription[] expected) { var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, assemblyName: "PropertyModifiers_11_11"); compilation2.VerifyDiagnostics(expected); compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp, assemblyName: "PropertyModifiers_11_11"); compilation2.VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidatePropertyImplementationByBase_11(m)).VerifyDiagnostics(); ValidatePropertyImplementationByBase_11(compilation3.SourceModule); } [Fact] public void PropertyModifiers_12() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMember<PropertySymbol>("P1"); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Null(test1.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(p1.SetMethod)); } [Fact] public void PropertyModifiers_13() { var source1 = @" public interface I1 { public sealed int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } } } public interface I2 { public sealed int P2 { get { System.Console.WriteLine(""get_P2""); return 0; } set { System.Console.WriteLine(""set_P2""); } } } public interface I3 { public sealed int P3 { set { System.Console.WriteLine(""set_P3""); } } } public interface I4 { public sealed int P4 { get => GetP4(); } private int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } } public interface I5 { public sealed int P5 { get => GetP5(); set => System.Console.WriteLine(""set_P5""); } private int GetP5() { System.Console.WriteLine(""get_P5""); return 0; } } public interface I6 { public sealed int P6 { set => System.Console.WriteLine(""set_P6""); } } public interface I7 { public sealed int P7 => GetP7(); private int GetP7() { System.Console.WriteLine(""get_P7""); return 0; } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); var x = i1.P1; I2 i2 = new Test2(); i2.P2 = i2.P2; I3 i3 = new Test3(); i3.P3 = x; I4 i4 = new Test4(); x = i4.P4; I5 i5 = new Test5(); i5.P5 = i5.P5; I6 i6 = new Test6(); i6.P6 = x; I7 i7 = new Test7(); x = i7.P7; } public int P1 => throw null; } class Test2 : I2 { public int P2 { get => throw null; set => throw null; } } class Test3 : I3 { public int P3 { set => throw null; } } class Test4 : I4 { public int P4 { get => throw null; } } class Test5 : I5 { public int P5 { get => throw null; set => throw null; } } class Test6 : I6 { public int P6 { set => throw null; } } class Test7 : I7 { public int P7 => throw null; } "; ValidatePropertyModifiers_13(source1); } private void ValidatePropertyModifiers_13(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate(ModuleSymbol m) { for (int i = 1; i <= 7; i++) { var test1 = m.GlobalNamespace.GetTypeMember("Test" + i); var i1 = m.GlobalNamespace.GetTypeMember("I" + i); var p1 = GetSingleProperty(i1); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); switch (i) { case 3: case 6: Assert.Null(p1.GetMethod); ValidateAccessor(p1.SetMethod); break; case 1: case 4: case 7: Assert.Null(p1.SetMethod); ValidateAccessor(p1.GetMethod); break; default: ValidateAccessor(p1.GetMethod); ValidateAccessor(p1.SetMethod); break; } void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 get_P2 set_P2 set_P3 get_P4 get_P5 set_P5 set_P6 get_P7 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); } [Fact] public void PropertyModifiers_14() { var source1 = @" public interface I1 { public sealed int P1 {get;} = 0; } public interface I2 { abstract sealed int P2 {get;} } public interface I3 { virtual sealed int P3 { set {} } } class Test1 : I1, I2, I3 { int I1.P1 { get => throw null; } int I2.P2 { get => throw null; } int I3.P3 { set => throw null; } } class Test2 : I1, I2, I3 {} "; ValidatePropertyModifiers_14(source1, // (4,23): error CS8053: Instance properties in interfaces cannot have initializers. // public sealed int P1 {get;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P1").WithArguments("I1.P1").WithLocation(4, 23), // (4,27): error CS0501: 'I1.P1.get' must declare a body because it is not marked abstract, extern, or partial // public sealed int P1 {get;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.P1.get").WithLocation(4, 27), // (8,25): error CS0238: 'I2.P2' cannot be sealed because it is not an override // abstract sealed int P2 {get;} Diagnostic(ErrorCode.ERR_SealedNonOverride, "P2").WithArguments("I2.P2").WithLocation(8, 25), // (12,24): error CS0238: 'I3.P3' cannot be sealed because it is not an override // virtual sealed int P3 Diagnostic(ErrorCode.ERR_SealedNonOverride, "P3").WithArguments("I3.P3").WithLocation(12, 24), // (20,12): error CS0539: 'Test1.P1' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.P1 { get => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("Test1.P1").WithLocation(20, 12), // (21,12): error CS0539: 'Test1.P2' in explicit interface declaration is not found among members of the interface that can be implemented // int I2.P2 { get => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P2").WithArguments("Test1.P2").WithLocation(21, 12), // (22,12): error CS0539: 'Test1.P3' in explicit interface declaration is not found among members of the interface that can be implemented // int I3.P3 { set => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test1.P3").WithLocation(22, 12) ); } private void ValidatePropertyModifiers_14(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var p1 = GetSingleProperty(compilation1, "I1"); var p1get = p1.GetMethod; Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Null(test2.FindImplementationForInterfaceMember(p1)); Assert.False(p1get.IsAbstract); Assert.False(p1get.IsVirtual); Assert.False(p1get.IsMetadataVirtual()); Assert.False(p1get.IsSealed); Assert.False(p1get.IsStatic); Assert.False(p1get.IsExtern); Assert.False(p1get.IsAsync); Assert.False(p1get.IsOverride); Assert.Equal(Accessibility.Public, p1get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1get)); Assert.Null(test2.FindImplementationForInterfaceMember(p1get)); var p2 = GetSingleProperty(compilation1, "I2"); var test1P2 = test1.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); var p2get = p2.GetMethod; Assert.True(p2.IsAbstract); Assert.False(p2.IsVirtual); Assert.True(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2)); Assert.Null(test2.FindImplementationForInterfaceMember(p2)); Assert.True(p2get.IsAbstract); Assert.False(p2get.IsVirtual); Assert.True(p2get.IsMetadataVirtual()); Assert.True(p2get.IsSealed); Assert.False(p2get.IsStatic); Assert.False(p2get.IsExtern); Assert.False(p2get.IsAsync); Assert.False(p2get.IsOverride); Assert.Equal(Accessibility.Public, p2get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2get)); Assert.Null(test2.FindImplementationForInterfaceMember(p2get)); var p3 = GetSingleProperty(compilation1, "I3"); var test1P3 = test1.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I3.")).Single(); var p3set = p3.SetMethod; Assert.False(p3.IsAbstract); Assert.True(p3.IsVirtual); Assert.True(p3.IsSealed); Assert.False(p3.IsStatic); Assert.False(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); Assert.False(p3set.IsAbstract); Assert.True(p3set.IsVirtual); Assert.True(p3set.IsMetadataVirtual()); Assert.True(p3set.IsSealed); Assert.False(p3set.IsStatic); Assert.False(p3set.IsExtern); Assert.False(p3set.IsAsync); Assert.False(p3set.IsOverride); Assert.Equal(Accessibility.Public, p3set.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3set)); Assert.Null(test2.FindImplementationForInterfaceMember(p3set)); } [Fact] public void PropertyModifiers_15() { var source1 = @" public interface I0 { abstract virtual int P0 { get; set; } } public interface I1 { abstract virtual int P1 { get { throw null; } } } public interface I2 { virtual abstract int P2 { get { throw null; } set { throw null; } } } public interface I3 { abstract virtual int P3 { set { throw null; } } } public interface I4 { abstract virtual int P4 { get => throw null; } } public interface I5 { abstract virtual int P5 { get => throw null; set => throw null; } } public interface I6 { abstract virtual int P6 { set => throw null; } } public interface I7 { abstract virtual int P7 => throw null; } public interface I8 { abstract virtual int P8 {get;} = 0; } class Test1 : I0, I1, I2, I3, I4, I5, I6, I7, I8 { int I0.P0 { get { throw null; } set { throw null; } } int I1.P1 { get { throw null; } } int I2.P2 { get { throw null; } set { throw null; } } int I3.P3 { set { throw null; } } int I4.P4 { get { throw null; } } int I5.P5 { get { throw null; } set { throw null; } } int I6.P6 { set { throw null; } } int I7.P7 { get { throw null; } } int I8.P8 { get { throw null; } } } class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 {} "; ValidatePropertyModifiers_15(source1, // (4,26): error CS0503: The abstract property 'I0.P0' cannot be marked virtual // abstract virtual int P0 { get; set; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P0").WithArguments("property", "I0.P0").WithLocation(4, 26), // (8,26): error CS0503: The abstract property 'I1.P1' cannot be marked virtual // abstract virtual int P1 { get { throw null; } } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P1").WithArguments("property", "I1.P1").WithLocation(8, 26), // (8,31): error CS0500: 'I1.P1.get' cannot declare a body because it is marked abstract // abstract virtual int P1 { get { throw null; } } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.P1.get").WithLocation(8, 31), // (12,26): error CS0503: The abstract property 'I2.P2' cannot be marked virtual // virtual abstract int P2 Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P2").WithArguments("property", "I2.P2").WithLocation(12, 26), // (14,9): error CS0500: 'I2.P2.get' cannot declare a body because it is marked abstract // get { throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.P2.get").WithLocation(14, 9), // (15,9): error CS0500: 'I2.P2.set' cannot declare a body because it is marked abstract // set { throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.P2.set").WithLocation(15, 9), // (20,26): error CS0503: The abstract property 'I3.P3' cannot be marked virtual // abstract virtual int P3 { set { throw null; } } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P3").WithArguments("property", "I3.P3").WithLocation(20, 26), // (20,31): error CS0500: 'I3.P3.set' cannot declare a body because it is marked abstract // abstract virtual int P3 { set { throw null; } } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I3.P3.set").WithLocation(20, 31), // (24,26): error CS0503: The abstract property 'I4.P4' cannot be marked virtual // abstract virtual int P4 { get => throw null; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P4").WithArguments("property", "I4.P4").WithLocation(24, 26), // (24,31): error CS0500: 'I4.P4.get' cannot declare a body because it is marked abstract // abstract virtual int P4 { get => throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I4.P4.get").WithLocation(24, 31), // (28,26): error CS0503: The abstract property 'I5.P5' cannot be marked virtual // abstract virtual int P5 Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P5").WithArguments("property", "I5.P5").WithLocation(28, 26), // (30,9): error CS0500: 'I5.P5.get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I5.P5.get").WithLocation(30, 9), // (31,9): error CS0500: 'I5.P5.set' cannot declare a body because it is marked abstract // set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I5.P5.set").WithLocation(31, 9), // (36,26): error CS0503: The abstract property 'I6.P6' cannot be marked virtual // abstract virtual int P6 { set => throw null; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P6").WithArguments("property", "I6.P6").WithLocation(36, 26), // (36,31): error CS0500: 'I6.P6.set' cannot declare a body because it is marked abstract // abstract virtual int P6 { set => throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I6.P6.set").WithLocation(36, 31), // (40,26): error CS0503: The abstract property 'I7.P7' cannot be marked virtual // abstract virtual int P7 => throw null; Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P7").WithArguments("property", "I7.P7").WithLocation(40, 26), // (40,32): error CS0500: 'I7.P7.get' cannot declare a body because it is marked abstract // abstract virtual int P7 => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "throw null").WithArguments("I7.P7.get").WithLocation(40, 32), // (44,26): error CS0503: The abstract property 'I8.P8' cannot be marked virtual // abstract virtual int P8 {get;} = 0; Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P8").WithArguments("property", "I8.P8").WithLocation(44, 26), // (44,26): error CS8053: Instance properties in interfaces cannot have initializers. // abstract virtual int P8 {get;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P8").WithArguments("I8.P8").WithLocation(44, 26), // (90,15): error CS0535: 'Test2' does not implement interface member 'I0.P0' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I0").WithArguments("Test2", "I0.P0").WithLocation(90, 15), // (90,19): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(90, 19), // (90,23): error CS0535: 'Test2' does not implement interface member 'I2.P2' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I2.P2").WithLocation(90, 23), // (90,27): error CS0535: 'Test2' does not implement interface member 'I3.P3' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test2", "I3.P3").WithLocation(90, 27), // (90,31): error CS0535: 'Test2' does not implement interface member 'I4.P4' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test2", "I4.P4").WithLocation(90, 31), // (90,35): error CS0535: 'Test2' does not implement interface member 'I5.P5' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I5").WithArguments("Test2", "I5.P5").WithLocation(90, 35), // (90,39): error CS0535: 'Test2' does not implement interface member 'I6.P6' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I6").WithArguments("Test2", "I6.P6").WithLocation(90, 39), // (90,43): error CS0535: 'Test2' does not implement interface member 'I7.P7' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I7").WithArguments("Test2", "I7.P7").WithLocation(90, 43), // (90,47): error CS0535: 'Test2' does not implement interface member 'I8.P8' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I8").WithArguments("Test2", "I8.P8").WithLocation(90, 47) ); } private void ValidatePropertyModifiers_15(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); for (int i = 0; i <= 8; i++) { var i1 = compilation1.GetTypeByMetadataName("I" + i); var p2 = GetSingleProperty(i1); var test1P2 = test1.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith(i1.Name)).Single(); Assert.True(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Same(test1P2, test1.FindImplementationForInterfaceMember(p2)); Assert.Null(test2.FindImplementationForInterfaceMember(p2)); switch (i) { case 3: case 6: Assert.Null(p2.GetMethod); ValidateAccessor(p2.SetMethod, test1P2.SetMethod); break; case 1: case 4: case 7: case 8: Assert.Null(p2.SetMethod); ValidateAccessor(p2.GetMethod, test1P2.GetMethod); break; default: ValidateAccessor(p2.GetMethod, test1P2.GetMethod); ValidateAccessor(p2.SetMethod, test1P2.SetMethod); break; } void ValidateAccessor(MethodSymbol accessor, MethodSymbol implementedBy) { Assert.True(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(implementedBy, test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } } } [Fact] public void PropertyModifiers_16() { var source1 = @" public interface I1 { extern int P1 {get;} } public interface I2 { virtual extern int P2 {set;} } public interface I3 { static extern int P3 {get; set;} } public interface I4 { private extern int P4 {get;} } public interface I5 { extern sealed int P5 {set;} } class Test1 : I1, I2, I3, I4, I5 { } class Test2 : I1, I2, I3, I4, I5 { int I1.P1 => 0; int I2.P2 { set {} } } "; ValidatePropertyModifiers_16(source1, new DiagnosticDescription[] { // (4,16): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern int P1 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("extern", "7.3", "8.0").WithLocation(4, 16), // (8,24): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern int P2 {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P2").WithArguments("extern", "7.3", "8.0").WithLocation(8, 24), // (8,24): error CS8503: The modifier 'virtual' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern int P2 {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P2").WithArguments("virtual", "7.3", "8.0").WithLocation(8, 24), // (12,23): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static extern int P3 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P3").WithArguments("static", "7.3", "8.0").WithLocation(12, 23), // (12,23): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static extern int P3 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P3").WithArguments("extern", "7.3", "8.0").WithLocation(12, 23), // (16,24): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern int P4 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P4").WithArguments("private", "7.3", "8.0").WithLocation(16, 24), // (16,24): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern int P4 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P4").WithArguments("extern", "7.3", "8.0").WithLocation(16, 24), // (20,23): error CS8503: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed int P5 {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P5").WithArguments("sealed", "7.3", "8.0").WithLocation(20, 23), // (20,23): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed int P5 {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P5").WithArguments("extern", "7.3", "8.0").WithLocation(20, 23), // (8,28): warning CS0626: Method, operator, or accessor 'I2.P2.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern int P2 {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I2.P2.set").WithLocation(8, 28), // (12,27): warning CS0626: Method, operator, or accessor 'I3.P3.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I3.P3.get").WithLocation(12, 27), // (12,32): warning CS0626: Method, operator, or accessor 'I3.P3.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I3.P3.set").WithLocation(12, 32), // (16,28): warning CS0626: Method, operator, or accessor 'I4.P4.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern int P4 {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I4.P4.get").WithLocation(16, 28), // (20,27): warning CS0626: Method, operator, or accessor 'I5.P5.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed int P5 {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I5.P5.set").WithLocation(20, 27), // (4,20): warning CS0626: Method, operator, or accessor 'I1.P1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P1 {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.P1.get").WithLocation(4, 20) }, // (4,20): error CS8501: Target runtime doesn't support default interface implementation. // extern int P1 {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(4, 20), // (8,28): error CS8501: Target runtime doesn't support default interface implementation. // virtual extern int P2 {set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(8, 28), // (16,28): error CS8501: Target runtime doesn't support default interface implementation. // private extern int P4 {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(16, 28), // (20,27): error CS8501: Target runtime doesn't support default interface implementation. // extern sealed int P5 {set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(20, 27), // (8,28): warning CS0626: Method, operator, or accessor 'I2.P2.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern int P2 {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I2.P2.set").WithLocation(8, 28), // (12,27): error CS8701: Target runtime doesn't support default interface implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(12, 27), // (12,27): warning CS0626: Method, operator, or accessor 'I3.P3.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I3.P3.get").WithLocation(12, 27), // (12,32): error CS8701: Target runtime doesn't support default interface implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(12, 32), // (12,32): warning CS0626: Method, operator, or accessor 'I3.P3.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I3.P3.set").WithLocation(12, 32), // (16,28): warning CS0626: Method, operator, or accessor 'I4.P4.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern int P4 {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I4.P4.get").WithLocation(16, 28), // (20,27): warning CS0626: Method, operator, or accessor 'I5.P5.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed int P5 {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I5.P5.set").WithLocation(20, 27), // (4,20): warning CS0626: Method, operator, or accessor 'I1.P1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P1 {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.P1.get").WithLocation(4, 20) ); } private void ValidatePropertyModifiers_16(string source1, DiagnosticDescription[] expected1, params DiagnosticDescription[] expected2) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test2 = m.GlobalNamespace.GetTypeMember("Test2"); bool isSource = !(m is PEModuleSymbol); var p1 = GetSingleProperty(m, "I1"); var test2P1 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I1.")).Single(); var p1get = p1.GetMethod; Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.Equal(isSource, p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test2P1, test2.FindImplementationForInterfaceMember(p1)); Assert.False(p1get.IsAbstract); Assert.True(p1get.IsVirtual); Assert.True(p1get.IsMetadataVirtual()); Assert.False(p1get.IsSealed); Assert.False(p1get.IsStatic); Assert.Equal(isSource, p1get.IsExtern); Assert.False(p1get.IsAsync); Assert.False(p1get.IsOverride); Assert.Equal(Accessibility.Public, p1get.DeclaredAccessibility); Assert.Same(p1get, test1.FindImplementationForInterfaceMember(p1get)); Assert.Same(test2P1.GetMethod, test2.FindImplementationForInterfaceMember(p1get)); var p2 = GetSingleProperty(m, "I2"); var test2P2 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); var p2set = p2.SetMethod; Assert.False(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.Equal(isSource, p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Same(p2, test1.FindImplementationForInterfaceMember(p2)); Assert.Same(test2P2, test2.FindImplementationForInterfaceMember(p2)); Assert.False(p2set.IsAbstract); Assert.True(p2set.IsVirtual); Assert.True(p2set.IsMetadataVirtual()); Assert.False(p2set.IsSealed); Assert.False(p2set.IsStatic); Assert.Equal(isSource, p2set.IsExtern); Assert.False(p2set.IsAsync); Assert.False(p2set.IsOverride); Assert.Equal(Accessibility.Public, p2set.DeclaredAccessibility); Assert.Same(p2set, test1.FindImplementationForInterfaceMember(p2set)); Assert.Same(test2P2.SetMethod, test2.FindImplementationForInterfaceMember(p2set)); var i3 = m.ContainingAssembly.GetTypeByMetadataName("I3"); if ((object)i3 != null) { var p3 = GetSingleProperty(i3); Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.False(p3.IsSealed); Assert.True(p3.IsStatic); Assert.Equal(isSource, p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.GetMethod); ValidateP3Accessor(p3.SetMethod); void ValidateP3Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.Equal(isSource, accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } } var p4 = GetSingleProperty(m, "I4"); var p4get = p4.GetMethod; Assert.False(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.False(p4.IsStatic); Assert.Equal(isSource, p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Private, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); Assert.Null(test2.FindImplementationForInterfaceMember(p4)); Assert.False(p4get.IsAbstract); Assert.False(p4get.IsVirtual); Assert.False(p4get.IsMetadataVirtual()); Assert.False(p4get.IsSealed); Assert.False(p4get.IsStatic); Assert.Equal(isSource, p4get.IsExtern); Assert.False(p4get.IsAsync); Assert.False(p4get.IsOverride); Assert.Equal(Accessibility.Private, p4get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4get)); Assert.Null(test2.FindImplementationForInterfaceMember(p4get)); var p5 = GetSingleProperty(m, "I5"); var p5set = p5.SetMethod; Assert.False(p5.IsAbstract); Assert.False(p5.IsVirtual); Assert.False(p5.IsSealed); Assert.False(p5.IsStatic); Assert.Equal(isSource, p5.IsExtern); Assert.False(p5.IsOverride); Assert.Equal(Accessibility.Public, p5.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5)); Assert.Null(test2.FindImplementationForInterfaceMember(p5)); Assert.False(p5set.IsAbstract); Assert.False(p5set.IsVirtual); Assert.False(p5set.IsMetadataVirtual()); Assert.False(p5set.IsSealed); Assert.False(p5set.IsStatic); Assert.Equal(isSource, p5set.IsExtern); Assert.False(p5set.IsAsync); Assert.False(p5set.IsOverride); Assert.Equal(Accessibility.Public, p5set.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5set)); Assert.Null(test2.FindImplementationForInterfaceMember(p5set)); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(expected1); Validate(compilation2.SourceModule); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected2); Validate(compilation3.SourceModule); } [Fact] public void PropertyModifiers_17() { var source1 = @" public interface I1 { abstract extern int P1 {get;} } public interface I2 { extern int P2 => 0; } public interface I3 { static extern int P3 {get => 0; set => throw null;} } public interface I4 { private extern int P4 { get {throw null;} set {throw null;}} } public interface I5 { extern sealed int P5 {get;} = 0; } class Test1 : I1, I2, I3, I4, I5 { } class Test2 : I1, I2, I3, I4, I5 { int I1.P1 => 0; int I2.P2 => 0; int I3.P3 { get => 0; set => throw null;} int I4.P4 { get => 0; set => throw null;} int I5.P5 => 0; } "; ValidatePropertyModifiers_17(source1, // (4,25): error CS0180: 'I1.P1' cannot be both extern and abstract // abstract extern int P1 {get;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P1").WithArguments("I1.P1").WithLocation(4, 25), // (8,22): error CS0179: 'I2.P2.get' cannot be extern and declare a body // extern int P2 => 0; Diagnostic(ErrorCode.ERR_ExternHasBody, "0").WithArguments("I2.P2.get").WithLocation(8, 22), // (12,27): error CS0179: 'I3.P3.get' cannot be extern and declare a body // static extern int P3 {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("I3.P3.get").WithLocation(12, 27), // (12,37): error CS0179: 'I3.P3.set' cannot be extern and declare a body // static extern int P3 {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("I3.P3.set").WithLocation(12, 37), // (16,29): error CS0179: 'I4.P4.get' cannot be extern and declare a body // private extern int P4 { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("I4.P4.get").WithLocation(16, 29), // (16,47): error CS0179: 'I4.P4.set' cannot be extern and declare a body // private extern int P4 { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("I4.P4.set").WithLocation(16, 47), // (20,23): error CS8053: Instance properties in interfaces cannot have initializers. // extern sealed int P5 {get;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P5").WithArguments("I5.P5").WithLocation(20, 23), // (23,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(23, 15), // (31,12): error CS0539: 'Test2.P3' in explicit interface declaration is not found among members of the interface that can be implemented // int I3.P3 { get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test2.P3").WithLocation(31, 12), // (32,12): error CS0539: 'Test2.P4' in explicit interface declaration is not found among members of the interface that can be implemented // int I4.P4 { get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P4").WithArguments("Test2.P4").WithLocation(32, 12), // (33,12): error CS0539: 'Test2.P5' in explicit interface declaration is not found among members of the interface that can be implemented // int I5.P5 => 0; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P5").WithArguments("Test2.P5").WithLocation(33, 12), // (20,27): warning CS0626: Method, operator, or accessor 'I5.P5.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed int P5 {get;} = 0; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I5.P5.get").WithLocation(20, 27) ); } private void ValidatePropertyModifiers_17(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var p1 = GetSingleProperty(compilation1, "I1"); var test2P1 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I1.")).Single(); var p1get = p1.GetMethod; Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.True(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test2P1, test2.FindImplementationForInterfaceMember(p1)); Assert.True(p1get.IsAbstract); Assert.False(p1get.IsVirtual); Assert.True(p1get.IsMetadataVirtual()); Assert.False(p1get.IsSealed); Assert.False(p1get.IsStatic); Assert.True(p1get.IsExtern); Assert.False(p1get.IsAsync); Assert.False(p1get.IsOverride); Assert.Equal(Accessibility.Public, p1get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1get)); Assert.Same(test2P1.GetMethod, test2.FindImplementationForInterfaceMember(p1get)); var p2 = GetSingleProperty(compilation1, "I2"); var test2P2 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); var p2get = p2.GetMethod; Assert.False(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.True(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Same(p2, test1.FindImplementationForInterfaceMember(p2)); Assert.Same(test2P2, test2.FindImplementationForInterfaceMember(p2)); Assert.False(p2get.IsAbstract); Assert.True(p2get.IsVirtual); Assert.True(p2get.IsMetadataVirtual()); Assert.False(p2get.IsSealed); Assert.False(p2get.IsStatic); Assert.True(p2get.IsExtern); Assert.False(p2get.IsAsync); Assert.False(p2get.IsOverride); Assert.Equal(Accessibility.Public, p2get.DeclaredAccessibility); Assert.Same(p2get, test1.FindImplementationForInterfaceMember(p2get)); Assert.Same(test2P2.GetMethod, test2.FindImplementationForInterfaceMember(p2get)); var p3 = GetSingleProperty(compilation1, "I3"); var test2P3 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I3.")).Single(); Assert.False(p3.IsAbstract); Assert.Equal(p3.IsIndexer, p3.IsVirtual); Assert.False(p3.IsSealed); Assert.Equal(!p3.IsIndexer, p3.IsStatic); Assert.True(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Same(p3.IsIndexer ? p3 : null, test1.FindImplementationForInterfaceMember(p3)); Assert.Same(p3.IsIndexer ? test2P3 : null, test2.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.GetMethod, p3.IsIndexer ? test2P3.GetMethod : null); ValidateP3Accessor(p3.SetMethod, p3.IsIndexer ? test2P3.SetMethod : null); void ValidateP3Accessor(MethodSymbol accessor, MethodSymbol test2Implementation) { Assert.False(accessor.IsAbstract); Assert.Equal(p3.IsIndexer, accessor.IsVirtual); Assert.Equal(p3.IsIndexer, accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.Equal(!p3.IsIndexer, accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(p3.IsIndexer ? accessor : null, test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(test2Implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p4 = GetSingleProperty(compilation1, "I4"); Assert.False(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.False(p4.IsStatic); Assert.True(p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Private, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); Assert.Null(test2.FindImplementationForInterfaceMember(p4)); ValidateP4Accessor(p4.GetMethod); ValidateP4Accessor(p4.SetMethod); void ValidateP4Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p5 = GetSingleProperty(compilation1, "I5"); var p5get = p5.GetMethod; Assert.False(p5.IsAbstract); Assert.False(p5.IsVirtual); Assert.False(p5.IsSealed); Assert.False(p5.IsStatic); Assert.True(p5.IsExtern); Assert.False(p5.IsOverride); Assert.Equal(Accessibility.Public, p5.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5)); Assert.Null(test2.FindImplementationForInterfaceMember(p5)); Assert.False(p5get.IsAbstract); Assert.False(p5get.IsVirtual); Assert.False(p5get.IsMetadataVirtual()); Assert.False(p5get.IsSealed); Assert.False(p5get.IsStatic); Assert.True(p5get.IsExtern); Assert.False(p5get.IsAsync); Assert.False(p5get.IsOverride); Assert.Equal(Accessibility.Public, p5get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5get)); Assert.Null(test2.FindImplementationForInterfaceMember(p5get)); } [Fact] public void PropertyModifiers_18() { var source1 = @" public interface I1 { abstract int P1 {get => 0; set => throw null;} } public interface I2 { abstract private int P2 => 0; } public interface I3 { static extern int P3 {get; set;} } public interface I4 { abstract static int P4 { get {throw null;} set {throw null;}} } public interface I5 { override sealed int P5 {get;} = 0; } class Test1 : I1, I2, I3, I4, I5 { } class Test2 : I1, I2, I3, I4, I5 { int I1.P1 { get => 0; set => throw null;} int I2.P2 => 0; int I3.P3 { get => 0; set => throw null;} int I4.P4 { get => 0; set => throw null;} int I5.P5 => 0; } "; ValidatePropertyModifiers_18(source1, // (4,22): error CS0500: 'I1.P1.get' cannot declare a body because it is marked abstract // abstract int P1 {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.P1.get").WithLocation(4, 22), // (4,32): error CS0500: 'I1.P1.set' cannot declare a body because it is marked abstract // abstract int P1 {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I1.P1.set").WithLocation(4, 32), // (8,26): error CS0621: 'I2.P2': virtual or abstract members cannot be private // abstract private int P2 => 0; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P2").WithArguments("I2.P2").WithLocation(8, 26), // (8,32): error CS0500: 'I2.P2.get' cannot declare a body because it is marked abstract // abstract private int P2 => 0; Diagnostic(ErrorCode.ERR_AbstractHasBody, "0").WithArguments("I2.P2.get").WithLocation(8, 32), // (16,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P4 { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P4").WithArguments("abstract", "9.0", "preview").WithLocation(16, 25), // (16,30): error CS0500: 'I4.P4.get' cannot declare a body because it is marked abstract // abstract static int P4 { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I4.P4.get").WithLocation(16, 30), // (16,48): error CS0500: 'I4.P4.set' cannot declare a body because it is marked abstract // abstract static int P4 { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I4.P4.set").WithLocation(16, 48), // (20,25): error CS0106: The modifier 'override' is not valid for this item // override sealed int P5 {get;} = 0; Diagnostic(ErrorCode.ERR_BadMemberFlag, "P5").WithArguments("override").WithLocation(20, 25), // (20,25): error CS8053: Instance properties in interfaces cannot have initializers. // override sealed int P5 {get;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P5").WithArguments("I5.P5").WithLocation(20, 25), // (20,29): error CS0501: 'I5.P5.get' must declare a body because it is not marked abstract, extern, or partial // override sealed int P5 {get;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I5.P5.get").WithLocation(20, 29), // (23,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(23, 15), // (23,19): error CS0535: 'Test1' does not implement interface member 'I2.P2' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I2.P2").WithLocation(23, 19), // (30,12): error CS0122: 'I2.P2' is inaccessible due to its protection level // int I2.P2 => 0; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I2.P2").WithLocation(30, 12), // (31,12): error CS0539: 'Test2.P3' in explicit interface declaration is not found among members of the interface that can be implemented // int I3.P3 { get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test2.P3").WithLocation(31, 12), // (32,12): error CS0539: 'Test2.P4' in explicit interface declaration is not found among members of the interface that can be implemented // int I4.P4 { get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P4").WithArguments("Test2.P4").WithLocation(32, 12), // (33,12): error CS0539: 'Test2.P5' in explicit interface declaration is not found among members of the interface that can be implemented // int I5.P5 => 0; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P5").WithArguments("Test2.P5").WithLocation(33, 12), // (12,27): warning CS0626: Method, operator, or accessor 'I3.P3.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I3.P3.get").WithLocation(12, 27), // (12,32): warning CS0626: Method, operator, or accessor 'I3.P3.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I3.P3.set").WithLocation(12, 32), // (23,27): error CS0535: 'Test1' does not implement interface member 'I4.P4' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test1", "I4.P4").WithLocation(23, 27), // (27,27): error CS0535: 'Test2' does not implement interface member 'I4.P4' // class Test2 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test2", "I4.P4").WithLocation(27, 27) ); } private void ValidatePropertyModifiers_18(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var p1 = GetSingleProperty(compilation1, "I1"); var test2P1 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I1.")).Single(); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test2P1, test2.FindImplementationForInterfaceMember(p1)); ValidateP1Accessor(p1.GetMethod, test2P1.GetMethod); ValidateP1Accessor(p1.SetMethod, test2P1.SetMethod); void ValidateP1Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p2 = GetSingleProperty(compilation1, "I2"); var test2P2 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); var p2get = p2.GetMethod; Assert.True(p2.IsAbstract); Assert.False(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Private, p2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2)); Assert.Same(test2P2, test2.FindImplementationForInterfaceMember(p2)); Assert.True(p2get.IsAbstract); Assert.False(p2get.IsVirtual); Assert.True(p2get.IsMetadataVirtual()); Assert.False(p2get.IsSealed); Assert.False(p2get.IsStatic); Assert.False(p2get.IsExtern); Assert.False(p2get.IsAsync); Assert.False(p2get.IsOverride); Assert.Equal(Accessibility.Private, p2get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2get)); Assert.Same(test2P2.GetMethod, test2.FindImplementationForInterfaceMember(p2get)); var p3 = GetSingleProperty(compilation1, "I3"); var test2P3 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I3.")).Single(); Assert.False(p3.IsAbstract); Assert.Equal(p3.IsIndexer, p3.IsVirtual); Assert.False(p3.IsSealed); Assert.Equal(!p3.IsIndexer, p3.IsStatic); Assert.True(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Same(p3.IsIndexer ? p3 : null, test1.FindImplementationForInterfaceMember(p3)); Assert.Same(p3.IsIndexer ? test2P3 : null, test2.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.GetMethod, p3.IsIndexer ? test2P3.GetMethod : null); ValidateP3Accessor(p3.SetMethod, p3.IsIndexer ? test2P3.SetMethod : null); void ValidateP3Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.False(accessor.IsAbstract); Assert.Equal(p3.IsIndexer, accessor.IsVirtual); Assert.Equal(p3.IsIndexer, accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.Equal(!p3.IsIndexer, accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(p3.IsIndexer ? accessor : null, test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p4 = GetSingleProperty(compilation1, "I4"); var test2P4 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I4.")).Single(); Assert.True(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.Equal(!p4.IsIndexer, p4.IsStatic); Assert.False(p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Public, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); Assert.Same(p4.IsIndexer ? test2P4 : null, test2.FindImplementationForInterfaceMember(p4)); ValidateP4Accessor(p4.GetMethod, p4.IsIndexer ? test2P4.GetMethod : null); ValidateP4Accessor(p4.SetMethod, p4.IsIndexer ? test2P4.SetMethod : null); void ValidateP4Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.Equal(!p4.IsIndexer, accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p5 = GetSingleProperty(compilation1, "I5"); var p5get = p5.GetMethod; Assert.False(p5.IsAbstract); Assert.False(p5.IsVirtual); Assert.False(p5.IsSealed); Assert.False(p5.IsStatic); Assert.False(p5.IsExtern); Assert.False(p5.IsOverride); Assert.Equal(Accessibility.Public, p5.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5)); Assert.Null(test2.FindImplementationForInterfaceMember(p5)); Assert.False(p5get.IsAbstract); Assert.False(p5get.IsVirtual); Assert.False(p5get.IsMetadataVirtual()); Assert.False(p5get.IsSealed); Assert.False(p5get.IsStatic); Assert.False(p5get.IsExtern); Assert.False(p5get.IsAsync); Assert.False(p5get.IsOverride); Assert.Equal(Accessibility.Public, p5get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5get)); Assert.Null(test2.FindImplementationForInterfaceMember(p5get)); } [Fact] public void PropertyModifiers_20() { var source1 = @" public interface I1 { internal int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } void M2() {P1 = P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidatePropertyModifiers_20(source1, source2, Accessibility.Internal); } private void ValidatePropertyModifiers_20(string source1, string source2, Accessibility accessibility) { var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var p1 = GetSingleProperty(i1); var p1get = p1.GetMethod; var p1set = p1.SetMethod; ValidateProperty(p1); ValidateMethod(p1get); ValidateMethod(p1set); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(p1get, test1.FindImplementationForInterfaceMember(p1get)); Assert.Same(p1set, test1.FindImplementationForInterfaceMember(p1set)); } void ValidateProperty(PropertySymbol p1) { Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(accessibility, p1.DeclaredAccessibility); } void ValidateMethod(MethodSymbol m1) { Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(accessibility, m1.DeclaredAccessibility); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var p1 = GetSingleProperty(i1); var p1get = p1.GetMethod; var p1set = p1.SetMethod; ValidateProperty(p1); ValidateMethod(p1get); ValidateMethod(p1set); } var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation3.SourceModule); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation4.SourceModule); } [Fact] public void PropertyModifiers_21() { var source1 = @" public interface I1 { private static int P1 { get => throw null; set => throw null; } internal static int P2 { get => throw null; set => throw null; } public static int P3 { get => throw null; set => throw null; } static int P4 { get => throw null; set => throw null; } } class Test1 { static void Main() { int x; x = I1.P1; I1.P1 = x; x = I1.P2; I1.P2 = x; x = I1.P3; I1.P3 = x; x = I1.P4; I1.P4 = x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (18,16): error CS0122: 'I1.P1' is inaccessible due to its protection level // x = I1.P1; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(18, 16), // (19,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 = x; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(19, 12) ); var source2 = @" class Test2 { static void Main() { int x; x = I1.P1; I1.P1 = x; x = I1.P2; I1.P2 = x; x = I1.P3; I1.P3 = x; x = I1.P4; I1.P4 = x; } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (7,16): error CS0122: 'I1.P1' is inaccessible due to its protection level // x = I1.P1; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(7, 16), // (8,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 = x; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(8, 12), // (9,16): error CS0122: 'I1.P2' is inaccessible due to its protection level // x = I1.P2; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(9, 16), // (10,12): error CS0122: 'I1.P2' is inaccessible due to its protection level // I1.P2 = x; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(10, 12) ); } [Fact] public void PropertyModifiers_22() { var source1 = @" public interface I1 { public int P1 { internal get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int P2 { get { System.Console.WriteLine(""get_P2""); return 0; } internal set { System.Console.WriteLine(""set_P2""); } } } public interface I3 { int P3 { internal get => Test1.GetP3(); set => System.Console.WriteLine(""set_P3""); } } public interface I4 { int P4 { get => Test1.GetP4(); internal set => System.Console.WriteLine(""set_P4""); } } class Test1 : I1, I2, I3, I4 { static void Main() { I1 i1 = new Test1(); I2 i2 = new Test1(); I3 i3 = new Test1(); I4 i4 = new Test1(); i1.P1 = i1.P1; i2.P2 = i2.P2; i3.P3 = i3.P3; i4.P4 = i4.P4; } public static int GetP3() { System.Console.WriteLine(""get_P3""); return 0; } public static int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } } "; ValidatePropertyModifiers_22(source1, Accessibility.Internal); } private void ValidatePropertyModifiers_22(string source1, Accessibility accessibility) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 set_P2 get_P3 set_P3 get_P4 set_P4 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); for (int i = 1; i <= 4; i++) { var i1 = m.GlobalNamespace.GetTypeMember("I" + i); var p1 = GetSingleProperty(i1); Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); switch (i) { case 1: case 3: ValidateAccessor(p1.GetMethod, accessibility); ValidateAccessor(p1.SetMethod, Accessibility.Public); break; case 2: case 4: ValidateAccessor(p1.GetMethod, Accessibility.Public); ValidateAccessor(p1.SetMethod, accessibility); break; default: Assert.False(true); break; } void ValidateAccessor(MethodSymbol accessor, Accessibility access) { Assert.False(accessor.IsAbstract); Assert.Equal(accessor.DeclaredAccessibility != Accessibility.Private, accessor.IsVirtual); Assert.Equal(accessor.DeclaredAccessibility != Accessibility.Private, accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(access, accessor.DeclaredAccessibility); Assert.Same(accessor.DeclaredAccessibility == Accessibility.Private ? null : accessor, test1.FindImplementationForInterfaceMember(accessor)); } } } } [Fact] public void PropertyModifiers_23_00() { var source1 = @" public interface I1 {} public interface I3 { int P3 { private get { System.Console.WriteLine(""get_P3""); return 0; } set {System.Console.WriteLine(""set_P3"");} } void M2() { P3 = P3; } } public interface I4 { int P4 { get {System.Console.WriteLine(""get_P4""); return 0;} private set {System.Console.WriteLine(""set_P4"");} } void M2() { P4 = P4; } } public interface I5 { int P5 { private get => GetP5(); set => System.Console.WriteLine(""set_P5""); } private int GetP5() { System.Console.WriteLine(""get_P5""); return 0; } void M2() { P5 = P5; } } public interface I6 { int P6 { get => GetP6(); private set => System.Console.WriteLine(""set_P6""); } private int GetP6() { System.Console.WriteLine(""get_P6""); return 0; } void M2() { P6 = P6; } } "; var source2 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public int P3 { get { throw null; } set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public int P4 { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } set { throw null; } } } class Test5 : I5 { public int P5 { get { throw null; } set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public int P6 { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } set { throw null; } } } "; ValidatePropertyModifiers_23(source1, source2); var source3 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public int P3 { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public int P4 { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test5 : I5 { public int P5 { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public int P6 { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } "; ValidatePropertyModifiers_23(source1, source3); var source4 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public virtual int P3 { get { throw null; } set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public virtual int P4 { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } set { throw null; } } } class Test5 : I5 { public virtual int P5 { get { throw null; } set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public virtual int P6 { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } set { throw null; } } } "; ValidatePropertyModifiers_23(source1, source4); var source5 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public virtual int P3 { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public virtual int P4 { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test5 : I5 { public virtual int P5 { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public virtual int P6 { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } "; ValidatePropertyModifiers_23(source1, source5); var source6 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { int I3.P3 { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { int I4.P4 { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test5 : I5 { int I5.P5 { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { int I6.P6 { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } "; ValidatePropertyModifiers_23(source1, source6); var source7 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test33(); I4 i4 = new Test44(); I5 i5 = new Test55(); I6 i6 = new Test66(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } interface Test3 : I3 { int I3.P3 { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test33 : Test3 {} interface Test4 : I4 { int I4.P4 { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test44 : Test4 {} interface Test5 : I5 { int I5.P5 { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test55 : Test5 {} interface Test6 : I6 { int I6.P6 { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } class Test66 : Test6 {} "; ValidatePropertyModifiers_23(source1, source7); } private void ValidatePropertyModifiers_23(string source1, string source2) { foreach (var metadataImportOptions in new[] { MetadataImportOptions.All, MetadataImportOptions.Public }) { var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe.WithMetadataImportOptions(metadataImportOptions), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var im = test1.InterfacesNoUseSiteDiagnostics().Single().ContainingModule; ValidateProperty23(GetSingleProperty(im, "I3"), false, Accessibility.Private, Accessibility.Public, m.GlobalNamespace.GetTypeMember("Test3")); ValidateProperty23(GetSingleProperty(im, "I4"), false, Accessibility.Public, Accessibility.Private, m.GlobalNamespace.GetTypeMember("Test4")); ValidateProperty23(GetSingleProperty(im, "I5"), false, Accessibility.Private, Accessibility.Public, m.GlobalNamespace.GetTypeMember("Test5")); ValidateProperty23(GetSingleProperty(im, "I6"), false, Accessibility.Public, Accessibility.Private, m.GlobalNamespace.GetTypeMember("Test6")); } var expectedOutput = @" get_P3 Test3.set_P3 Test4.get_P4 set_P4 get_P5 Test5.set_P5 Test6.get_P6 set_P6 "; CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(metadataImportOptions), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateProperty23(GetSingleProperty(compilation2, "I3"), false, Accessibility.Private, Accessibility.Public); ValidateProperty23(GetSingleProperty(compilation2, "I4"), false, Accessibility.Public, Accessibility.Private); ValidateProperty23(GetSingleProperty(compilation2, "I5"), false, Accessibility.Private, Accessibility.Public); ValidateProperty23(GetSingleProperty(compilation2, "I6"), false, Accessibility.Public, Accessibility.Private); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe.WithMetadataImportOptions(metadataImportOptions), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(); Validate1(compilation3.SourceModule); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); } } } private static void ValidateProperty23(PropertySymbol p1, bool isAbstract, Accessibility getAccess, Accessibility setAccess, NamedTypeSymbol test1 = null) { Assert.Equal(isAbstract, p1.IsAbstract); Assert.NotEqual(isAbstract, p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); PropertySymbol implementingProperty = null; if ((object)test1 != null) { implementingProperty = GetSingleProperty(test1); Assert.Same(implementingProperty, test1.FindImplementationForInterfaceMember(p1)); if (implementingProperty.GetMethod?.ExplicitInterfaceImplementations.Length > 0 || implementingProperty.SetMethod?.ExplicitInterfaceImplementations.Length > 0) { Assert.Same(p1, implementingProperty.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(implementingProperty.ExplicitInterfaceImplementations); } } ValidateMethod23(p1, p1.GetMethod, isAbstract, getAccess, test1, implementingProperty?.GetMethod); ValidateMethod23(p1, p1.SetMethod, isAbstract, setAccess, test1, implementingProperty?.SetMethod); } private static void ValidateMethod23(PropertySymbol p1, MethodSymbol m1, bool isAbstract, Accessibility access, NamedTypeSymbol test1, MethodSymbol implementingMethod) { if (m1 is null) { Assert.Equal(Accessibility.Private, access); Assert.Equal(MetadataImportOptions.Public, ((PEModuleSymbol)p1.ContainingModule).ImportOptions); return; } Assert.Equal(isAbstract, m1.IsAbstract); Assert.NotEqual(isAbstract || access == Accessibility.Private, m1.IsVirtual); Assert.Equal(isAbstract || access != Accessibility.Private, m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(access, m1.DeclaredAccessibility); if ((object)test1 != null) { Assert.Same(access != Accessibility.Private ? implementingMethod : null, test1.FindImplementationForInterfaceMember(m1)); } } [Fact] public void PropertyModifiers_23_01() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} void M2() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_23(source1, source2, Accessibility.Internal, Accessibility.Public, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) ); } private void ValidatePropertyModifiers_23(string source1, string source2, Accessibility getAccess, Accessibility setAccess, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); Validate1(compilation1.SourceModule); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => Validate1(m)).VerifyDiagnostics(); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var im = test1.InterfacesNoUseSiteDiagnostics().Single().ContainingModule; ValidateProperty23(GetSingleProperty(im, "I1"), true, getAccess, setAccess, test1); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateProperty23(GetSingleProperty(compilation2, "I1"), true, getAccess, setAccess); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected); Validate1(compilation3.SourceModule); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => Validate1(m)).VerifyDiagnostics(); Validate1(compilation3.SourceModule); } } [Fact] public void PropertyModifiers_23_02() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_23_03() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.Standard, // (9,12): error CS0122: 'I1.P1.get' is inaccessible due to its protection level // int I1.P1 Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1.get").WithLocation(9, 12) ); } [Fact] public void PropertyModifiers_23_04() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_05() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_06() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test3()); } public abstract int P1 {get; set;} } class Test3 : Test1 { public override int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_07() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallP1(new Test1()); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int P1 {get; set;} } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_08() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_08(source1, source2); } [Fact] public void PropertyModifiers_23_09() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_09(source1, source2, // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.P1'. 'Test1.P1' cannot implement 'I1.P1' because it does not have the matching return type of 'int'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.P1", "Test1.P1", "int").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_23_10() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} sealed void Test() { P1 = P1; } } "; var source2 = @" public class Test2 : I1 { public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_10(source1, source2, // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.get'. 'Test2.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.get", "Test2.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_11() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} sealed void Test() { P1 = P1; } } public class Test2 : I1 { public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_11(source1, source2, // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.get'. 'Test2.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.get", "Test2.P1.get", "9.0", "10.0").WithLocation(11, 22) ); } [Fact] public void PropertyModifiers_23_51() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} void M2() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_23(source1, source2, Accessibility.Public, Accessibility.Internal, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_23_52() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_23_53() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.Standard, // (9,12): error CS0122: 'I1.P1.set' is inaccessible due to its protection level // int I1.P1 Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1.set").WithLocation(9, 12) ); } [Fact] public void PropertyModifiers_23_54() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_55() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_56() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test3()); } public abstract int P1 {get; set;} } class Test3 : Test1 { public override int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_57() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallP1(new Test1()); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int P1 {get; set;} } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_58() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_08(source1, source2); } [Fact] public void PropertyModifiers_23_59() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_09(source1, source2, // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.P1'. 'Test1.P1' cannot implement 'I1.P1' because it does not have the matching return type of 'int'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.P1", "Test1.P1", "int").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_23_60() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} sealed void Test() { P1 = P1; } } "; var source2 = @" public class Test2 : I1 { public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_10(source1, source2, // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.set'. 'Test2.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.set", "Test2.P1.set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_61() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} sealed void Test() { P1 = P1; } } public class Test2 : I1 { public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_11(source1, source2, // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.set'. 'Test2.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.set", "Test2.P1.set", "9.0", "10.0").WithLocation(11, 22) ); } [Fact] public void PropertyModifiers_24() { var source1 = @" public interface I1 { int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } internal set { System.Console.WriteLine(""set_P1""); } } void M2() {P1 = P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidatePropertyModifiers_24(source1, source2); } private void ValidatePropertyModifiers_24(string source1, string source2) { var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var p1 = GetSingleProperty(i1); var p1get = p1.GetMethod; var p1set = p1.SetMethod; ValidateProperty(p1); ValidateMethod(p1get, Accessibility.Public); ValidateMethod(p1set, Accessibility.Internal); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(p1get, test1.FindImplementationForInterfaceMember(p1get)); Assert.Same(p1set, test1.FindImplementationForInterfaceMember(p1set)); } void ValidateProperty(PropertySymbol p1) { Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); } void ValidateMethod(MethodSymbol m1, Accessibility access) { Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(access, m1.DeclaredAccessibility); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var p1 = GetSingleProperty(i1); var p1get = p1.GetMethod; var p1set = p1.SetMethod; ValidateProperty(p1); ValidateMethod(p1get, Accessibility.Public); ValidateMethod(p1set, Accessibility.Internal); } var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation3.SourceModule); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation4.SourceModule); } [Fact] public void PropertyModifiers_25() { var source1 = @" public interface I1 { static int P1 { private get => throw null; set => throw null; } static int P2 { internal get => throw null; set => throw null; } public static int P3 { get => throw null; private set => throw null; } static int P4 { get => throw null; internal set => throw null; } } class Test1 { static void Main() { int x; x = I1.P1; I1.P1 = x; x = I1.P2; I1.P2 = x; x = I1.P3; I1.P3 = x; x = I1.P4; I1.P4 = x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (18,13): error CS0271: The property or indexer 'I1.P1' cannot be used in this context because the get accessor is inaccessible // x = I1.P1; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "I1.P1").WithArguments("I1.P1").WithLocation(18, 13), // (23,9): error CS0272: The property or indexer 'I1.P3' cannot be used in this context because the set accessor is inaccessible // I1.P3 = x; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "I1.P3").WithArguments("I1.P3").WithLocation(23, 9) ); var source2 = @" class Test2 { static void Main() { int x; x = I1.P1; I1.P1 = x; x = I1.P2; I1.P2 = x; x = I1.P3; I1.P3 = x; x = I1.P4; I1.P4 = x; } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (7,13): error CS0271: The property or indexer 'I1.P1' cannot be used in this context because the get accessor is inaccessible // x = I1.P1; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "I1.P1").WithArguments("I1.P1").WithLocation(7, 13), // (9,13): error CS0271: The property or indexer 'I1.P2' cannot be used in this context because the get accessor is inaccessible // x = I1.P2; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "I1.P2").WithArguments("I1.P2").WithLocation(9, 13), // (12,9): error CS0272: The property or indexer 'I1.P3' cannot be used in this context because the set accessor is inaccessible // I1.P3 = x; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "I1.P3").WithArguments("I1.P3").WithLocation(12, 9), // (14,9): error CS0272: The property or indexer 'I1.P4' cannot be used in this context because the set accessor is inaccessible // I1.P4 = x; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "I1.P4").WithArguments("I1.P4").WithLocation(14, 9) ); } [Fact] public void PropertyModifiers_26() { var source1 = @" public interface I1 { abstract int P1 { private get; set; } abstract int P2 { get; private set; } abstract int P3 { internal get; } static int P4 {internal get;} = 0; static int P5 { internal get {throw null;} } static int P6 { internal set {throw null;} } static int P7 { internal get => throw null; } static int P8 { internal set => throw null; } static int P9 { internal get {throw null;} private set {throw null;}} static int P10 { internal get => throw null; private set => throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,31): error CS0442: 'I1.P1.get': abstract properties cannot have private accessors // abstract int P1 { private get; set; } Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I1.P1.get").WithLocation(4, 31), // (5,36): error CS0442: 'I1.P2.set': abstract properties cannot have private accessors // abstract int P2 { get; private set; } Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "set").WithArguments("I1.P2.set").WithLocation(5, 36), // (6,18): error CS0276: 'I1.P3': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // abstract int P3 { internal get; } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P3").WithArguments("I1.P3").WithLocation(6, 18), // (7,16): error CS0276: 'I1.P4': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // static int P4 {internal get;} = 0; Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P4").WithArguments("I1.P4").WithLocation(7, 16), // (8,16): error CS0276: 'I1.P5': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // static int P5 { internal get {throw null;} } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P5").WithArguments("I1.P5").WithLocation(8, 16), // (9,16): error CS0276: 'I1.P6': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // static int P6 { internal set {throw null;} } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P6").WithArguments("I1.P6").WithLocation(9, 16), // (10,16): error CS0276: 'I1.P7': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // static int P7 { internal get => throw null; } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P7").WithArguments("I1.P7").WithLocation(10, 16), // (11,16): error CS0276: 'I1.P8': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // static int P8 { internal set => throw null; } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P8").WithArguments("I1.P8").WithLocation(11, 16), // (12,16): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'I1.P9' // static int P9 { internal get {throw null;} private set {throw null;}} Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "P9").WithArguments("I1.P9").WithLocation(12, 16), // (13,16): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'I1.P10' // static int P10 { internal get => throw null; private set => throw null;} Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "P10").WithArguments("I1.P10").WithLocation(13, 16) ); } [Fact] public void PropertyModifiers_27() { var source1 = @" public interface I1 { int P3 { private get {throw null;} set {} } int P4 { get {throw null;} private set {} } } class Test1 : I1 { int I1.P3 { get {throw null;} set {} } int I1.P4 { get {throw null;} set {} } } interface ITest1 : I1 { int I1.P3 { get {throw null;} set {} } int I1.P4 { get {throw null;} set {} } } public interface I2 { int P5 { private get {throw null;} set {} } int P6 { get {throw null;} private set {} } class Test3 : I2 { int I2.P5 { get {throw null;} set {} } int I2.P6 { get {throw null;} set {} } } interface ITest3 : I2 { int I2.P5 { get {throw null;} set {} } int I2.P6 { get {throw null;} set {} } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // https://github.com/dotnet/roslyn/issues/34455: The wording "accessor not found in interface member" is somewhat misleading // in this scenario. The accessor is there, but cannot be implemented. Perhaps // the message should be adjusted. Should also check diagnostics for an attempt // to implement other sealed members. compilation1.VerifyDiagnostics( // (21,9): error CS0550: 'Test1.I1.P3.get' adds an accessor not found in interface member 'I1.P3' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("Test1.I1.P3.get", "I1.P3").WithLocation(21, 9), // (28,9): error CS0550: 'Test1.I1.P4.set' adds an accessor not found in interface member 'I1.P4' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("Test1.I1.P4.set", "I1.P4").WithLocation(28, 9), // (36,9): error CS0550: 'ITest1.I1.P3.get' adds an accessor not found in interface member 'I1.P3' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("ITest1.I1.P3.get", "I1.P3").WithLocation(36, 9), // (43,9): error CS0550: 'ITest1.I1.P4.set' adds an accessor not found in interface member 'I1.P4' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("ITest1.I1.P4.set", "I1.P4").WithLocation(43, 9), // (65,13): error CS0550: 'I2.Test3.I2.P5.get' adds an accessor not found in interface member 'I2.P5' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.Test3.I2.P5.get", "I2.P5").WithLocation(65, 13), // (72,13): error CS0550: 'I2.Test3.I2.P6.set' adds an accessor not found in interface member 'I2.P6' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.Test3.I2.P6.set", "I2.P6").WithLocation(72, 13), // (80,13): error CS0550: 'I2.ITest3.I2.P5.get' adds an accessor not found in interface member 'I2.P5' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.ITest3.I2.P5.get", "I2.P5").WithLocation(80, 13), // (87,13): error CS0550: 'I2.ITest3.I2.P6.set' adds an accessor not found in interface member 'I2.P6' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.ITest3.I2.P6.set", "I2.P6").WithLocation(87, 13) ); } [Fact] public void PropertyModifiers_28() { var source0 = @" public interface I1 { protected static int P1 { get { System.Console.WriteLine(""get_P1""); return 1; } set { System.Console.WriteLine(""set_P1""); } } protected internal static int P2 { get { System.Console.WriteLine(""get_P2""); return 2; } set { System.Console.WriteLine(""set_P2""); } } private protected static int P3 { get { System.Console.WriteLine(""get_P3""); return 3; } set { System.Console.WriteLine(""set_P3""); } } static int P4 { protected get { System.Console.WriteLine(""get_P4""); return 4; } set { System.Console.WriteLine(""set_P4""); } } static int P5 { get { System.Console.WriteLine(""get_P5""); return 5; } protected internal set { System.Console.WriteLine(""set_P5""); } } static int P6 { private protected get { System.Console.WriteLine(""get_P6""); return 6; } set { System.Console.WriteLine(""set_P6""); } } } "; var source1 = @" class Test1 : I1 { static void Main() { _ = I1.P1; I1.P1 = 11; _ = I1.P2; I1.P2 = 11; _ = I1.P3; I1.P3 = 11; _ = I1.P4; I1.P4 = 11; _ = I1.P5; I1.P5 = 11; _ = I1.P6; I1.P6 = 11; } } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 set_P2 get_P3 set_P3 get_P4 set_P4 get_P5 set_P5 get_P6 set_P6", symbolValidator: validate, verify: VerifyOnMonoOrCoreClr); validate(compilation1.SourceModule); var source2 = @" class Test1 { static void Main() { _ = I1.P2; I1.P2 = 11; I1.P4 = 11; _ = I1.P5; I1.P5 = 11; I1.P6 = 11; } } "; var compilation2 = CreateCompilation(source0 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P2 set_P2 set_P4 get_P5 set_P5 set_P6 ", verify: VerifyOnMonoOrCoreClr); var compilation3 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); var source3 = @" class Test1 : I1 { static void Main() { _ = I1.P1; I1.P1 = 11; _ = I1.P2; I1.P2 = 11; _ = I1.P4; I1.P4 = 11; _ = I1.P5; I1.P5 = 11; I1.P6 = 11; } } "; var source4 = @" class Test1 { static void Main() { I1.P4 = 11; _ = I1.P5; I1.P6 = 11; } } "; var source5 = @" class Test1 { static void Main() { _ = I1.P1; I1.P1 = 11; _ = I1.P2; I1.P2 = 11; _ = I1.P3; I1.P3 = 11; _ = I1.P4; I1.P5 = 11; _ = I1.P6; } } "; foreach (var reference in new[] { compilation3.ToMetadataReference(), compilation3.EmitToImageReference() }) { var compilation4 = CreateCompilation(source3, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 set_P2 get_P4 set_P4 get_P5 set_P5 set_P6 ", verify: VerifyOnMonoOrCoreClr); var compilation5 = CreateCompilation(source4, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"set_P4 get_P5 set_P6 ", verify: VerifyOnMonoOrCoreClr); var compilation6 = CreateCompilation(source5, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (6,16): error CS0122: 'I1.P1' is inaccessible due to its protection level // _ = I1.P1; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(6, 16), // (7,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 = 11; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(7, 12), // (8,16): error CS0122: 'I1.P2' is inaccessible due to its protection level // _ = I1.P2; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(8, 16), // (9,12): error CS0122: 'I1.P2' is inaccessible due to its protection level // I1.P2 = 11; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(9, 12), // (10,16): error CS0122: 'I1.P3' is inaccessible due to its protection level // _ = I1.P3; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(10, 16), // (11,12): error CS0122: 'I1.P3' is inaccessible due to its protection level // I1.P3 = 11; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(11, 12), // (12,13): error CS0271: The property or indexer 'I1.P4' cannot be used in this context because the get accessor is inaccessible // _ = I1.P4; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "I1.P4").WithArguments("I1.P4").WithLocation(12, 13), // (13,9): error CS0272: The property or indexer 'I1.P5' cannot be used in this context because the set accessor is inaccessible // I1.P5 = 11; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "I1.P5").WithArguments("I1.P5").WithLocation(13, 9), // (14,13): error CS0271: The property or indexer 'I1.P6' cannot be used in this context because the get accessor is inaccessible // _ = I1.P6; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "I1.P6").WithArguments("I1.P6").WithLocation(14, 13) ); var compilation7 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (10,16): error CS0122: 'I1.P3' is inaccessible due to its protection level // _ = I1.P3; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(10, 16), // (11,12): error CS0122: 'I1.P3' is inaccessible due to its protection level // I1.P3 = 11; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(11, 12), // (16,13): error CS0271: The property or indexer 'I1.P6' cannot be used in this context because the get accessor is inaccessible // _ = I1.P6; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "I1.P6").WithArguments("I1.P6").WithLocation(16, 13) ); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); foreach (var tuple in new[] { (name: "P1", access: Accessibility.Protected, getAccess: Accessibility.Protected, setAccess: Accessibility.Protected), (name: "P2", access: Accessibility.ProtectedOrInternal, getAccess: Accessibility.ProtectedOrInternal, setAccess: Accessibility.ProtectedOrInternal), (name: "P3", access: Accessibility.ProtectedAndInternal, getAccess: Accessibility.ProtectedAndInternal, setAccess: Accessibility.ProtectedAndInternal), (name: "P4", access: Accessibility.Public, getAccess: Accessibility.Protected, setAccess: Accessibility.Public), (name: "P5", access: Accessibility.Public, getAccess: Accessibility.Public, setAccess: Accessibility.ProtectedOrInternal), (name: "P6", access: Accessibility.Public, getAccess: Accessibility.ProtectedAndInternal, setAccess: Accessibility.Public)}) { var p1 = i1.GetMember<PropertySymbol>(tuple.name); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.True(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(tuple.access, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); validateAccessor(p1.GetMethod, tuple.getAccess); validateAccessor(p1.SetMethod, tuple.setAccess); } void validateAccessor(MethodSymbol accessor, Accessibility accessibility) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } [Fact] public void PropertyModifiers_29() { var source1 = @" public interface I1 { protected abstract int P1 {get; set;} sealed void Test() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_01(source1, source2, Accessibility.Protected, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_30() { var source1 = @" public interface I1 { protected internal abstract int P1 {get; set;} sealed void Test() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_01(source1, source2, Accessibility.ProtectedOrInternal, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_31() { var source1 = @" public interface I1 { private protected abstract int P1 {get; set;} sealed void Test() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_01(source1, source2, Accessibility.ProtectedAndInternal, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_32() { var source1 = @" public interface I1 { abstract int P1 {protected get; set;} void M2() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_23(source1, source2, Accessibility.Protected, Accessibility.Public, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_33() { var source1 = @" public interface I1 { abstract int P1 {protected internal get; set;} void M2() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_23(source1, source2, Accessibility.ProtectedOrInternal, Accessibility.Public, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_34() { var source1 = @" public interface I1 { abstract int P1 {get; private protected set;} void M2() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_23(source1, source2, Accessibility.Public, Accessibility.ProtectedAndInternal, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_35() { var source1 = @" public interface I1 { protected abstract int P1 {get; set;} public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.NetCoreApp); } [Fact] public void PropertyModifiers_36() { var source1 = @" public interface I1 { protected internal abstract int P1 {get; set;} public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.NetCoreApp); } [Fact] public void PropertyModifiers_37() { var source1 = @" public interface I1 { private protected abstract int P1 {get; set;} public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.NetCoreApp, // (9,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // int I1.P1 Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(9, 12) ); } [Fact] public void PropertyModifiers_38() { var source1 = @" public interface I1 { abstract int P1 {protected get; set;} public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.NetCoreApp); } [Fact] public void PropertyModifiers_39() { var source1 = @" public interface I1 { abstract int P1 {get; protected internal set;} public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.NetCoreApp); } [Fact] public void PropertyModifiers_40() { var source1 = @" public interface I1 { abstract int P1 { private protected get; set;} public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.NetCoreApp, // (9,12): error CS0122: 'I1.P1.get' is inaccessible due to its protection level // int I1.P1 Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1.get").WithLocation(9, 12) ); } [Fact] public void PropertyModifiers_41() { var source1 = @" public interface I1 { protected int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } void M2() {P1 = P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidatePropertyModifiers_20(source1, source2, Accessibility.Protected); } [Fact] public void PropertyModifiers_42() { var source1 = @" public interface I1 { protected internal int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } void M2() {P1 = P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidatePropertyModifiers_20(source1, source2, Accessibility.ProtectedOrInternal); } [Fact] public void PropertyModifiers_43() { var source1 = @" public interface I1 { private protected int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } void M2() {P1 = P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidatePropertyModifiers_20(source1, source2, Accessibility.ProtectedAndInternal); } [Fact] public void PropertyModifiers_44() { var source1 = @" public interface I1 { public int P1 { protected get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } static void Test(I1 i1) { i1.P1 = i1.P1; } } public interface I2 { int P2 { get { System.Console.WriteLine(""get_P2""); return 0; } protected set { System.Console.WriteLine(""set_P2""); } } static void Test(I2 i2) { i2.P2 = i2.P2; } } public interface I3 { int P3 { protected get => Test1.GetP3(); set => System.Console.WriteLine(""set_P3""); } static void Test(I3 i3) { i3.P3 = i3.P3; } } public interface I4 { int P4 { get => Test1.GetP4(); protected set => System.Console.WriteLine(""set_P4""); } static void Test(I4 i4) { i4.P4 = i4.P4; } } class Test1 : I1, I2, I3, I4 { static void Main() { I1.Test(new Test1()); I2.Test(new Test1()); I3.Test(new Test1()); I4.Test(new Test1()); } public static int GetP3() { System.Console.WriteLine(""get_P3""); return 0; } public static int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } } "; ValidatePropertyModifiers_22(source1, Accessibility.Protected); } [Fact] public void PropertyModifiers_45() { var source1 = @" public interface I1 { public int P1 { protected internal get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int P2 { get { System.Console.WriteLine(""get_P2""); return 0; } protected internal set { System.Console.WriteLine(""set_P2""); } } } public interface I3 { int P3 { protected internal get => Test1.GetP3(); set => System.Console.WriteLine(""set_P3""); } } public interface I4 { int P4 { get => Test1.GetP4(); protected internal set => System.Console.WriteLine(""set_P4""); } } class Test1 : I1, I2, I3, I4 { static void Main() { I1 i1 = new Test1(); I2 i2 = new Test1(); I3 i3 = new Test1(); I4 i4 = new Test1(); i1.P1 = i1.P1; i2.P2 = i2.P2; i3.P3 = i3.P3; i4.P4 = i4.P4; } public static int GetP3() { System.Console.WriteLine(""get_P3""); return 0; } public static int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } } "; ValidatePropertyModifiers_22(source1, Accessibility.ProtectedOrInternal); } [Fact] public void PropertyModifiers_46() { var source1 = @" public interface I1 { public int P1 { private protected get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } static void Test(I1 i1) { i1.P1 = i1.P1; } } public interface I2 { int P2 { get { System.Console.WriteLine(""get_P2""); return 0; } private protected set { System.Console.WriteLine(""set_P2""); } } static void Test(I2 i2) { i2.P2 = i2.P2; } } public interface I3 { int P3 { private protected get => Test1.GetP3(); set => System.Console.WriteLine(""set_P3""); } static void Test(I3 i3) { i3.P3 = i3.P3; } } public interface I4 { int P4 { get => Test1.GetP4(); private protected set => System.Console.WriteLine(""set_P4""); } static void Test(I4 i4) { i4.P4 = i4.P4; } } class Test1 : I1, I2, I3, I4 { static void Main() { I1.Test(new Test1()); I2.Test(new Test1()); I3.Test(new Test1()); I4.Test(new Test1()); } public static int GetP3() { System.Console.WriteLine(""get_P3""); return 0; } public static int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } } "; ValidatePropertyModifiers_22(source1, Accessibility.ProtectedAndInternal); } [Fact] public void IndexerModifiers_01() { var source1 = @" public interface I01{ public int this[int x] {get; set;} } public interface I02{ protected int this[int x] {get;} } public interface I03{ protected internal int this[int x] {set;} } public interface I04{ internal int this[int x] {get;} } public interface I05{ private int this[int x] {set;} } public interface I06{ static int this[int x] {get;} } public interface I07{ virtual int this[int x] {set;} } public interface I08{ sealed int this[int x] {get;} } public interface I09{ override int this[int x] {set;} } public interface I10{ abstract int this[int x] {get;} } public interface I11{ extern int this[int x] {get; set;} } public interface I12{ int this[int x] { public get; set;} } public interface I13{ int this[int x] { get; protected set;} } public interface I14{ int this[int x] { protected internal get; set;} } public interface I15{ int this[int x] { get; internal set;} } public interface I16{ int this[int x] { private get; set;} } public interface I17{ int this[int x] { private get;} } public interface I18{ private protected int this[int x] { get; } } public interface I19{ int this[int x] { get; private protected set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (6,48): error CS0501: 'I05.this[int].set' must declare a body because it is not marked abstract, extern, or partial // public interface I05{ private int this[int x] {set;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I05.this[int].set").WithLocation(6, 48), // (7,34): error CS0106: The modifier 'static' is not valid for this item // public interface I06{ static int this[int x] {get;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(7, 34), // (8,48): error CS0501: 'I07.this[int].set' must declare a body because it is not marked abstract, extern, or partial // public interface I07{ virtual int this[int x] {set;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I07.this[int].set").WithLocation(8, 48), // (9,47): error CS0501: 'I08.this[int].get' must declare a body because it is not marked abstract, extern, or partial // public interface I08{ sealed int this[int x] {get;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I08.this[int].get").WithLocation(9, 47), // (10,36): error CS0106: The modifier 'override' is not valid for this item // public interface I09{ override int this[int x] {set;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("override").WithLocation(10, 36), // (14,48): error CS0273: The accessibility modifier of the 'I12.this[int].get' accessor must be more restrictive than the property or indexer 'I12.this[int]' // public interface I12{ int this[int x] { public get; set;} } Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("I12.this[int].get", "I12.this[int]").WithLocation(14, 48), // (18,49): error CS0442: 'I16.this[int].get': abstract properties cannot have private accessors // public interface I16{ int this[int x] { private get; set;} } Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I16.this[int].get").WithLocation(18, 49), // (19,27): error CS0276: 'I17.this[int]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // public interface I17{ int this[int x] { private get;} } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I17.this[int]").WithLocation(19, 27), // (12,47): warning CS0626: Method, operator, or accessor 'I11.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I11.this[int].get").WithLocation(12, 47), // (12,52): warning CS0626: Method, operator, or accessor 'I11.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I11.this[int].set").WithLocation(12, 52) ); ValidateSymbolsIndexerModifiers_01(compilation1); } private static void ValidateSymbolsIndexerModifiers_01(CSharpCompilation compilation1) { var p01 = compilation1.GetMember<PropertySymbol>("I01.this[]"); Assert.True(p01.IsAbstract); Assert.False(p01.IsVirtual); Assert.False(p01.IsSealed); Assert.False(p01.IsStatic); Assert.False(p01.IsExtern); Assert.False(p01.IsOverride); Assert.Equal(Accessibility.Public, p01.DeclaredAccessibility); ValidateP01Accessor(p01.GetMethod); ValidateP01Accessor(p01.SetMethod); void ValidateP01Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } var p02 = compilation1.GetMember<PropertySymbol>("I02.this[]"); var p02get = p02.GetMethod; Assert.True(p02.IsAbstract); Assert.False(p02.IsVirtual); Assert.False(p02.IsSealed); Assert.False(p02.IsStatic); Assert.False(p02.IsExtern); Assert.False(p02.IsOverride); Assert.Equal(Accessibility.Protected, p02.DeclaredAccessibility); Assert.True(p02get.IsAbstract); Assert.False(p02get.IsVirtual); Assert.True(p02get.IsMetadataVirtual()); Assert.False(p02get.IsSealed); Assert.False(p02get.IsStatic); Assert.False(p02get.IsExtern); Assert.False(p02get.IsAsync); Assert.False(p02get.IsOverride); Assert.Equal(Accessibility.Protected, p02get.DeclaredAccessibility); var p03 = compilation1.GetMember<PropertySymbol>("I03.this[]"); var p03set = p03.SetMethod; Assert.True(p03.IsAbstract); Assert.False(p03.IsVirtual); Assert.False(p03.IsSealed); Assert.False(p03.IsStatic); Assert.False(p03.IsExtern); Assert.False(p03.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, p03.DeclaredAccessibility); Assert.True(p03set.IsAbstract); Assert.False(p03set.IsVirtual); Assert.True(p03set.IsMetadataVirtual()); Assert.False(p03set.IsSealed); Assert.False(p03set.IsStatic); Assert.False(p03set.IsExtern); Assert.False(p03set.IsAsync); Assert.False(p03set.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, p03set.DeclaredAccessibility); var p04 = compilation1.GetMember<PropertySymbol>("I04.this[]"); var p04get = p04.GetMethod; Assert.True(p04.IsAbstract); Assert.False(p04.IsVirtual); Assert.False(p04.IsSealed); Assert.False(p04.IsStatic); Assert.False(p04.IsExtern); Assert.False(p04.IsOverride); Assert.Equal(Accessibility.Internal, p04.DeclaredAccessibility); Assert.True(p04get.IsAbstract); Assert.False(p04get.IsVirtual); Assert.True(p04get.IsMetadataVirtual()); Assert.False(p04get.IsSealed); Assert.False(p04get.IsStatic); Assert.False(p04get.IsExtern); Assert.False(p04get.IsAsync); Assert.False(p04get.IsOverride); Assert.Equal(Accessibility.Internal, p04get.DeclaredAccessibility); var p05 = compilation1.GetMember<PropertySymbol>("I05.this[]"); var p05set = p05.SetMethod; Assert.False(p05.IsAbstract); Assert.False(p05.IsVirtual); Assert.False(p05.IsSealed); Assert.False(p05.IsStatic); Assert.False(p05.IsExtern); Assert.False(p05.IsOverride); Assert.Equal(Accessibility.Private, p05.DeclaredAccessibility); Assert.False(p05set.IsAbstract); Assert.False(p05set.IsVirtual); Assert.False(p05set.IsMetadataVirtual()); Assert.False(p05set.IsSealed); Assert.False(p05set.IsStatic); Assert.False(p05set.IsExtern); Assert.False(p05set.IsAsync); Assert.False(p05set.IsOverride); Assert.Equal(Accessibility.Private, p05set.DeclaredAccessibility); var p06 = compilation1.GetMember<PropertySymbol>("I06.this[]"); var p06get = p06.GetMethod; Assert.True(p06.IsAbstract); Assert.False(p06.IsVirtual); Assert.False(p06.IsSealed); Assert.False(p06.IsStatic); Assert.False(p06.IsExtern); Assert.False(p06.IsOverride); Assert.Equal(Accessibility.Public, p06.DeclaredAccessibility); Assert.True(p06get.IsAbstract); Assert.False(p06get.IsVirtual); Assert.True(p06get.IsMetadataVirtual()); Assert.False(p06get.IsSealed); Assert.False(p06get.IsStatic); Assert.False(p06get.IsExtern); Assert.False(p06get.IsAsync); Assert.False(p06get.IsOverride); Assert.Equal(Accessibility.Public, p06get.DeclaredAccessibility); var p07 = compilation1.GetMember<PropertySymbol>("I07.this[]"); var p07set = p07.SetMethod; Assert.False(p07.IsAbstract); Assert.True(p07.IsVirtual); Assert.False(p07.IsSealed); Assert.False(p07.IsStatic); Assert.False(p07.IsExtern); Assert.False(p07.IsOverride); Assert.Equal(Accessibility.Public, p07.DeclaredAccessibility); Assert.False(p07set.IsAbstract); Assert.True(p07set.IsVirtual); Assert.True(p07set.IsMetadataVirtual()); Assert.False(p07set.IsSealed); Assert.False(p07set.IsStatic); Assert.False(p07set.IsExtern); Assert.False(p07set.IsAsync); Assert.False(p07set.IsOverride); Assert.Equal(Accessibility.Public, p07set.DeclaredAccessibility); var p08 = compilation1.GetMember<PropertySymbol>("I08.this[]"); var p08get = p08.GetMethod; Assert.False(p08.IsAbstract); Assert.False(p08.IsVirtual); Assert.False(p08.IsSealed); Assert.False(p08.IsStatic); Assert.False(p08.IsExtern); Assert.False(p08.IsOverride); Assert.Equal(Accessibility.Public, p08.DeclaredAccessibility); Assert.False(p08get.IsAbstract); Assert.False(p08get.IsVirtual); Assert.False(p08get.IsMetadataVirtual()); Assert.False(p08get.IsSealed); Assert.False(p08get.IsStatic); Assert.False(p08get.IsExtern); Assert.False(p08get.IsAsync); Assert.False(p08get.IsOverride); Assert.Equal(Accessibility.Public, p08get.DeclaredAccessibility); var p09 = compilation1.GetMember<PropertySymbol>("I09.this[]"); var p09set = p09.SetMethod; Assert.True(p09.IsAbstract); Assert.False(p09.IsVirtual); Assert.False(p09.IsSealed); Assert.False(p09.IsStatic); Assert.False(p09.IsExtern); Assert.False(p09.IsOverride); Assert.Equal(Accessibility.Public, p09.DeclaredAccessibility); Assert.True(p09set.IsAbstract); Assert.False(p09set.IsVirtual); Assert.True(p09set.IsMetadataVirtual()); Assert.False(p09set.IsSealed); Assert.False(p09set.IsStatic); Assert.False(p09set.IsExtern); Assert.False(p09set.IsAsync); Assert.False(p09set.IsOverride); Assert.Equal(Accessibility.Public, p09set.DeclaredAccessibility); var p10 = compilation1.GetMember<PropertySymbol>("I10.this[]"); var p10get = p10.GetMethod; Assert.True(p10.IsAbstract); Assert.False(p10.IsVirtual); Assert.False(p10.IsSealed); Assert.False(p10.IsStatic); Assert.False(p10.IsExtern); Assert.False(p10.IsOverride); Assert.Equal(Accessibility.Public, p10.DeclaredAccessibility); Assert.True(p10get.IsAbstract); Assert.False(p10get.IsVirtual); Assert.True(p10get.IsMetadataVirtual()); Assert.False(p10get.IsSealed); Assert.False(p10get.IsStatic); Assert.False(p10get.IsExtern); Assert.False(p10get.IsAsync); Assert.False(p10get.IsOverride); Assert.Equal(Accessibility.Public, p10get.DeclaredAccessibility); var p11 = compilation1.GetMember<PropertySymbol>("I11.this[]"); Assert.False(p11.IsAbstract); Assert.True(p11.IsVirtual); Assert.False(p11.IsSealed); Assert.False(p11.IsStatic); Assert.True(p11.IsExtern); Assert.False(p11.IsOverride); Assert.Equal(Accessibility.Public, p11.DeclaredAccessibility); ValidateP11Accessor(p11.GetMethod); ValidateP11Accessor(p11.SetMethod); void ValidateP11Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } var p12 = compilation1.GetMember<PropertySymbol>("I12.this[]"); Assert.True(p12.IsAbstract); Assert.False(p12.IsVirtual); Assert.False(p12.IsSealed); Assert.False(p12.IsStatic); Assert.False(p12.IsExtern); Assert.False(p12.IsOverride); Assert.Equal(Accessibility.Public, p12.DeclaredAccessibility); ValidateP12Accessor(p12.GetMethod); ValidateP12Accessor(p12.SetMethod); void ValidateP12Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } var p13 = compilation1.GetMember<PropertySymbol>("I13.this[]"); Assert.True(p13.IsAbstract); Assert.False(p13.IsVirtual); Assert.False(p13.IsSealed); Assert.False(p13.IsStatic); Assert.False(p13.IsExtern); Assert.False(p13.IsOverride); Assert.Equal(Accessibility.Public, p13.DeclaredAccessibility); ValidateP13Accessor(p13.GetMethod, Accessibility.Public); ValidateP13Accessor(p13.SetMethod, Accessibility.Protected); void ValidateP13Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p14 = compilation1.GetMember<PropertySymbol>("I14.this[]"); Assert.True(p14.IsAbstract); Assert.False(p14.IsVirtual); Assert.False(p14.IsSealed); Assert.False(p14.IsStatic); Assert.False(p14.IsExtern); Assert.False(p14.IsOverride); Assert.Equal(Accessibility.Public, p14.DeclaredAccessibility); ValidateP14Accessor(p14.GetMethod, Accessibility.ProtectedOrInternal); ValidateP14Accessor(p14.SetMethod, Accessibility.Public); void ValidateP14Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p15 = compilation1.GetMember<PropertySymbol>("I15.this[]"); Assert.True(p15.IsAbstract); Assert.False(p15.IsVirtual); Assert.False(p15.IsSealed); Assert.False(p15.IsStatic); Assert.False(p15.IsExtern); Assert.False(p15.IsOverride); Assert.Equal(Accessibility.Public, p15.DeclaredAccessibility); ValidateP15Accessor(p15.GetMethod, Accessibility.Public); ValidateP15Accessor(p15.SetMethod, Accessibility.Internal); void ValidateP15Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p16 = compilation1.GetMember<PropertySymbol>("I16.this[]"); Assert.True(p16.IsAbstract); Assert.False(p16.IsVirtual); Assert.False(p16.IsSealed); Assert.False(p16.IsStatic); Assert.False(p16.IsExtern); Assert.False(p16.IsOverride); Assert.Equal(Accessibility.Public, p16.DeclaredAccessibility); ValidateP16Accessor(p16.GetMethod, Accessibility.Private); ValidateP16Accessor(p16.SetMethod, Accessibility.Public); void ValidateP16Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p17 = compilation1.GetMember<PropertySymbol>("I17.this[]"); var p17get = p17.GetMethod; Assert.True(p17.IsAbstract); Assert.False(p17.IsVirtual); Assert.False(p17.IsSealed); Assert.False(p17.IsStatic); Assert.False(p17.IsExtern); Assert.False(p17.IsOverride); Assert.Equal(Accessibility.Public, p17.DeclaredAccessibility); Assert.True(p17get.IsAbstract); Assert.False(p17get.IsVirtual); Assert.True(p17get.IsMetadataVirtual()); Assert.False(p17get.IsSealed); Assert.False(p17get.IsStatic); Assert.False(p17get.IsExtern); Assert.False(p17get.IsAsync); Assert.False(p17get.IsOverride); Assert.Equal(Accessibility.Private, p17get.DeclaredAccessibility); var p18 = compilation1.GetMember<PropertySymbol>("I18.this[]"); var p18get = p18.GetMethod; Assert.True(p18.IsAbstract); Assert.False(p18.IsVirtual); Assert.False(p18.IsSealed); Assert.False(p18.IsStatic); Assert.False(p18.IsExtern); Assert.False(p18.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, p18.DeclaredAccessibility); Assert.True(p18get.IsAbstract); Assert.False(p18get.IsVirtual); Assert.True(p18get.IsMetadataVirtual()); Assert.False(p18get.IsSealed); Assert.False(p18get.IsStatic); Assert.False(p18get.IsExtern); Assert.False(p18get.IsAsync); Assert.False(p18get.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, p18get.DeclaredAccessibility); var p19 = compilation1.GetMember<PropertySymbol>("I19.this[]"); Assert.True(p19.IsAbstract); Assert.False(p19.IsVirtual); Assert.False(p19.IsSealed); Assert.False(p19.IsStatic); Assert.False(p19.IsExtern); Assert.False(p19.IsOverride); Assert.Equal(Accessibility.Public, p19.DeclaredAccessibility); ValidateP13Accessor(p19.GetMethod, Accessibility.Public); ValidateP13Accessor(p19.SetMethod, Accessibility.ProtectedAndInternal); } [Fact] public void IndexerModifiers_02() { var source1 = @" public interface I01{ public int this[int x] {get; set;} } public interface I02{ protected int this[int x] {get;} } public interface I03{ protected internal int this[int x] {set;} } public interface I04{ internal int this[int x] {get;} } public interface I05{ private int this[int x] {set;} } public interface I06{ static int this[int x] {get;} } public interface I07{ virtual int this[int x] {set;} } public interface I08{ sealed int this[int x] {get;} } public interface I09{ override int this[int x] {set;} } public interface I10{ abstract int this[int x] {get;} } public interface I11{ extern int this[int x] {get; set;} } public interface I12{ int this[int x] { public get; set;} } public interface I13{ int this[int x] { get; protected set;} } public interface I14{ int this[int x] { protected internal get; set;} } public interface I15{ int this[int x] { get; internal set;} } public interface I16{ int this[int x] { private get; set;} } public interface I17{ int this[int x] { private get;} } public interface I18{ private protected int this[int x] { get; } } public interface I19{ int this[int x] { get; private protected set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (2,34): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I01{ public int this[int x] {get; set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("public", "7.3", "8.0").WithLocation(2, 34), // (3,37): error CS8703: The modifier 'protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I02{ protected int this[int x] {get;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("protected", "7.3", "8.0").WithLocation(3, 37), // (4,46): error CS8703: The modifier 'protected internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I03{ protected internal int this[int x] {set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("protected internal", "7.3", "8.0").WithLocation(4, 46), // (5,36): error CS8503: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I04{ internal int this[int x] {get;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("internal", "7.3", "8.0").WithLocation(5, 36), // (6,35): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I05{ private int this[int x] {set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("private", "7.3", "8.0").WithLocation(6, 35), // (6,48): error CS0501: 'I05.this[int].set' must declare a body because it is not marked abstract, extern, or partial // public interface I05{ private int this[int x] {set;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I05.this[int].set").WithLocation(6, 48), // (7,34): error CS0106: The modifier 'static' is not valid for this item // public interface I06{ static int this[int x] {get;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(7, 34), // (8,35): error CS8503: The modifier 'virtual' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I07{ virtual int this[int x] {set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("virtual", "7.3", "8.0").WithLocation(8, 35), // (8,48): error CS0501: 'I07.this[int].set' must declare a body because it is not marked abstract, extern, or partial // public interface I07{ virtual int this[int x] {set;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I07.this[int].set").WithLocation(8, 48), // (9,34): error CS8503: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I08{ sealed int this[int x] {get;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("sealed", "7.3", "8.0").WithLocation(9, 34), // (9,47): error CS0501: 'I08.this[int].get' must declare a body because it is not marked abstract, extern, or partial // public interface I08{ sealed int this[int x] {get;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I08.this[int].get").WithLocation(9, 47), // (10,36): error CS0106: The modifier 'override' is not valid for this item // public interface I09{ override int this[int x] {set;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("override").WithLocation(10, 36), // (11,36): error CS8503: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I10{ abstract int this[int x] {get;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("abstract", "7.3", "8.0").WithLocation(11, 36), // (12,34): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("extern", "7.3", "8.0").WithLocation(12, 34), // (14,48): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I12{ int this[int x] { public get; set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("public", "7.3", "8.0").WithLocation(14, 48), // (14,48): error CS0273: The accessibility modifier of the 'I12.this[int].get' accessor must be more restrictive than the property or indexer 'I12.this[int]' // public interface I12{ int this[int x] { public get; set;} } Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("I12.this[int].get", "I12.this[int]").WithLocation(14, 48), // (15,56): error CS8703: The modifier 'protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I13{ int this[int x] { get; protected set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("protected", "7.3", "8.0").WithLocation(15, 56), // (16,60): error CS8703: The modifier 'protected internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I14{ int this[int x] { protected internal get; set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("protected internal", "7.3", "8.0").WithLocation(16, 60), // (17,55): error CS8503: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I15{ int this[int x] { get; internal set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("internal", "7.3", "8.0").WithLocation(17, 55), // (18,49): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I16{ int this[int x] { private get; set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("private", "7.3", "8.0").WithLocation(18, 49), // (18,49): error CS0442: 'I16.this[int].get': abstract properties cannot have private accessors // public interface I16{ int this[int x] { private get; set;} } Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I16.this[int].get").WithLocation(18, 49), // (19,49): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I17{ int this[int x] { private get;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("private", "7.3", "8.0").WithLocation(19, 49), // (19,27): error CS0276: 'I17.this[int]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // public interface I17{ int this[int x] { private get;} } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I17.this[int]").WithLocation(19, 27), // (21,45): error CS8703: The modifier 'private protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I18{ private protected int this[int x] { get; } } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("private protected", "7.3", "8.0").WithLocation(21, 45), // (22,64): error CS8703: The modifier 'private protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I19{ int this[int x] { get; private protected set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("private protected", "7.3", "8.0").WithLocation(22, 64), // (12,47): warning CS0626: Method, operator, or accessor 'I11.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I11.this[int].get").WithLocation(12, 47), // (12,52): warning CS0626: Method, operator, or accessor 'I11.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I11.this[int].set").WithLocation(12, 52) ); ValidateSymbolsIndexerModifiers_01(compilation1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (3,37): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // public interface I02{ protected int this[int x] {get;} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "this").WithLocation(3, 37), // (4,46): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // public interface I03{ protected internal int this[int x] {set;} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "this").WithLocation(4, 46), // (6,48): error CS0501: 'I05.this[int].set' must declare a body because it is not marked abstract, extern, or partial // public interface I05{ private int this[int x] {set;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I05.this[int].set").WithLocation(6, 48), // (7,34): error CS0106: The modifier 'static' is not valid for this item // public interface I06{ static int this[int x] {get;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(7, 34), // (8,48): error CS0501: 'I07.this[int].set' must declare a body because it is not marked abstract, extern, or partial // public interface I07{ virtual int this[int x] {set;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I07.this[int].set").WithLocation(8, 48), // (9,47): error CS0501: 'I08.this[int].get' must declare a body because it is not marked abstract, extern, or partial // public interface I08{ sealed int this[int x] {get;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I08.this[int].get").WithLocation(9, 47), // (10,36): error CS0106: The modifier 'override' is not valid for this item // public interface I09{ override int this[int x] {set;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("override").WithLocation(10, 36), // (12,47): error CS8701: Target runtime doesn't support default interface implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(12, 47), // (12,47): warning CS0626: Method, operator, or accessor 'I11.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I11.this[int].get").WithLocation(12, 47), // (12,52): error CS8701: Target runtime doesn't support default interface implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(12, 52), // (12,52): warning CS0626: Method, operator, or accessor 'I11.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I11.this[int].set").WithLocation(12, 52), // (14,48): error CS0273: The accessibility modifier of the 'I12.this[int].get' accessor must be more restrictive than the property or indexer 'I12.this[int]' // public interface I12{ int this[int x] { public get; set;} } Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("I12.this[int].get", "I12.this[int]").WithLocation(14, 48), // (15,56): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // public interface I13{ int this[int x] { get; protected set;} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "set").WithLocation(15, 56), // (16,60): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // public interface I14{ int this[int x] { protected internal get; set;} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "get").WithLocation(16, 60), // (18,49): error CS0442: 'I16.this[int].get': abstract properties cannot have private accessors // public interface I16{ int this[int x] { private get; set;} } Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I16.this[int].get").WithLocation(18, 49), // (19,27): error CS0276: 'I17.this[int]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // public interface I17{ int this[int x] { private get;} } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I17.this[int]").WithLocation(19, 27), // (21,45): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // public interface I18{ private protected int this[int x] { get; } } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "this").WithLocation(21, 45), // (22,64): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // public interface I19{ int this[int x] { get; private protected set;} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "set").WithLocation(22, 64) ); ValidateSymbolsIndexerModifiers_01(compilation2); } [Fact] public void IndexerModifiers_03() { ValidateIndexerImplementation_101(@" public interface I1 { public virtual int this[int i] { get { System.Console.WriteLine(""get P1""); return 0; } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "); ValidateIndexerImplementation_101(@" public interface I1 { public virtual int this[int i] { get => Test1.GetP1(); } } class Test1 : I1 { public static int GetP1() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "); ValidateIndexerImplementation_101(@" public interface I1 { public virtual int this[int i] => Test1.GetP1(); } class Test1 : I1 { public static int GetP1() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "); ValidateIndexerImplementation_102(@" public interface I1 { public virtual int this[int i] { get { System.Console.WriteLine(""get P1""); return 0; } set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1[0] = i1[0]; } } "); ValidateIndexerImplementation_102(@" public interface I1 { public virtual int this[int i] { get => Test1.GetP1(); set => System.Console.WriteLine(""set P1""); } } class Test1 : I1 { public static int GetP1() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); i1[0] = i1[0]; } } "); ValidateIndexerImplementation_103(@" public interface I1 { public virtual int this[int i] { set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } } "); ValidateIndexerImplementation_103(@" public interface I1 { public virtual int this[int i] { set => System.Console.WriteLine(""set P1""); } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } } "); } [Fact] public void IndexerModifiers_04() { var source1 = @" public interface I1 { public virtual int this[int x] { get; } = 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,45): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // public virtual int this[int x] { get; } = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(4, 45), // (4,38): error CS0501: 'I1.this[int].get' must declare a body because it is not marked abstract, extern, or partial // public virtual int this[int x] { get; } = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.this[int].get").WithLocation(4, 38) ); ValidatePropertyModifiers_04(compilation1, "this[]"); } [Fact] public void IndexerModifiers_05() { var source1 = @" public interface I1 { public abstract int this[int x] {get; set;} } public interface I2 { int this[int x] {get; set;} } class Test1 : I1 { public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set => System.Console.WriteLine(""set_P1""); } } class Test2 : I2 { public int this[int x] { get { System.Console.WriteLine(""get_P2""); return 0; } set => System.Console.WriteLine(""set_P2""); } static void Main() { I1 x = new Test1(); x[0] = x[0]; I2 y = new Test2(); y[0] = y[0]; } } "; ValidatePropertyModifiers_05(source1); } [Fact] public void IndexerModifiers_06() { var source1 = @" public interface I1 { public abstract int this[int x] {get; set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3); compilation1.VerifyDiagnostics( // (4,25): error CS8503: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract int this[int x] {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("abstract", "7.3", "8.0").WithLocation(4, 25), // (4,25): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract int this[int x] {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("public", "7.3", "8.0").WithLocation(4, 25) ); ValidatePropertyModifiers_06(compilation1, "this[]"); } [Fact] public void IndexerModifiers_09() { var source1 = @" public interface I1 { private int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } } sealed void M() { var x = this[0]; } } public interface I2 { private int this[int x] { get { System.Console.WriteLine(""get_P2""); return 0; } set { System.Console.WriteLine(""set_P2""); } } sealed void M() { this[0] = this[0]; } } public interface I3 { private int this[int x] { set { System.Console.WriteLine(""set_P3""); } } sealed void M() { this[0] = 0; } } public interface I4 { private int this[int x] { get => GetP4(); } private int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } sealed void M() { var x = this[0]; } } public interface I5 { private int this[int x] { get => GetP5(); set => System.Console.WriteLine(""set_P5""); } private int GetP5() { System.Console.WriteLine(""get_P5""); return 0; } sealed void M() { this[0] = this[0]; } } public interface I6 { private int this[int x] { set => System.Console.WriteLine(""set_P6""); } sealed void M() { this[0] = 0; } } public interface I7 { private int this[int x] => GetP7(); private int GetP7() { System.Console.WriteLine(""get_P7""); return 0; } sealed void M() { var x = this[0]; } } class Test1 : I1, I2, I3, I4, I5, I6, I7 { static void Main() { I1 x1 = new Test1(); x1.M(); I2 x2 = new Test1(); x2.M(); I3 x3 = new Test1(); x3.M(); I4 x4 = new Test1(); x4.M(); I5 x5 = new Test1(); x5.M(); I6 x6 = new Test1(); x6.M(); I7 x7 = new Test1(); x7.M(); } } "; ValidatePropertyModifiers_09(source1); } [Fact] public void IndexerModifiers_10() { var source1 = @" public interface I1 { abstract private int this[byte x] { get; } virtual private int this[int x] => 0; sealed private int this[short x] { get => 0; set {} } private int this[long x] {get;} = 0; } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,37): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // private int this[long x] {get;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(14, 37), // (4,26): error CS0621: 'I1.this[byte]': virtual or abstract members cannot be private // abstract private int this[byte x] { get; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "this").WithArguments("I1.this[byte]").WithLocation(4, 26), // (6,25): error CS0621: 'I1.this[int]': virtual or abstract members cannot be private // virtual private int this[int x] => 0; Diagnostic(ErrorCode.ERR_VirtualPrivate, "this").WithArguments("I1.this[int]").WithLocation(6, 25), // (8,24): error CS0238: 'I1.this[short]' cannot be sealed because it is not an override // sealed private int this[short x] Diagnostic(ErrorCode.ERR_SealedNonOverride, "this").WithArguments("I1.this[short]").WithLocation(8, 24), // (14,31): error CS0501: 'I1.this[long].get' must declare a body because it is not marked abstract, extern, or partial // private int this[long x] {get;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.this[long].get").WithLocation(14, 31), // (17,15): error CS0535: 'Test1' does not implement interface member 'I1.this[byte]' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.this[byte]") ); ValidatePropertyModifiers_10(compilation1); } [Fact] public void IndexerModifiers_11_01() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} sealed void Test() { this[0] = this[0]; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_01(source1, source2, Accessibility.Internal, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.this[int]' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.this[int]") ); } [Fact] public void IndexerModifiers_11_02() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_11_03() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } int I1.this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.Standard, // (9,12): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // int I1.this[int x] Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int]").WithLocation(9, 12) ); } [Fact] public void IndexerModifiers_11_04() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_11_05() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_11_06() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test3()); } public abstract int this[int x] {get; set;} } class Test3 : Test1 { public override int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_11_07() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallP1(new Test1()); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int this[int x] {get; set;} } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_11_08() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long this[int x] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_08(source1, source2); } [Fact] public void IndexerModifiers_11_09() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long this[int x] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_09(source1, source2, // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.this[int]'. 'Test1.this[int]' cannot implement 'I1.this[int]' because it does not have the matching return type of 'int'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.this[int]", "Test1.this[int]", "int").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_11_10() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} sealed void Test() { this[0] = this[0]; } } "; var source2 = @" public class Test2 : I1 { public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_10(source1, source2, // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].set'. 'Test2.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].set", "Test2.this[int].set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].get'. 'Test2.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].get", "Test2.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_11_11() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} sealed void Test() { this[0] = this[0]; } } public class Test2 : I1 { public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_11(source1, source2, // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].get'. 'Test2.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].get", "Test2.this[int].get", "9.0", "10.0").WithLocation(11, 22), // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].set'. 'Test2.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].set", "Test2.this[int].set", "9.0", "10.0").WithLocation(11, 22) ); } [Fact] public void IndexerModifiers_12() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.this[int]") ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMember<PropertySymbol>("this[]"); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Null(test1.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(p1.SetMethod)); } [Fact] public void IndexerModifiers_13() { var source1 = @" public interface I1 { public sealed int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } } } public interface I2 { public sealed int this[int x] { get { System.Console.WriteLine(""get_P2""); return 0; } set { System.Console.WriteLine(""set_P2""); } } } public interface I3 { public sealed int this[int x] { set { System.Console.WriteLine(""set_P3""); } } } public interface I4 { public sealed int this[int x] { get => GetP4(); } private int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } } public interface I5 { public sealed int this[int x] { get => GetP5(); set => System.Console.WriteLine(""set_P5""); } private int GetP5() { System.Console.WriteLine(""get_P5""); return 0; } } public interface I6 { public sealed int this[int x] { set => System.Console.WriteLine(""set_P6""); } } public interface I7 { public sealed int this[int x] => GetP7(); private int GetP7() { System.Console.WriteLine(""get_P7""); return 0; } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); var x = i1[0]; I2 i2 = new Test2(); i2[0] = i2[0]; I3 i3 = new Test3(); i3[0] = x; I4 i4 = new Test4(); x = i4[0]; I5 i5 = new Test5(); i5[0] = i5[0]; I6 i6 = new Test6(); i6[0] = x; I7 i7 = new Test7(); x = i7[0]; } public int this[int x] => throw null; } class Test2 : I2 { public int this[int x] { get => throw null; set => throw null; } } class Test3 : I3 { public int this[int x] { set => throw null; } } class Test4 : I4 { public int this[int x] { get => throw null; } } class Test5 : I5 { public int this[int x] { get => throw null; set => throw null; } } class Test6 : I6 { public int this[int x] { set => throw null; } } class Test7 : I7 { public int this[int x] => throw null; } "; ValidatePropertyModifiers_13(source1); } [Fact] public void AccessModifiers_14() { var source1 = @" public interface I1 { public sealed int this[int x] {get;} = 0; } public interface I2 { abstract sealed int this[int x] {get;} } public interface I3 { virtual sealed int this[int x] { set {} } } class Test1 : I1, I2, I3 { int I1.this[int x] { get => throw null; } int I2.this[int x] { get => throw null; } int I3.this[int x] { set => throw null; } } class Test2 : I1, I2, I3 {} "; ValidatePropertyModifiers_14(source1, // (4,42): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // public sealed int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(4, 42), // (4,36): error CS0501: 'I1.this[int].get' must declare a body because it is not marked abstract, extern, or partial // public sealed int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.this[int].get").WithLocation(4, 36), // (8,25): error CS0238: 'I2.this[int]' cannot be sealed because it is not an override // abstract sealed int this[int x] {get;} Diagnostic(ErrorCode.ERR_SealedNonOverride, "this").WithArguments("I2.this[int]").WithLocation(8, 25), // (12,24): error CS0238: 'I3.this[int]' cannot be sealed because it is not an override // virtual sealed int this[int x] Diagnostic(ErrorCode.ERR_SealedNonOverride, "this").WithArguments("I3.this[int]").WithLocation(12, 24), // (20,12): error CS0539: 'Test1.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.this[int x] { get => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Test1.this[int]").WithLocation(20, 12), // (21,12): error CS0539: 'Test1.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // int I2.this[int x] { get => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Test1.this[int]").WithLocation(21, 12), // (22,12): error CS0539: 'Test1.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // int I3.this[int x] { set => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Test1.this[int]").WithLocation(22, 12) ); } [Fact] [WorkItem(38398, "https://github.com/dotnet/roslyn/issues/38398")] public void InconsistentAccessibility_01() { var source1 = @" interface I1 { protected interface I2 { } } class C1 { protected interface I2 { } } interface I3 : I1 { protected I1.I2 M1(); protected interface I5 { I1.I2 M5(); } } class CI3 : I3 { I1.I2 I3.M1() => null; class CI5 : I3.I5 { I1.I2 I3.I5.M5() => null; } } class C3 : I1 { protected virtual void M1(I1.I2 x) { } protected interface I7 { I1.I2 M7(); } } class CC3 : C3 { protected override void M1(I1.I2 x) { } class CI7 : C3.I7 { I1.I2 C3.I7.M7() => null; } } class C33 : C1 { protected virtual void M1(C1.I2 x) { } protected class C55 { public virtual C1.I2 M55() => null; } } class CC33 : C33 { protected override void M1(C1.I2 x) { } class CC55 : C33.C55 { public override C1.I2 M55() => null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(38398, "https://github.com/dotnet/roslyn/issues/38398")] public void InconsistentAccessibility_02() { var source1 = @" interface I1 { protected interface I2 { } } class C1 { protected interface I2 { } } interface I3 : I1 { interface I4 { protected I1.I2 M4(); } } class CI4 : I3.I4 { I1.I2 I3.I4.M4() => null; } class C3 : I1 { public interface I6 { protected I1.I2 M6(); } } class CI6 : C3.I6 { I1.I2 C3.I6.M6() => null; } class C33 : C1 { public class C44 { protected virtual C1.I2 M44() => null; } } class CC44 : C33.C44 { protected override C1.I2 M44() => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (20,29): error CS0050: Inconsistent accessibility: return type 'I1.I2' is less accessible than method 'I3.I4.M4()' // protected I1.I2 M4(); Diagnostic(ErrorCode.ERR_BadVisReturnType, "M4").WithArguments("I3.I4.M4()", "I1.I2").WithLocation(20, 29), // (24,17): error CS0535: 'CI4' does not implement interface member 'I3.I4.M4()' // class CI4 : I3.I4 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3.I4").WithArguments("CI4", "I3.I4.M4()").WithLocation(24, 17), // (26,12): error CS0122: 'I1.I2' is inaccessible due to its protection level // I1.I2 I3.I4.M4() => null; Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1.I2").WithLocation(26, 12), // (26,21): error CS0539: 'CI4.M4()' in explicit interface declaration is not found among members of the interface that can be implemented // I1.I2 I3.I4.M4() => null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M4").WithArguments("CI4.M4()").WithLocation(26, 21), // (33,29): error CS0050: Inconsistent accessibility: return type 'I1.I2' is less accessible than method 'C3.I6.M6()' // protected I1.I2 M6(); Diagnostic(ErrorCode.ERR_BadVisReturnType, "M6").WithArguments("C3.I6.M6()", "I1.I2").WithLocation(33, 29), // (37,17): error CS0535: 'CI6' does not implement interface member 'C3.I6.M6()' // class CI6 : C3.I6 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "C3.I6").WithArguments("CI6", "C3.I6.M6()").WithLocation(37, 17), // (39,12): error CS0122: 'I1.I2' is inaccessible due to its protection level // I1.I2 C3.I6.M6() => null; Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1.I2").WithLocation(39, 12), // (39,21): error CS0539: 'CI6.M6()' in explicit interface declaration is not found among members of the interface that can be implemented // I1.I2 C3.I6.M6() => null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M6").WithArguments("CI6.M6()").WithLocation(39, 21), // (46,37): error CS0050: Inconsistent accessibility: return type 'C1.I2' is less accessible than method 'C33.C44.M44()' // protected virtual C1.I2 M44() => null; Diagnostic(ErrorCode.ERR_BadVisReturnType, "M44").WithArguments("C33.C44.M44()", "C1.I2").WithLocation(46, 37), // (52,31): error CS0122: 'C1.I2' is inaccessible due to its protection level // protected override C1.I2 M44() => null; Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("C1.I2").WithLocation(52, 31) ); } [Fact] [WorkItem(38398, "https://github.com/dotnet/roslyn/issues/38398")] public void InconsistentAccessibility_03() { var source1 = @" interface I1<T> { protected interface I2 { } } class C1<T> { protected interface I2 { } } interface I3 : I1<int> { protected I1<string>.I2 M1(); protected interface I5 { I1<string>.I2 M5(); } } class CI3 : I3 { I1<string>.I2 I3.M1() => null; class CI5 : I3.I5 { I1<string>.I2 I3.I5.M5() => null; } } class C3 : I1<int> { protected virtual void M1(I1<string>.I2 x) { } protected interface I7 { I1<string>.I2 M7(); } } class CC3 : C3 { protected override void M1(I1<string>.I2 x) { } class CI7 : C3.I7 { I1<string>.I2 C3.I7.M7() => null; } } class C33 : C1<int> { protected virtual void M1(C1<string>.I2 x) { } protected class C55 { public virtual C1<string>.I2 M55() => null; } } class CC33 : C33 { protected override void M1(C1<string>.I2 x) { } class CC55 : C33.C55 { public override C1<string>.I2 M55() => null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(38398, "https://github.com/dotnet/roslyn/issues/38398")] public void InconsistentAccessibility_04() { var source1 = @" interface I1<T> { protected interface I2 { } } class C1<T> { protected interface I2 { } } interface I3 : I1<int> { interface I4 { protected I1<string>.I2 M4(); } } class CI4 : I3.I4 { I1<string>.I2 I3.I4.M4() => null; } class C3 : I1<int> { public interface I6 { protected I1<string>.I2 M6(); } } class CI6 : C3.I6 { I1<string>.I2 C3.I6.M6() => null; } class C33 : C1<int> { public class C44 { protected virtual C1<string>.I2 M44() => null; } } class CC44 : C33.C44 { protected override C1<string>.I2 M44() => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (20,37): error CS0050: Inconsistent accessibility: return type 'I1<string>.I2' is less accessible than method 'I3.I4.M4()' // protected I1<string>.I2 M4(); Diagnostic(ErrorCode.ERR_BadVisReturnType, "M4").WithArguments("I3.I4.M4()", "I1<string>.I2").WithLocation(20, 37), // (24,17): error CS0535: 'CI4' does not implement interface member 'I3.I4.M4()' // class CI4 : I3.I4 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3.I4").WithArguments("CI4", "I3.I4.M4()").WithLocation(24, 17), // (26,20): error CS0122: 'I1<string>.I2' is inaccessible due to its protection level // I1<string>.I2 I3.I4.M4() => null; Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1<string>.I2").WithLocation(26, 20), // (26,29): error CS0539: 'CI4.M4()' in explicit interface declaration is not found among members of the interface that can be implemented // I1<string>.I2 I3.I4.M4() => null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M4").WithArguments("CI4.M4()").WithLocation(26, 29), // (33,37): error CS0050: Inconsistent accessibility: return type 'I1<string>.I2' is less accessible than method 'C3.I6.M6()' // protected I1<string>.I2 M6(); Diagnostic(ErrorCode.ERR_BadVisReturnType, "M6").WithArguments("C3.I6.M6()", "I1<string>.I2").WithLocation(33, 37), // (37,17): error CS0535: 'CI6' does not implement interface member 'C3.I6.M6()' // class CI6 : C3.I6 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "C3.I6").WithArguments("CI6", "C3.I6.M6()").WithLocation(37, 17), // (39,20): error CS0122: 'I1<string>.I2' is inaccessible due to its protection level // I1<string>.I2 C3.I6.M6() => null; Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1<string>.I2").WithLocation(39, 20), // (39,29): error CS0539: 'CI6.M6()' in explicit interface declaration is not found among members of the interface that can be implemented // I1<string>.I2 C3.I6.M6() => null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M6").WithArguments("CI6.M6()").WithLocation(39, 29), // (46,45): error CS0050: Inconsistent accessibility: return type 'C1<string>.I2' is less accessible than method 'C33.C44.M44()' // protected virtual C1<string>.I2 M44() => null; Diagnostic(ErrorCode.ERR_BadVisReturnType, "M44").WithArguments("C33.C44.M44()", "C1<string>.I2").WithLocation(46, 45), // (52,39): error CS0122: 'C1<string>.I2' is inaccessible due to its protection level // protected override C1<string>.I2 M44() => null; Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("C1<string>.I2").WithLocation(52, 39) ); } [Fact] public void IndexerModifiers_15() { var source1 = @" public interface I0 { abstract virtual int this[int x] { get; set; } } public interface I1 { abstract virtual int this[int x] { get { throw null; } } } public interface I2 { virtual abstract int this[int x] { get { throw null; } set { throw null; } } } public interface I3 { abstract virtual int this[int x] { set { throw null; } } } public interface I4 { abstract virtual int this[int x] { get => throw null; } } public interface I5 { abstract virtual int this[int x] { get => throw null; set => throw null; } } public interface I6 { abstract virtual int this[int x] { set => throw null; } } public interface I7 { abstract virtual int this[int x] => throw null; } public interface I8 { abstract virtual int this[int x] {get;} = 0; } class Test1 : I0, I1, I2, I3, I4, I5, I6, I7, I8 { int I0.this[int x] { get { throw null; } set { throw null; } } int I1.this[int x] { get { throw null; } } int I2.this[int x] { get { throw null; } set { throw null; } } int I3.this[int x] { set { throw null; } } int I4.this[int x] { get { throw null; } } int I5.this[int x] { get { throw null; } set { throw null; } } int I6.this[int x] { set { throw null; } } int I7.this[int x] { get { throw null; } } int I8.this[int x] { get { throw null; } } } class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 {} "; ValidatePropertyModifiers_15(source1, // (44,45): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // abstract virtual int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(44, 45), // (4,26): error CS0503: The abstract property 'I0.this[int]' cannot be marked virtual // abstract virtual int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I0.this[int]").WithLocation(4, 26), // (8,26): error CS0503: The abstract property 'I1.this[int]' cannot be marked virtual // abstract virtual int this[int x] { get { throw null; } } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I1.this[int]").WithLocation(8, 26), // (8,40): error CS0500: 'I1.this[int].get' cannot declare a body because it is marked abstract // abstract virtual int this[int x] { get { throw null; } } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.this[int].get").WithLocation(8, 40), // (12,26): error CS0503: The abstract property 'I2.this[int]' cannot be marked virtual // virtual abstract int this[int x] Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I2.this[int]").WithLocation(12, 26), // (14,9): error CS0500: 'I2.this[int].get' cannot declare a body because it is marked abstract // get { throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.this[int].get").WithLocation(14, 9), // (15,9): error CS0500: 'I2.this[int].set' cannot declare a body because it is marked abstract // set { throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.this[int].set").WithLocation(15, 9), // (20,26): error CS0503: The abstract property 'I3.this[int]' cannot be marked virtual // abstract virtual int this[int x] { set { throw null; } } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I3.this[int]").WithLocation(20, 26), // (20,40): error CS0500: 'I3.this[int].set' cannot declare a body because it is marked abstract // abstract virtual int this[int x] { set { throw null; } } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I3.this[int].set").WithLocation(20, 40), // (24,26): error CS0503: The abstract property 'I4.this[int]' cannot be marked virtual // abstract virtual int this[int x] { get => throw null; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I4.this[int]").WithLocation(24, 26), // (24,40): error CS0500: 'I4.this[int].get' cannot declare a body because it is marked abstract // abstract virtual int this[int x] { get => throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I4.this[int].get").WithLocation(24, 40), // (28,26): error CS0503: The abstract property 'I5.this[int]' cannot be marked virtual // abstract virtual int this[int x] Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I5.this[int]").WithLocation(28, 26), // (30,9): error CS0500: 'I5.this[int].get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I5.this[int].get").WithLocation(30, 9), // (31,9): error CS0500: 'I5.this[int].set' cannot declare a body because it is marked abstract // set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I5.this[int].set").WithLocation(31, 9), // (36,26): error CS0503: The abstract property 'I6.this[int]' cannot be marked virtual // abstract virtual int this[int x] { set => throw null; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I6.this[int]").WithLocation(36, 26), // (36,40): error CS0500: 'I6.this[int].set' cannot declare a body because it is marked abstract // abstract virtual int this[int x] { set => throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I6.this[int].set").WithLocation(36, 40), // (40,26): error CS0503: The abstract property 'I7.this[int]' cannot be marked virtual // abstract virtual int this[int x] => throw null; Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I7.this[int]").WithLocation(40, 26), // (40,41): error CS0500: 'I7.this[int].get' cannot declare a body because it is marked abstract // abstract virtual int this[int x] => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "throw null").WithArguments("I7.this[int].get").WithLocation(40, 41), // (44,26): error CS0503: The abstract property 'I8.this[int]' cannot be marked virtual // abstract virtual int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I8.this[int]").WithLocation(44, 26), // (90,15): error CS0535: 'Test2' does not implement interface member 'I0.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I0").WithArguments("Test2", "I0.this[int]").WithLocation(90, 15), // (90,19): error CS0535: 'Test2' does not implement interface member 'I1.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.this[int]").WithLocation(90, 19), // (90,23): error CS0535: 'Test2' does not implement interface member 'I2.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I2.this[int]").WithLocation(90, 23), // (90,27): error CS0535: 'Test2' does not implement interface member 'I3.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test2", "I3.this[int]").WithLocation(90, 27), // (90,31): error CS0535: 'Test2' does not implement interface member 'I4.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test2", "I4.this[int]").WithLocation(90, 31), // (90,35): error CS0535: 'Test2' does not implement interface member 'I5.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I5").WithArguments("Test2", "I5.this[int]").WithLocation(90, 35), // (90,39): error CS0535: 'Test2' does not implement interface member 'I6.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I6").WithArguments("Test2", "I6.this[int]").WithLocation(90, 39), // (90,43): error CS0535: 'Test2' does not implement interface member 'I7.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I7").WithArguments("Test2", "I7.this[int]").WithLocation(90, 43), // (90,47): error CS0535: 'Test2' does not implement interface member 'I8.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I8").WithArguments("Test2", "I8.this[int]").WithLocation(90, 47) ); } [Fact] public void IndexerModifiers_16() { var source1 = @" public interface I1 { extern int this[int x] {get;} } public interface I2 { virtual extern int this[int x] {set;} } public interface I4 { private extern int this[int x] {get;} } public interface I5 { extern sealed int this[int x] {set;} } class Test1 : I1, I2, I4, I5 { } class Test2 : I1, I2, I4, I5 { int I1.this[int x] => 0; int I2.this[int x] { set {} } } "; ValidatePropertyModifiers_16(source1, new DiagnosticDescription[] { // (4,16): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern int this[int x] {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("extern", "7.3", "8.0").WithLocation(4, 16), // (8,24): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern int this[int x] {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("extern", "7.3", "8.0").WithLocation(8, 24), // (8,24): error CS8503: The modifier 'virtual' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern int this[int x] {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("virtual", "7.3", "8.0").WithLocation(8, 24), // (12,24): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern int this[int x] {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("private", "7.3", "8.0").WithLocation(12, 24), // (12,24): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern int this[int x] {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("extern", "7.3", "8.0").WithLocation(12, 24), // (16,23): error CS8503: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed int this[int x] {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("sealed", "7.3", "8.0").WithLocation(16, 23), // (16,23): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed int this[int x] {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("extern", "7.3", "8.0").WithLocation(16, 23), // (8,37): warning CS0626: Method, operator, or accessor 'I2.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern int this[int x] {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I2.this[int].set").WithLocation(8, 37), // (12,37): warning CS0626: Method, operator, or accessor 'I4.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern int this[int x] {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I4.this[int].get").WithLocation(12, 37), // (16,36): warning CS0626: Method, operator, or accessor 'I5.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed int this[int x] {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I5.this[int].set").WithLocation(16, 36), // (4,29): warning CS0626: Method, operator, or accessor 'I1.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int this[int x] {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.this[int].get").WithLocation(4, 29) }, // (4,29): error CS8501: Target runtime doesn't support default interface implementation. // extern int this[int x] {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(4, 29), // (8,37): error CS8501: Target runtime doesn't support default interface implementation. // virtual extern int this[int x] {set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(8, 37), // (12,37): error CS8501: Target runtime doesn't support default interface implementation. // private extern int this[int x] {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(12, 37), // (16,36): error CS8501: Target runtime doesn't support default interface implementation. // extern sealed int this[int x] {set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(16, 36), // (8,37): warning CS0626: Method, operator, or accessor 'I2.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern int this[int x] {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I2.this[int].set").WithLocation(8, 37), // (12,37): warning CS0626: Method, operator, or accessor 'I4.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern int this[int x] {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I4.this[int].get").WithLocation(12, 37), // (16,36): warning CS0626: Method, operator, or accessor 'I5.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed int this[int x] {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I5.this[int].set").WithLocation(16, 36), // (4,29): warning CS0626: Method, operator, or accessor 'I1.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int this[int x] {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.this[int].get").WithLocation(4, 29) ); } [Fact] public void IndexerModifiers_17() { var source1 = @" public interface I1 { abstract extern int this[int x] {get;} } public interface I2 { extern int this[int x] => 0; } public interface I3 { static extern int this[int x] {get => 0; set => throw null;} } public interface I4 { private extern int this[int x] { get {throw null;} set {throw null;}} } public interface I5 { extern sealed int this[int x] {get;} = 0; } class Test1 : I1, I2, I3, I4, I5 { } class Test2 : I1, I2, I3, I4, I5 { int I1.this[int x] => 0; int I2.this[int x] => 0; int I3.this[int x] { get => 0; set => throw null;} int I4.this[int x] { get => 0; set => throw null;} int I5.this[int x] => 0; } "; ValidatePropertyModifiers_17(source1, // (20,42): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // extern sealed int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(20, 42), // (4,25): error CS0180: 'I1.this[int]' cannot be both extern and abstract // abstract extern int this[int x] {get;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "this").WithArguments("I1.this[int]").WithLocation(4, 25), // (8,31): error CS0179: 'I2.this[int].get' cannot be extern and declare a body // extern int this[int x] => 0; Diagnostic(ErrorCode.ERR_ExternHasBody, "0").WithArguments("I2.this[int].get").WithLocation(8, 31), // (12,23): error CS0106: The modifier 'static' is not valid for this item // static extern int this[int x] {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(12, 23), // (12,36): error CS0179: 'I3.this[int].get' cannot be extern and declare a body // static extern int this[int x] {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("I3.this[int].get").WithLocation(12, 36), // (12,46): error CS0179: 'I3.this[int].set' cannot be extern and declare a body // static extern int this[int x] {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("I3.this[int].set").WithLocation(12, 46), // (16,38): error CS0179: 'I4.this[int].get' cannot be extern and declare a body // private extern int this[int x] { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("I4.this[int].get").WithLocation(16, 38), // (16,56): error CS0179: 'I4.this[int].set' cannot be extern and declare a body // private extern int this[int x] { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("I4.this[int].set").WithLocation(16, 56), // (23,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.this[int]"), // (32,12): error CS0539: 'Test2.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // int I4.this[int x] { get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Test2.this[int]").WithLocation(32, 12), // (33,12): error CS0539: 'Test2.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // int I5.this[int x] => 0; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Test2.this[int]").WithLocation(33, 12), // (20,36): warning CS0626: Method, operator, or accessor 'I5.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed int this[int x] {get;} = 0; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I5.this[int].get").WithLocation(20, 36) ); } [Fact] public void IndexerModifiers_18() { var source1 = @" public interface I1 { abstract int this[int x] {get => 0; set => throw null;} } public interface I2 { abstract private int this[int x] => 0; } public interface I3 { static extern int this[int x] {get; set;} } public interface I4 { abstract static int this[int x] { get {throw null;} set {throw null;}} } public interface I5 { override sealed int this[int x] {get;} = 0; } class Test1 : I1, I2, I3, I4, I5 { } class Test2 : I1, I2, I3, I4, I5 { int I1.this[int x] { get => 0; set => throw null;} int I2.this[int x] => 0; int I3.this[int x] { get => 0; set => throw null;} int I4.this[int x] { get => 0; set => throw null;} int I5.this[int x] => 0; } "; ValidatePropertyModifiers_18(source1, // (20,44): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // override sealed int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(20, 44), // (4,31): error CS0500: 'I1.this[int].get' cannot declare a body because it is marked abstract // abstract int this[int x] {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.this[int].get").WithLocation(4, 31), // (4,41): error CS0500: 'I1.this[int].set' cannot declare a body because it is marked abstract // abstract int this[int x] {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I1.this[int].set").WithLocation(4, 41), // (8,26): error CS0621: 'I2.this[int]': virtual or abstract members cannot be private // abstract private int this[int x] => 0; Diagnostic(ErrorCode.ERR_VirtualPrivate, "this").WithArguments("I2.this[int]").WithLocation(8, 26), // (8,41): error CS0500: 'I2.this[int].get' cannot declare a body because it is marked abstract // abstract private int this[int x] => 0; Diagnostic(ErrorCode.ERR_AbstractHasBody, "0").WithArguments("I2.this[int].get").WithLocation(8, 41), // (12,23): error CS0106: The modifier 'static' is not valid for this item // static extern int this[int x] {get; set;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(12, 23), // (16,25): error CS0106: The modifier 'static' is not valid for this item // abstract static int this[int x] { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(16, 25), // (16,39): error CS0500: 'I4.this[int].get' cannot declare a body because it is marked abstract // abstract static int this[int x] { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I4.this[int].get").WithLocation(16, 39), // (16,57): error CS0500: 'I4.this[int].set' cannot declare a body because it is marked abstract // abstract static int this[int x] { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I4.this[int].set").WithLocation(16, 57), // (20,25): error CS0106: The modifier 'override' is not valid for this item // override sealed int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("override").WithLocation(20, 25), // (20,38): error CS0501: 'I5.this[int].get' must declare a body because it is not marked abstract, extern, or partial // override sealed int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I5.this[int].get").WithLocation(20, 38), // (23,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.this[int]"), // (23,19): error CS0535: 'Test1' does not implement interface member 'I2.this[int]' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I2.this[int]"), // (23,27): error CS0535: 'Test1' does not implement interface member 'I4.this[int]' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test1", "I4.this[int]").WithLocation(23, 27), // (30,12): error CS0122: 'I2.this[int]' is inaccessible due to its protection level // int I2.this[int x] => 0; Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I2.this[int]").WithLocation(30, 12), // (33,12): error CS0539: 'Test2.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // int I5.this[int x] => 0; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Test2.this[int]").WithLocation(33, 12), // (12,36): warning CS0626: Method, operator, or accessor 'I3.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int this[int x] {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I3.this[int].get").WithLocation(12, 36), // (12,41): warning CS0626: Method, operator, or accessor 'I3.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int this[int x] {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I3.this[int].set").WithLocation(12, 41) ); } [Fact] public void IndexerModifiers_20() { var source1 = @" public interface I1 { internal int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } void M2() {this[0] = this[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidatePropertyModifiers_20(source1, source2, Accessibility.Internal); } [Fact] public void IndexerModifiers_21() { var source1 = @" public interface I1 { private int this[int x] { get => throw null; set => throw null; } } public interface I2 { internal int this[int x] { get => throw null; set => throw null; } } public interface I3 { public int this[int x] { get => throw null; set => throw null; } } public interface I4 { int this[int x] { get => throw null; set => throw null; } } class Test1 { static void Test(I1 i1, I2 i2, I3 i3, I4 i4) { int x; x = i1[0]; i1[0] = x; x = i2[0]; i2[0] = x; x = i3[0]; i3[0] = x; x = i4[0]; i4[0] = x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (24,13): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // x = i1[0]; Diagnostic(ErrorCode.ERR_BadAccess, "i1[0]").WithArguments("I1.this[int]").WithLocation(24, 13), // (25,9): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // i1[0] = x; Diagnostic(ErrorCode.ERR_BadAccess, "i1[0]").WithArguments("I1.this[int]").WithLocation(25, 9) ); var source2 = @" class Test2 { static void Test(I1 i1, I2 i2, I3 i3, I4 i4) { int x; x = i1[0]; i1[0] = x; x = i2[0]; i2[0] = x; x = i3[0]; i3[0] = x; x = i4[0]; i4[0] = x; } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (7,13): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // x = i1[0]; Diagnostic(ErrorCode.ERR_BadAccess, "i1[0]").WithArguments("I1.this[int]").WithLocation(7, 13), // (8,9): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // i1[0] = x; Diagnostic(ErrorCode.ERR_BadAccess, "i1[0]").WithArguments("I1.this[int]").WithLocation(8, 9), // (9,13): error CS0122: 'I2.this[int]' is inaccessible due to its protection level // x = i2[0]; Diagnostic(ErrorCode.ERR_BadAccess, "i2[0]").WithArguments("I2.this[int]").WithLocation(9, 13), // (10,9): error CS0122: 'I2.this[int]' is inaccessible due to its protection level // i2[0] = x; Diagnostic(ErrorCode.ERR_BadAccess, "i2[0]").WithArguments("I2.this[int]").WithLocation(10, 9) ); } [Fact] public void IndexerModifiers_22() { var source1 = @" public interface I1 { public int this[int x] { internal get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int this[int x] { get { System.Console.WriteLine(""get_P2""); return 0; } internal set { System.Console.WriteLine(""set_P2""); } } } public interface I3 { int this[int x] { internal get => Test1.GetP3(); set => System.Console.WriteLine(""set_P3""); } } public interface I4 { int this[int x] { get => Test1.GetP4(); internal set => System.Console.WriteLine(""set_P4""); } } class Test1 : I1, I2, I3, I4 { static void Main() { I1 i1 = new Test1(); I2 i2 = new Test1(); I3 i3 = new Test1(); I4 i4 = new Test1(); i1[0] = i1[0]; i2[0] = i2[0]; i3[0] = i3[0]; i4[0] = i4[0]; } public static int GetP3() { System.Console.WriteLine(""get_P3""); return 0; } public static int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } } "; ValidatePropertyModifiers_22(source1, Accessibility.Internal); } [Fact] public void IndexerModifiers_23_00() { var source1 = @" public interface I1 { } public interface I3 { int this[int x] { private get { System.Console.WriteLine(""get_P3""); return 0; } set {System.Console.WriteLine(""set_P3"");} } void M2() { this[0] = this[1]; } } public interface I4 { int this[int x] { get {System.Console.WriteLine(""get_P4""); return 0;} private set {System.Console.WriteLine(""set_P4"");} } void M2() { this[0] = this[1]; } } public interface I5 { int this[int x] { private get => GetP5(); set => System.Console.WriteLine(""set_P5""); } private int GetP5() { System.Console.WriteLine(""get_P5""); return 0; } void M2() { this[0] = this[1]; } } public interface I6 { int this[int x] { get => GetP6(); private set => System.Console.WriteLine(""set_P6""); } private int GetP6() { System.Console.WriteLine(""get_P6""); return 0; } void M2() { this[0] = this[1]; } } "; var source2 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public int this[int x] { get { throw null; } set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public int this[int x] { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } set { throw null; } } } class Test5 : I5 { public int this[int x] { get { throw null; } set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public int this[int x] { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } set { throw null; } } } "; ValidatePropertyModifiers_23(source1, source2); var source3 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public int this[int x] { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public int this[int x] { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test5 : I5 { public int this[int x] { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public int this[int x] { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } "; ValidatePropertyModifiers_23(source1, source3); var source4 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public virtual int this[int x] { get { throw null; } set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public virtual int this[int x] { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } set { throw null; } } } class Test5 : I5 { public virtual int this[int x] { get { throw null; } set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public virtual int this[int x] { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } set { throw null; } } } "; ValidatePropertyModifiers_23(source1, source4); var source5 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public virtual int this[int x] { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public virtual int this[int x] { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test5 : I5 { public virtual int this[int x] { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public virtual int this[int x] { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } "; ValidatePropertyModifiers_23(source1, source5); var source6 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { int I3.this[int x] { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { int I4.this[int x] { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test5 : I5 { int I5.this[int x] { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { int I6.this[int x] { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } "; ValidatePropertyModifiers_23(source1, source6); var source7 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test33(); I4 i4 = new Test44(); I5 i5 = new Test55(); I6 i6 = new Test66(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } interface Test3 : I3 { int I3.this[int x] { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test33 : Test3 {} interface Test4 : I4 { int I4.this[int x] { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test44 : Test4 {} interface Test5 : I5 { int I5.this[int x] { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test55 : Test5 {} interface Test6 : I6 { int I6.this[int x] { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } class Test66 : Test6 {} "; ValidatePropertyModifiers_23(source1, source7); } [Fact] public void IndexerModifiers_23_01() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} void M2() { this[0] = this[1]; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_23(source1, source2, Accessibility.Internal, Accessibility.Public, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_23_02() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_23_03() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } int I1.this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.Standard, // (9,12): error CS0122: 'I1.this[int].get' is inaccessible due to its protection level // int I1.this[int x] Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int].get").WithLocation(9, 12) ); } [Fact] public void IndexerModifiers_23_04() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_05() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_06() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test3()); } public abstract int this[int x] {get; set;} } class Test3 : Test1 { public override int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_07() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallP1(new Test1()); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int this[int x] {get; set;} } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_08() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long this[int x] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_08(source1, source2); } [Fact] public void IndexerModifiers_23_09() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long this[int x] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_09(source1, source2, // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.this[int]'. 'Test1.this[int]' cannot implement 'I1.this[int]' because it does not have the matching return type of 'int'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.this[int]", "Test1.this[int]", "int").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_23_10() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} sealed void Test() { this[0] = this[0]; } } "; var source2 = @" public class Test2 : I1 { public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_10(source1, source2, // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].get'. 'Test2.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].get", "Test2.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_11() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} sealed void Test() { this[0] = this[0]; } } public class Test2 : I1 { public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_11(source1, source2, // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].get'. 'Test2.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].get", "Test2.this[int].get", "9.0", "10.0").WithLocation(11, 22) ); } [Fact] public void IndexerModifiers_23_51() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} void M2() { this[0] = this[0]; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_23(source1, source2, Accessibility.Public, Accessibility.Internal, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_23_52() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_23_53() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } int I1.this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.Standard, // (9,12): error CS0122: 'I1.this[int].set' is inaccessible due to its protection level // int I1.this[int x] Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int].set").WithLocation(9, 12) ); } [Fact] public void IndexerModifiers_23_54() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_55() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_56() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test3()); } public abstract int this[int x] {get; set;} } class Test3 : Test1 { public override int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_57() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallP1(new Test1()); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int this[int x] {get; set;} } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_58() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long this[int x] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_08(source1, source2); } [Fact] public void IndexerModifiers_23_59() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long this[int x] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_09(source1, source2, // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.this[int]'. 'Test1.this[int]' cannot implement 'I1.this[int]' because it does not have the matching return type of 'int'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.this[int]", "Test1.this[int]", "int").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_23_60() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} sealed void Test() { this[0] = this[0]; } } "; var source2 = @" public class Test2 : I1 { public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_10(source1, source2, // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].set'. 'Test2.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].set", "Test2.this[int].set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_61() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} sealed void Test() { this[0] = this[0]; } } public class Test2 : I1 { public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_11(source1, source2, // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].set'. 'Test2.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].set", "Test2.this[int].set", "9.0", "10.0").WithLocation(11, 22) ); } [Fact] public void IndexerModifiers_24() { var source1 = @" public interface I1 { int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } internal set { System.Console.WriteLine(""set_P1""); } } void M2() {this[0] = this[1];} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidatePropertyModifiers_24(source1, source2); } [Fact] public void IndexerModifiers_25() { var source1 = @" public interface I1 { int this[int x] { private get => throw null; set => throw null; } } public interface I2 { int this[int x] { internal get => throw null; set => throw null; } } public interface I3 { public int this[int x] { get => throw null; private set => throw null; } } public interface I4 { int this[int x] { get => throw null; internal set => throw null; } } public class Test1 : I1, I2, I3, I4 { static void Main() { int x; I1 i1 = new Test1(); I2 i2 = new Test1(); I3 i3 = new Test1(); I4 i4 = new Test1(); x = i1[0]; i1[0] = x; x = i2[0]; i2[0] = x; x = i3[0]; i3[0] = x; x = i4[0]; i4[0] = x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (29,13): error CS0271: The property or indexer 'I1.this[int]' cannot be used in this context because the get accessor is inaccessible // x = i1[0]; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "i1[0]").WithArguments("I1.this[int]").WithLocation(29, 13), // (34,9): error CS0272: The property or indexer 'I3.this[int]' cannot be used in this context because the set accessor is inaccessible // i3[0] = x; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "i3[0]").WithArguments("I3.this[int]").WithLocation(34, 9) ); var source2 = @" class Test2 { static void Main() { int x; I1 i1 = new Test1(); I2 i2 = new Test1(); I3 i3 = new Test1(); I4 i4 = new Test1(); x = i1[0]; i1[0] = x; x = i2[0]; i2[0] = x; x = i3[0]; i3[0] = x; x = i4[0]; i4[0] = x; } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (12,13): error CS0271: The property or indexer 'I1.this[int]' cannot be used in this context because the get accessor is inaccessible // x = i1[0]; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "i1[0]").WithArguments("I1.this[int]").WithLocation(12, 13), // (14,13): error CS0271: The property or indexer 'I2.this[int]' cannot be used in this context because the get accessor is inaccessible // x = i2[0]; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "i2[0]").WithArguments("I2.this[int]").WithLocation(14, 13), // (17,9): error CS0272: The property or indexer 'I3.this[int]' cannot be used in this context because the set accessor is inaccessible // i3[0] = x; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "i3[0]").WithArguments("I3.this[int]").WithLocation(17, 9), // (19,9): error CS0272: The property or indexer 'I4.this[int]' cannot be used in this context because the set accessor is inaccessible // i4[0] = x; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "i4[0]").WithArguments("I4.this[int]").WithLocation(19, 9) ); } [Fact] public void IndexerModifiers_26() { var source1 = @" public interface I1 { abstract int this[sbyte x] { private get; set; } abstract int this[byte x] { get; private set; } abstract int this[short x] { internal get; } int this[ushort x] {internal get;} = 0; int this[int x] { internal get {throw null;} } int this[uint x] { internal set {throw null;} } int this[long x] { internal get => throw null; } int this[ulong x] { internal set => throw null; } int this[float x] { internal get {throw null;} private set {throw null;}} int this[double x] { internal get => throw null; private set => throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (7,40): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // int this[ushort x] {internal get;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(7, 40), // (4,42): error CS0442: 'I1.this[sbyte].get': abstract properties cannot have private accessors // abstract int this[sbyte x] { private get; set; } Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I1.this[sbyte].get").WithLocation(4, 42), // (5,46): error CS0442: 'I1.this[byte].set': abstract properties cannot have private accessors // abstract int this[byte x] { get; private set; } Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "set").WithArguments("I1.this[byte].set").WithLocation(5, 46), // (6,18): error CS0276: 'I1.this[short]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // abstract int this[short x] { internal get; } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I1.this[short]").WithLocation(6, 18), // (7,9): error CS0276: 'I1.this[ushort]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int this[ushort x] {internal get;} = 0; Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I1.this[ushort]").WithLocation(7, 9), // (8,9): error CS0276: 'I1.this[int]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int this[int x] { internal get {throw null;} } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I1.this[int]").WithLocation(8, 9), // (9,9): error CS0276: 'I1.this[uint]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int this[uint x] { internal set {throw null;} } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I1.this[uint]").WithLocation(9, 9), // (10,9): error CS0276: 'I1.this[long]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int this[long x] { internal get => throw null; } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I1.this[long]").WithLocation(10, 9), // (11,9): error CS0276: 'I1.this[ulong]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int this[ulong x] { internal set => throw null; } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I1.this[ulong]").WithLocation(11, 9), // (12,9): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'I1.this[float]' // int this[float x] { internal get {throw null;} private set {throw null;}} Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "this").WithArguments("I1.this[float]").WithLocation(12, 9), // (13,9): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'I1.this[double]' // int this[double x] { internal get => throw null; private set => throw null;} Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "this").WithArguments("I1.this[double]").WithLocation(13, 9) ); } [Fact] public void IndexerModifiers_27() { var source1 = @" public interface I1 { int this[short x] { private get {throw null;} set {} } int this[int x] { get {throw null;} private set {} } } class Test1 : I1 { int I1.this[short x] { get {throw null;} set {} } int I1.this[int x] { get {throw null;} set {} } } interface ITest1 : I1 { int I1.this[short x] { get {throw null;} set {} } int I1.this[int x] { get {throw null;} set {} } } public interface I2 { int this[short x] { private get {throw null;} set {} } int this[int x] { get {throw null;} private set {} } class Test3 : I2 { int I2.this[short x] { get {throw null;} set {} } int I2.this[int x] { get {throw null;} set {} } } interface ITest3 : I2 { int I2.this[short x] { get {throw null;} set {} } int I2.this[int x] { get {throw null;} set {} } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (21,9): error CS0550: 'Test1.I1.this[short].get' adds an accessor not found in interface member 'I1.this[short]' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("Test1.I1.this[short].get", "I1.this[short]").WithLocation(21, 9), // (28,9): error CS0550: 'Test1.I1.this[int].set' adds an accessor not found in interface member 'I1.this[int]' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("Test1.I1.this[int].set", "I1.this[int]").WithLocation(28, 9), // (36,9): error CS0550: 'ITest1.I1.this[short].get' adds an accessor not found in interface member 'I1.this[short]' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("ITest1.I1.this[short].get", "I1.this[short]").WithLocation(36, 9), // (43,9): error CS0550: 'ITest1.I1.this[int].set' adds an accessor not found in interface member 'I1.this[int]' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("ITest1.I1.this[int].set", "I1.this[int]").WithLocation(43, 9), // (65,13): error CS0550: 'I2.Test3.I2.this[short].get' adds an accessor not found in interface member 'I2.this[short]' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.Test3.I2.this[short].get", "I2.this[short]").WithLocation(65, 13), // (72,13): error CS0550: 'I2.Test3.I2.this[int].set' adds an accessor not found in interface member 'I2.this[int]' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.Test3.I2.this[int].set", "I2.this[int]").WithLocation(72, 13), // (80,13): error CS0550: 'I2.ITest3.I2.this[short].get' adds an accessor not found in interface member 'I2.this[short]' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.ITest3.I2.this[short].get", "I2.this[short]").WithLocation(80, 13), // (87,13): error CS0550: 'I2.ITest3.I2.this[int].set' adds an accessor not found in interface member 'I2.this[int]' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.ITest3.I2.this[int].set", "I2.this[int]").WithLocation(87, 13) ); } [Fact] public void EventModifiers_01() { var source1 = @" public interface I1 { public event System.Action P01; protected event System.Action P02 {add{}} protected internal event System.Action P03 {remove{}} internal event System.Action P04 {add{}} private event System.Action P05 {remove{}} static event System.Action P06 {add{}} virtual event System.Action P07 {remove{}} sealed event System.Action P08 {add{}} override event System.Action P09 {remove{}} abstract event System.Action P10 {add{}} extern event System.Action P11 {add{} remove{}} extern event System.Action P12 {add; remove;} extern event System.Action P13; private protected event System.Action P14; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_EventNeedsBothAccessors).Verify( // (12,34): error CS0106: The modifier 'override' is not valid for this item // override event System.Action P09 {remove{}} Diagnostic(ErrorCode.ERR_BadMemberFlag, "P09").WithArguments("override").WithLocation(12, 34), // (13,38): error CS8712: 'I1.P10': abstract event cannot use event accessor syntax // abstract event System.Action P10 {add{}} Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.P10").WithLocation(13, 38), // (14,37): error CS0179: 'I1.P11.add' cannot be extern and declare a body // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("I1.P11.add").WithLocation(14, 37), // (14,43): error CS0179: 'I1.P11.remove' cannot be extern and declare a body // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("I1.P11.remove").WithLocation(14, 43), // (15,37): warning CS0626: Method, operator, or accessor 'I1.P12.add' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "add").WithArguments("I1.P12.add").WithLocation(15, 37), // (15,40): error CS0073: An add or remove accessor must have a body // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(15, 40), // (15,42): warning CS0626: Method, operator, or accessor 'I1.P12.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "remove").WithArguments("I1.P12.remove").WithLocation(15, 42), // (15,48): error CS0073: An add or remove accessor must have a body // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(15, 48), // (16,32): warning CS0626: Method, operator, or accessor 'I1.P13.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P13; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P13").WithArguments("I1.P13.remove").WithLocation(16, 32) ); ValidateSymbolsEventModifiers_01(compilation1); } private static void ValidateSymbolsEventModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var p01 = i1.GetMember<EventSymbol>("P01"); Assert.True(p01.IsAbstract); Assert.False(p01.IsVirtual); Assert.False(p01.IsSealed); Assert.False(p01.IsStatic); Assert.False(p01.IsExtern); Assert.False(p01.IsOverride); Assert.Equal(Accessibility.Public, p01.DeclaredAccessibility); ValidateP01Accessor(p01.AddMethod); ValidateP01Accessor(p01.RemoveMethod); void ValidateP01Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } var p02 = i1.GetMember<EventSymbol>("P02"); var p02get = p02.AddMethod; Assert.False(p02.IsAbstract); Assert.True(p02.IsVirtual); Assert.False(p02.IsSealed); Assert.False(p02.IsStatic); Assert.False(p02.IsExtern); Assert.False(p02.IsOverride); Assert.Equal(Accessibility.Protected, p02.DeclaredAccessibility); Assert.False(p02get.IsAbstract); Assert.True(p02get.IsVirtual); Assert.True(p02get.IsMetadataVirtual()); Assert.False(p02get.IsSealed); Assert.False(p02get.IsStatic); Assert.False(p02get.IsExtern); Assert.False(p02get.IsAsync); Assert.False(p02get.IsOverride); Assert.Equal(Accessibility.Protected, p02get.DeclaredAccessibility); var p03 = i1.GetMember<EventSymbol>("P03"); var p03set = p03.RemoveMethod; Assert.False(p03.IsAbstract); Assert.True(p03.IsVirtual); Assert.False(p03.IsSealed); Assert.False(p03.IsStatic); Assert.False(p03.IsExtern); Assert.False(p03.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, p03.DeclaredAccessibility); Assert.False(p03set.IsAbstract); Assert.True(p03set.IsVirtual); Assert.True(p03set.IsMetadataVirtual()); Assert.False(p03set.IsSealed); Assert.False(p03set.IsStatic); Assert.False(p03set.IsExtern); Assert.False(p03set.IsAsync); Assert.False(p03set.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, p03set.DeclaredAccessibility); var p04 = i1.GetMember<EventSymbol>("P04"); var p04get = p04.AddMethod; Assert.False(p04.IsAbstract); Assert.True(p04.IsVirtual); Assert.False(p04.IsSealed); Assert.False(p04.IsStatic); Assert.False(p04.IsExtern); Assert.False(p04.IsOverride); Assert.Equal(Accessibility.Internal, p04.DeclaredAccessibility); Assert.False(p04get.IsAbstract); Assert.True(p04get.IsVirtual); Assert.True(p04get.IsMetadataVirtual()); Assert.False(p04get.IsSealed); Assert.False(p04get.IsStatic); Assert.False(p04get.IsExtern); Assert.False(p04get.IsAsync); Assert.False(p04get.IsOverride); Assert.Equal(Accessibility.Internal, p04get.DeclaredAccessibility); var p05 = i1.GetMember<EventSymbol>("P05"); var p05set = p05.RemoveMethod; Assert.False(p05.IsAbstract); Assert.False(p05.IsVirtual); Assert.False(p05.IsSealed); Assert.False(p05.IsStatic); Assert.False(p05.IsExtern); Assert.False(p05.IsOverride); Assert.Equal(Accessibility.Private, p05.DeclaredAccessibility); Assert.False(p05set.IsAbstract); Assert.False(p05set.IsVirtual); Assert.False(p05set.IsMetadataVirtual()); Assert.False(p05set.IsSealed); Assert.False(p05set.IsStatic); Assert.False(p05set.IsExtern); Assert.False(p05set.IsAsync); Assert.False(p05set.IsOverride); Assert.Equal(Accessibility.Private, p05set.DeclaredAccessibility); var p06 = i1.GetMember<EventSymbol>("P06"); var p06get = p06.AddMethod; Assert.False(p06.IsAbstract); Assert.False(p06.IsVirtual); Assert.False(p06.IsSealed); Assert.True(p06.IsStatic); Assert.False(p06.IsExtern); Assert.False(p06.IsOverride); Assert.Equal(Accessibility.Public, p06.DeclaredAccessibility); Assert.False(p06get.IsAbstract); Assert.False(p06get.IsVirtual); Assert.False(p06get.IsMetadataVirtual()); Assert.False(p06get.IsSealed); Assert.True(p06get.IsStatic); Assert.False(p06get.IsExtern); Assert.False(p06get.IsAsync); Assert.False(p06get.IsOverride); Assert.Equal(Accessibility.Public, p06get.DeclaredAccessibility); var p07 = i1.GetMember<EventSymbol>("P07"); var p07set = p07.RemoveMethod; Assert.False(p07.IsAbstract); Assert.True(p07.IsVirtual); Assert.False(p07.IsSealed); Assert.False(p07.IsStatic); Assert.False(p07.IsExtern); Assert.False(p07.IsOverride); Assert.Equal(Accessibility.Public, p07.DeclaredAccessibility); Assert.False(p07set.IsAbstract); Assert.True(p07set.IsVirtual); Assert.True(p07set.IsMetadataVirtual()); Assert.False(p07set.IsSealed); Assert.False(p07set.IsStatic); Assert.False(p07set.IsExtern); Assert.False(p07set.IsAsync); Assert.False(p07set.IsOverride); Assert.Equal(Accessibility.Public, p07set.DeclaredAccessibility); var p08 = i1.GetMember<EventSymbol>("P08"); var p08get = p08.AddMethod; Assert.False(p08.IsAbstract); Assert.False(p08.IsVirtual); Assert.False(p08.IsSealed); Assert.False(p08.IsStatic); Assert.False(p08.IsExtern); Assert.False(p08.IsOverride); Assert.Equal(Accessibility.Public, p08.DeclaredAccessibility); Assert.False(p08get.IsAbstract); Assert.False(p08get.IsVirtual); Assert.False(p08get.IsMetadataVirtual()); Assert.False(p08get.IsSealed); Assert.False(p08get.IsStatic); Assert.False(p08get.IsExtern); Assert.False(p08get.IsAsync); Assert.False(p08get.IsOverride); Assert.Equal(Accessibility.Public, p08get.DeclaredAccessibility); var p09 = i1.GetMember<EventSymbol>("P09"); var p09set = p09.RemoveMethod; Assert.False(p09.IsAbstract); Assert.True(p09.IsVirtual); Assert.False(p09.IsSealed); Assert.False(p09.IsStatic); Assert.False(p09.IsExtern); Assert.False(p09.IsOverride); Assert.Equal(Accessibility.Public, p09.DeclaredAccessibility); Assert.False(p09set.IsAbstract); Assert.True(p09set.IsVirtual); Assert.True(p09set.IsMetadataVirtual()); Assert.False(p09set.IsSealed); Assert.False(p09set.IsStatic); Assert.False(p09set.IsExtern); Assert.False(p09set.IsAsync); Assert.False(p09set.IsOverride); Assert.Equal(Accessibility.Public, p09set.DeclaredAccessibility); var p10 = i1.GetMember<EventSymbol>("P10"); var p10get = p10.AddMethod; Assert.True(p10.IsAbstract); Assert.False(p10.IsVirtual); Assert.False(p10.IsSealed); Assert.False(p10.IsStatic); Assert.False(p10.IsExtern); Assert.False(p10.IsOverride); Assert.Equal(Accessibility.Public, p10.DeclaredAccessibility); Assert.True(p10get.IsAbstract); Assert.False(p10get.IsVirtual); Assert.True(p10get.IsMetadataVirtual()); Assert.False(p10get.IsSealed); Assert.False(p10get.IsStatic); Assert.False(p10get.IsExtern); Assert.False(p10get.IsAsync); Assert.False(p10get.IsOverride); Assert.Equal(Accessibility.Public, p10get.DeclaredAccessibility); foreach (var name in new[] { "P11", "P12", "P13" }) { var p11 = i1.GetMember<EventSymbol>(name); Assert.False(p11.IsAbstract); Assert.True(p11.IsVirtual); Assert.False(p11.IsSealed); Assert.False(p11.IsStatic); Assert.True(p11.IsExtern); Assert.False(p11.IsOverride); Assert.Equal(Accessibility.Public, p11.DeclaredAccessibility); ValidateP11Accessor(p11.AddMethod); ValidateP11Accessor(p11.RemoveMethod); void ValidateP11Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } } var p14 = i1.GetMember<EventSymbol>("P14"); Assert.True(p14.IsAbstract); Assert.False(p14.IsVirtual); Assert.False(p14.IsSealed); Assert.False(p14.IsStatic); Assert.False(p14.IsExtern); Assert.False(p14.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, p14.DeclaredAccessibility); ValidateP14Accessor(p14.AddMethod); ValidateP14Accessor(p14.RemoveMethod); void ValidateP14Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, accessor.DeclaredAccessibility); } } [Fact] public void EventModifiers_02() { var source1 = @" public interface I1 { public event System.Action P01; protected event System.Action P02 {add{}} protected internal event System.Action P03 {remove{}} internal event System.Action P04 {add{}} private event System.Action P05 {remove{}} static event System.Action P06 {add{}} virtual event System.Action P07 {remove{}} sealed event System.Action P08 {add{}} override event System.Action P09 {remove{}} abstract event System.Action P10 {add{}} extern event System.Action P11 {add{} remove{}} extern event System.Action P12 {add; remove;} extern event System.Action P13; private protected event System.Action P14; protected event System.Action P15; protected internal event System.Action P16; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_EventNeedsBothAccessors).Verify( // (4,32): error CS8703: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public event System.Action P01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("public", "7.3", "8.0").WithLocation(4, 32), // (5,40): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // protected event System.Action P02 {add{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(5, 40), // (6,49): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // protected internal event System.Action P03 {remove{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(6, 49), // (7,39): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // internal event System.Action P04 {add{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(7, 39), // (8,38): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // private event System.Action P05 {remove{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(8, 38), // (9,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static event System.Action P06 {add{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "P06").WithArguments("default interface implementation", "8.0").WithLocation(9, 32), // (10,38): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual event System.Action P07 {remove{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(10, 38), // (11,37): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // sealed event System.Action P08 {add{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(11, 37), // (12,34): error CS0106: The modifier 'override' is not valid for this item // override event System.Action P09 {remove{}} Diagnostic(ErrorCode.ERR_BadMemberFlag, "P09").WithArguments("override").WithLocation(12, 34), // (12,39): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override event System.Action P09 {remove{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(12, 39), // (13,39): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract event System.Action P10 {add{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(13, 39), // (13,38): error CS8712: 'I1.P10': abstract event cannot use event accessor syntax // abstract event System.Action P10 {add{}} Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.P10").WithLocation(13, 38), // (14,37): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(14, 37), // (14,37): error CS0179: 'I1.P11.add' cannot be extern and declare a body // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("I1.P11.add").WithLocation(14, 37), // (14,43): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(14, 43), // (14,43): error CS0179: 'I1.P11.remove' cannot be extern and declare a body // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("I1.P11.remove").WithLocation(14, 43), // (15,37): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(15, 37), // (15,37): warning CS0626: Method, operator, or accessor 'I1.P12.add' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "add").WithArguments("I1.P12.add").WithLocation(15, 37), // (15,40): error CS0073: An add or remove accessor must have a body // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(15, 40), // (15,42): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(15, 42), // (15,42): warning CS0626: Method, operator, or accessor 'I1.P12.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "remove").WithArguments("I1.P12.remove").WithLocation(15, 42), // (15,48): error CS0073: An add or remove accessor must have a body // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(15, 48), // (16,32): error CS8703: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern event System.Action P13; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P13").WithArguments("extern", "7.3", "8.0").WithLocation(16, 32), // (16,32): warning CS0626: Method, operator, or accessor 'I1.P13.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P13; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P13").WithArguments("I1.P13.remove").WithLocation(16, 32), // (17,43): error CS8703: The modifier 'private protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private protected event System.Action P14; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P14").WithArguments("private protected", "7.3", "8.0").WithLocation(17, 43), // (18,35): error CS8703: The modifier 'protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // protected event System.Action P15; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P15").WithArguments("protected", "7.3", "8.0").WithLocation(18, 35), // (19,44): error CS8703: The modifier 'protected internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // protected internal event System.Action P16; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P16").WithArguments("protected internal", "7.3", "8.0").WithLocation(19, 44) ); ValidateSymbolsEventModifiers_01(compilation1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_EventNeedsBothAccessors).Verify( // (5,35): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected event System.Action P02 {add{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P02").WithLocation(5, 35), // (5,40): error CS8701: Target runtime doesn't support default interface implementation. // protected event System.Action P02 {add{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(5, 40), // (6,44): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal event System.Action P03 {remove{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P03").WithLocation(6, 44), // (6,49): error CS8701: Target runtime doesn't support default interface implementation. // protected internal event System.Action P03 {remove{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(6, 49), // (7,39): error CS8701: Target runtime doesn't support default interface implementation. // internal event System.Action P04 {add{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(7, 39), // (8,38): error CS8701: Target runtime doesn't support default interface implementation. // private event System.Action P05 {remove{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(8, 38), // (9,37): error CS8701: Target runtime doesn't support default interface implementation. // static event System.Action P06 {add{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(9, 37), // (10,38): error CS8701: Target runtime doesn't support default interface implementation. // virtual event System.Action P07 {remove{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(10, 38), // (11,37): error CS8701: Target runtime doesn't support default interface implementation. // sealed event System.Action P08 {add{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(11, 37), // (12,34): error CS0106: The modifier 'override' is not valid for this item // override event System.Action P09 {remove{}} Diagnostic(ErrorCode.ERR_BadMemberFlag, "P09").WithArguments("override").WithLocation(12, 34), // (12,39): error CS8701: Target runtime doesn't support default interface implementation. // override event System.Action P09 {remove{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(12, 39), // (13,39): error CS8701: Target runtime doesn't support default interface implementation. // abstract event System.Action P10 {add{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(13, 39), // (13,38): error CS8712: 'I1.P10': abstract event cannot use event accessor syntax // abstract event System.Action P10 {add{}} Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.P10").WithLocation(13, 38), // (14,37): error CS8701: Target runtime doesn't support default interface implementation. // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(14, 37), // (14,37): error CS0179: 'I1.P11.add' cannot be extern and declare a body // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("I1.P11.add").WithLocation(14, 37), // (14,43): error CS8701: Target runtime doesn't support default interface implementation. // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(14, 43), // (14,43): error CS0179: 'I1.P11.remove' cannot be extern and declare a body // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("I1.P11.remove").WithLocation(14, 43), // (15,37): error CS8701: Target runtime doesn't support default interface implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(15, 37), // (15,37): warning CS0626: Method, operator, or accessor 'I1.P12.add' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "add").WithArguments("I1.P12.add").WithLocation(15, 37), // (15,40): error CS0073: An add or remove accessor must have a body // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(15, 40), // (15,42): error CS8701: Target runtime doesn't support default interface implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(15, 42), // (15,42): warning CS0626: Method, operator, or accessor 'I1.P12.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "remove").WithArguments("I1.P12.remove").WithLocation(15, 42), // (15,48): error CS0073: An add or remove accessor must have a body // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(15, 48), // (16,32): error CS8701: Target runtime doesn't support default interface implementation. // extern event System.Action P13; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P13").WithLocation(16, 32), // (16,32): warning CS0626: Method, operator, or accessor 'I1.P13.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P13; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P13").WithArguments("I1.P13.remove").WithLocation(16, 32), // (17,43): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected event System.Action P14; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P14").WithLocation(17, 43), // (18,35): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected event System.Action P15; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P15").WithLocation(18, 35), // (19,44): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal event System.Action P16; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P16").WithLocation(19, 44) ); ValidateSymbolsEventModifiers_01(compilation2); } [Fact] public void EventModifiers_03() { ValidateEventImplementation_102(@" public interface I1 { public virtual event System.Action E1 { add => System.Console.WriteLine(""add E1""); remove => System.Console.WriteLine(""remove E1""); } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.E1 += null; i1.E1 -= null; } } "); ValidateEventImplementation_102(@" public interface I1 { public virtual event System.Action E1 { add {System.Console.WriteLine(""add E1"");} remove {System.Console.WriteLine(""remove E1"");} } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.E1 += null; i1.E1 -= null; } } "); } [Fact] public void EventModifiers_04() { ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 {} } class Test1 : I1 {} ", new[] { // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 {} Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: false, haveRemove: false); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 { add; } } class Test1 : I1 {} ", new[] { // (6,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";"), // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: true, haveRemove: false); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 { add {} } } class Test1 : I1 {} ", new[] { // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: true, haveRemove: false); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 { add => throw null; } } class Test1 : I1 {} ", new[] { // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: true, haveRemove: false); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 { remove; } } class Test1 : I1 {} ", new[] { // (6,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 15), // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: false, haveRemove: true); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 { remove {} } } class Test1 : I1 {} ", new[] { // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: false, haveRemove: true); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 { remove => throw null; } } class Test1 : I1 {} ", new[] { // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: false, haveRemove: true); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 { add; remove; } } class Test1 : I1 {} ", new[] { // (6,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";"), // (7,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(7, 15) }, haveAdd: true, haveRemove: true); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1; } class Test1 : I1 {} ", new[] { // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1; Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40), // (4,40): warning CS0067: The event 'I1.E1' is never used // public virtual event System.Action E1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: true, haveRemove: true); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 = null; } class Test1 : I1 {} ", new[] { // (4,40): error CS0068: 'I1.E1': instance event in interface cannot have initializer // public virtual event System.Action E1 = null; Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "E1").WithArguments("I1.E1").WithLocation(4, 40), // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 = null; Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40), // (4,40): warning CS0067: The event 'I1.E1' is never used // public virtual event System.Action E1 = null; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: true, haveRemove: true); } [Fact] public void EventModifiers_05() { var source1 = @" public interface I1 { public abstract event System.Action P1; } public interface I2 { event System.Action P2; } class Test1 : I1 { public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove => System.Console.WriteLine(""set_P1""); } } class Test2 : I2 { public event System.Action P2 { add { System.Console.WriteLine(""get_P2""); } remove => System.Console.WriteLine(""set_P2""); } static void Main() { I1 x = new Test1(); x.P1 += null; x.P1 -= null; I2 y = new Test2(); y.P2 += null; y.P2 -= null; } } "; ValidateEventModifiers_05(source1); } private void ValidateEventModifiers_05(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: @"get_P1 set_P1 get_P2 set_P2", symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { for (int i = 1; i <= 2; i++) { var test1 = m.GlobalNamespace.GetTypeMember("Test" + i); var i1 = m.GlobalNamespace.GetTypeMember("I" + i); var p1 = GetSingleEvent(i1); var test1P1 = GetSingleEvent(test1); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Same(test1P1, test1.FindImplementationForInterfaceMember(p1)); ValidateAccessor(p1.AddMethod, test1P1.AddMethod); ValidateAccessor(p1.RemoveMethod, test1P1.RemoveMethod); void ValidateAccessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(implementation, test1.FindImplementationForInterfaceMember(accessor)); } } } } private static EventSymbol GetSingleEvent(NamedTypeSymbol container) { return container.GetMembers().OfType<EventSymbol>().Single(); } private static EventSymbol GetSingleEvent(CSharpCompilation compilation, string containerName) { return GetSingleEvent(compilation.GetTypeByMetadataName(containerName)); } private static EventSymbol GetSingleEvent(ModuleSymbol m, string containerName) { return GetSingleEvent(m.GlobalNamespace.GetTypeMember(containerName)); } [Fact] public void EventModifiers_06() { var source1 = @" public interface I1 { public abstract event System.Action P1; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3); compilation1.VerifyDiagnostics( // (4,41): error CS8503: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract event System.Action P1; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("abstract", "7.3", "8.0").WithLocation(4, 41), // (4,41): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract event System.Action P1; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("public", "7.3", "8.0").WithLocation(4, 41) ); ValidateEventModifiers_06(compilation1); } private static void ValidateEventModifiers_06(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMember<EventSymbol>("P1"); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); ValidateAccessor(p1.AddMethod); ValidateAccessor(p1.RemoveMethod); void ValidateAccessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } } [Fact] public void EventModifiers_07() { var source1 = @" public interface I1 { public static event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } internal static event System.Action P2 { add { System.Console.WriteLine(""get_P2""); P3 += value; } remove { System.Console.WriteLine(""set_P2""); P3 -= value; } } private static event System.Action P3 { add => System.Console.WriteLine(""get_P3""); remove => System.Console.WriteLine(""set_P3""); } } class Test1 : I1 { static void Main() { I1.P1 += null; I1.P1 -= null; I1.P2 += null; I1.P2 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 get_P3 set_P2 set_P3", symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); foreach (var tuple in new[] { (name: "P1", access: Accessibility.Public), (name: "P2", access: Accessibility.Internal), (name: "P3", access: Accessibility.Private)}) { var p1 = i1.GetMember<EventSymbol>(tuple.name); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.True(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(tuple.access, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); ValidateAccessor(p1.AddMethod); ValidateAccessor(p1.RemoveMethod); void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(tuple.access, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } var source2 = @" public interface I1 { public static event System.Action P1; internal static event System.Action P2 { add; remove; } private static event System.Action P3 = null; } class Test1 : I1 { static void Main() { } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,39): warning CS0067: The event 'I1.P1' is never used // public static event System.Action P1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P1").WithArguments("I1.P1").WithLocation(4, 39), // (8,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(8, 12), // (9,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(9, 15), // (12,40): warning CS0414: The field 'I1.P3' is assigned but its value is never used // private static event System.Action P3 = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "P3").WithArguments("I1.P3").WithLocation(12, 40) ); Validate(compilation2.SourceModule); var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyEmitDiagnostics( // (4,39): error CS8701: Target runtime doesn't support default interface implementation. // public static event System.Action P1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P1").WithLocation(4, 39), // (4,39): warning CS0067: The event 'I1.P1' is never used // public static event System.Action P1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P1").WithArguments("I1.P1").WithLocation(4, 39), // (8,9): error CS8701: Target runtime doesn't support default interface implementation. // add; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(8, 9), // (8,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(8, 12), // (9,9): error CS8701: Target runtime doesn't support default interface implementation. // remove; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(9, 9), // (9,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(9, 15), // (12,40): error CS8701: Target runtime doesn't support default interface implementation. // private static event System.Action P3 = null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P3").WithLocation(12, 40), // (12,40): warning CS0414: The field 'I1.P3' is assigned but its value is never used // private static event System.Action P3 = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "P3").WithArguments("I1.P3").WithLocation(12, 40) ); Validate(compilation3.SourceModule); } [Fact] public void EventModifiers_08() { var source1 = @" public interface I1 { abstract static event System.Action P1; virtual static event System.Action P2 {add {} remove{}} sealed static event System.Action P3 {add; remove;} } class Test1 : I1 { event System.Action I1.P1 {add {} remove{}} event System.Action I1.P2 {add {} remove{}} event System.Action I1.P3 {add {} remove{}} } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,46): error CS0073: An add or remove accessor must have a body // sealed static event System.Action P3 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(8, 46), // (8,54): error CS0073: An add or remove accessor must have a body // sealed static event System.Action P3 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(8, 54), // (6,40): error CS0112: A static member cannot be marked as 'virtual' // virtual static event System.Action P2 {add {} remove{}} Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P2").WithArguments("virtual").WithLocation(6, 40), // (8,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static event System.Action P3 {add; remove;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P3").WithArguments("sealed", "9.0", "preview").WithLocation(8, 39), // (4,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P1; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("abstract", "9.0", "preview").WithLocation(4, 41), // (13,28): error CS0539: 'Test1.P1' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.P1 {add {} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("Test1.P1").WithLocation(13, 28), // (14,28): error CS0539: 'Test1.P2' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.P2 {add {} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P2").WithArguments("Test1.P2").WithLocation(14, 28), // (15,28): error CS0539: 'Test1.P3' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.P3 {add {} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test1.P3").WithLocation(15, 28), // (18,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(18, 15), // (11,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(11, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMember<EventSymbol>("P1"); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.True(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); ValidateAccessor1(p1.AddMethod); ValidateAccessor1(p1.RemoveMethod); void ValidateAccessor1(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } var p2 = i1.GetMember<EventSymbol>("P2"); Assert.False(p2.IsAbstract); Assert.False(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.True(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2)); ValidateAccessor2(p2.AddMethod); ValidateAccessor2(p2.RemoveMethod); void ValidateAccessor2(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } var p3 = i1.GetMember<EventSymbol>("P3"); Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.False(p3.IsSealed); Assert.True(p3.IsStatic); Assert.False(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); ValidateAccessor3(p3.AddMethod); ValidateAccessor3(p3.RemoveMethod); void ValidateAccessor3(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } [Fact] public void EventModifiers_09() { var source1 = @" public interface I1 { private event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } sealed void M() { P1 += null; P1 -= null; } } public interface I2 { private event System.Action P2 { add => System.Console.WriteLine(""get_P2""); remove => System.Console.WriteLine(""set_P2""); } sealed void M() { P2 += null; P2 -= null; } } class Test1 : I1, I2 { static void Main() { I1 x1 = new Test1(); x1.M(); I2 x2 = new Test1(); x2.M(); } } "; ValidateEventModifiers_09(source1); } private void ValidateEventModifiers_09(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 set_P2 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); for (int i = 1; i <= 2; i++) { var i1 = m.GlobalNamespace.GetTypeMember("I" + i); var p1 = GetSingleEvent(i1); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Private, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); ValidateAccessor(p1.AddMethod); ValidateAccessor(p1.RemoveMethod); void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } } [Fact] public void EventModifiers_10() { var source1 = @" public interface I1 { abstract private event System.Action P1; virtual private event System.Action P2; sealed private event System.Action P3 { add => throw null; remove {} } private event System.Action P4 = null; } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics( // (4,42): error CS0621: 'I1.P1': virtual or abstract members cannot be private // abstract private event System.Action P1; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P1").WithArguments("I1.P1").WithLocation(4, 42), // (6,41): error CS0065: 'I1.P2': event property must have both add and remove accessors // virtual private event System.Action P2; Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P2").WithArguments("I1.P2").WithLocation(6, 41), // (6,41): error CS0621: 'I1.P2': virtual or abstract members cannot be private // virtual private event System.Action P2; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P2").WithArguments("I1.P2").WithLocation(6, 41), // (6,41): warning CS0067: The event 'I1.P2' is never used // virtual private event System.Action P2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P2").WithArguments("I1.P2").WithLocation(6, 41), // (8,40): error CS0238: 'I1.P3' cannot be sealed because it is not an override // sealed private event System.Action P3 Diagnostic(ErrorCode.ERR_SealedNonOverride, "P3").WithArguments("I1.P3").WithLocation(8, 40), // (14,33): error CS0068: 'I1.P4': instance event in interface cannot have initializer // private event System.Action P4 = null; Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "P4").WithArguments("I1.P4").WithLocation(14, 33), // (14,33): error CS0065: 'I1.P4': event property must have both add and remove accessors // private event System.Action P4 = null; Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P4").WithArguments("I1.P4").WithLocation(14, 33), // (17,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1"), // (14,33): warning CS0067: The event 'I1.P4' is never used // private event System.Action P4 = null; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P4").WithArguments("I1.P4").WithLocation(14, 33) ); ValidateEventModifiers_10(compilation1); } private static void ValidateEventModifiers_10(CSharpCompilation compilation1) { var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMembers().OfType<EventSymbol>().ElementAt(0); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Private, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); ValidateP1Accessor(p1.AddMethod); ValidateP1Accessor(p1.RemoveMethod); void ValidateP1Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } var p2 = i1.GetMembers().OfType<EventSymbol>().ElementAt(1); Assert.False(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Private, p2.DeclaredAccessibility); Assert.Same(p2, test1.FindImplementationForInterfaceMember(p2)); ValidateP2Accessor(p2.AddMethod); ValidateP2Accessor(p2.RemoveMethod); void ValidateP2Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Same(accessor, test1.FindImplementationForInterfaceMember(accessor)); } var p3 = i1.GetMembers().OfType<EventSymbol>().ElementAt(2); Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.True(p3.IsSealed); Assert.False(p3.IsStatic); Assert.False(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Private, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.AddMethod); ValidateP3Accessor(p3.RemoveMethod); void ValidateP3Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.True(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } var p4 = i1.GetMembers().OfType<EventSymbol>().ElementAt(3); Assert.False(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.False(p4.IsStatic); Assert.False(p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Private, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); ValidateP4Accessor(p4.AddMethod); ValidateP4Accessor(p4.RemoveMethod); void ValidateP4Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } [Fact] public void EventModifiers_11_01() { var source1 = @" public interface I1 { internal abstract event System.Action P1; sealed void Test() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11(source1, source2, Accessibility.Internal, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } private void ValidateEventModifiers_11(string source1, string source2, Accessibility accessibility, DiagnosticDescription[] expected1, params DiagnosticDescription[] expected2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected1); Validate1(compilation1.SourceModule); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => Validate1(m)).VerifyDiagnostics(); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var p1 = GetSingleEvent(i1); var test1P1 = GetSingleEvent(test1); var p1add = p1.AddMethod; var p1remove = p1.RemoveMethod; ValidateEvent(p1); ValidateMethod(p1add); ValidateMethod(p1remove); Assert.Same(test1P1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test1P1.AddMethod, test1.FindImplementationForInterfaceMember(p1add)); Assert.Same(test1P1.RemoveMethod, test1.FindImplementationForInterfaceMember(p1remove)); } void ValidateEvent(EventSymbol p1) { Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(accessibility, p1.DeclaredAccessibility); } void ValidateMethod(MethodSymbol m1) { Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(accessibility, m1.DeclaredAccessibility); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var p1 = GetSingleEvent(i1); ValidateEvent(p1); ValidateMethod(p1.AddMethod); ValidateMethod(p1.RemoveMethod); } var source3 = @" class Test2 : I1 { } "; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected1); Validate1(compilation3.SourceModule); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => Validate1(m)).VerifyDiagnostics(); Validate1(compilation3.SourceModule); var compilation5 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics(expected2); ValidateEventNotImplemented_11(compilation5, "Test2"); } } private static void ValidateEventNotImplemented_11(CSharpCompilation compilation, string className) { var test2 = compilation.GetTypeByMetadataName(className); var i1 = compilation.GetTypeByMetadataName("I1"); var p1 = GetSingleEvent(i1); Assert.Null(test2.FindImplementationForInterfaceMember(p1)); Assert.Null(test2.FindImplementationForInterfaceMember(p1.AddMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p1.RemoveMethod)); } [Fact] public void EventModifiers_11_02() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_02(source1, source2, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 15) ); } private void ValidateEventModifiers_11_02(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(expected); ValidateEventImplementation_11(compilation1.SourceModule); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateEventImplementation_11(m)).VerifyDiagnostics(); ValidateEventImplementation_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(expected); ValidateEventImplementation_11(compilation3.SourceModule); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateEventImplementation_11(m)).VerifyDiagnostics(); ValidateEventImplementation_11(compilation3.SourceModule); } } private static void ValidateEventImplementation_11(ModuleSymbol m) { ValidateEventImplementation_11(m, implementedByBase: false); } private static void ValidateEventImplementationByBase_11(ModuleSymbol m) { ValidateEventImplementation_11(m, implementedByBase: true); } private static void ValidateEventImplementation_11(ModuleSymbol m, bool implementedByBase) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var p1 = GetSingleEvent(i1); var test1P1 = GetSingleEvent(implementedByBase ? test1.BaseTypeNoUseSiteDiagnostics : test1); var p1Add = p1.AddMethod; var p1Remove = p1.RemoveMethod; Assert.Same(test1P1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test1P1.AddMethod, test1.FindImplementationForInterfaceMember(p1Add)); Assert.Same(test1P1.RemoveMethod, test1.FindImplementationForInterfaceMember(p1Remove)); Assert.True(test1P1.AddMethod.IsMetadataVirtual()); Assert.True(test1P1.RemoveMethod.IsMetadataVirtual()); } [Fact] public void EventModifiers_11_03() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } event System.Action I1.P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_03(source1, source2, TargetFramework.Standard, // (9,28): error CS0122: 'I1.P1' is inaccessible due to its protection level // event System.Action I1.P1 Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(9, 28) ); } private void ValidateEventModifiers_11_03(string source1, string source2, TargetFramework targetFramework, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, targetFramework: targetFramework, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: !(targetFramework == TargetFramework.Standard || ExecutionConditionUtil.IsMonoOrCoreClr) ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementation_11); ValidateEventImplementation_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: targetFramework, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: targetFramework); compilation3.VerifyDiagnostics(expected); if (expected.Length == 0) { CompileAndVerify(compilation3, expectedOutput: !(targetFramework == TargetFramework.Standard || ExecutionConditionUtil.IsMonoOrCoreClr) ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementation_11); } ValidateEventImplementation_11(compilation3.SourceModule); } } [Fact] public void EventModifiers_11_04() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } public class Test2 : I1 { event System.Action I1.P1 { add { System.Console.WriteLine(""Test2.get_P1""); } remove { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void EventModifiers_11_05() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } public class Test2 : I1 { event System.Action I1.P1 { add { System.Console.WriteLine(""Test2.get_P1""); } remove { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void EventModifiers_11_06() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } public class Test2 : I1 { event System.Action I1.P1 { add { System.Console.WriteLine(""Test2.get_P1""); } remove { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test3()); } public abstract event System.Action P1; } class Test3 : Test1 { public override event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void EventModifiers_11_07() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } public class Test2 : I1 { event System.Action I1.P1 { add { System.Console.WriteLine(""Test2.get_P1""); } remove { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallP1(new Test1()); } public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } public interface I2 { event System.Action P1; } "; ValidateEventModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void EventModifiers_11_08() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } public class Test2 : I1 { event System.Action I1.P1 { add { System.Console.WriteLine(""Test2.get_P1""); } remove { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual event System.Action<object> P1 { add { System.Console.WriteLine(""Test1.get_P1""); } remove { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidateEventModifiers_11_08(source1, source2); } private void ValidateEventModifiers_11_08(string source1, string source2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: @"Test2.get_P1 Test2.set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationByBase_11); ValidateEventImplementationByBase_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation3, expectedOutput: @"Test2.get_P1 Test2.set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationByBase_11); ValidateEventImplementationByBase_11(compilation3.SourceModule); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation4, expectedOutput: @"Test2.get_P1 Test2.set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationByBase_11); ValidateEventImplementationByBase_11(compilation4.SourceModule); } [Fact] public void EventModifiers_11_09() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual event System.Action<object> P1 { add { System.Console.WriteLine(""Test1.get_P1""); } remove { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidateEventModifiers_11_09(source1, source2, // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.P1'. 'Test1.P1' cannot implement 'I1.P1' because it does not have the matching return type of 'Action'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.P1", "Test1.P1", "System.Action").WithLocation(2, 15) ); } private void ValidateEventModifiers_11_09(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics(expected); ValidateEventNotImplemented_11(compilation1, "Test1"); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation3.VerifyDiagnostics(expected); ValidateEventNotImplemented_11(compilation3, "Test1"); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation4.VerifyDiagnostics(expected); ValidateEventNotImplemented_11(compilation4, "Test1"); } [Fact] public void EventModifiers_11_10() { var source1 = @" public interface I1 { internal abstract event System.Action P1; sealed void Test() { P1 += null; P1 -= null; } } "; var source2 = @" public class Test2 : I1 { public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidateEventModifiers_11_10(source1, source2, // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.remove'. 'Test2.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.remove", "Test2.P1.remove", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.add'. 'Test2.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.add", "Test2.P1.add", "9.0", "10.0").WithLocation(2, 22) ); } private void ValidateEventModifiers_11_10(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(expected); ValidateEventImplementationByBase_11(compilation1.SourceModule); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateEventImplementationByBase_11(m)).VerifyDiagnostics(); ValidateEventImplementationByBase_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(expected); ValidateEventImplementationByBase_11(compilation3.SourceModule); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateEventImplementationByBase_11(m)).VerifyDiagnostics(); ValidateEventImplementationByBase_11(compilation3.SourceModule); } } [Fact] public void EventModifiers_11_11() { var source1 = @" public interface I1 { internal abstract event System.Action P1; sealed void Test() { P1 += null; P1 -= null; } } public class Test2 : I1 { public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidateEventModifiers_11_11(source1, source2, // (12,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.remove'. 'Test2.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.remove", "Test2.P1.remove", "9.0", "10.0").WithLocation(12, 22), // (12,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.add'. 'Test2.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.add", "Test2.P1.add", "9.0", "10.0").WithLocation(12, 22) ); } private void ValidateEventModifiers_11_11(string source1, string source2, params DiagnosticDescription[] expected) { var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, assemblyName: "EventModifiers_11_11"); compilation2.VerifyDiagnostics(expected); compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp, assemblyName: "EventModifiers_11_11"); compilation2.VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateEventImplementationByBase_11(m)).VerifyDiagnostics(); ValidateEventImplementationByBase_11(compilation3.SourceModule); } [Fact] public void EventModifiers_12() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMember<EventSymbol>("P1"); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Null(test1.FindImplementationForInterfaceMember(p1.AddMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(p1.RemoveMethod)); } [Fact] public void EventModifiers_13() { var source1 = @" public interface I1 { public sealed event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } public interface I2 { public sealed event System.Action P2 { add => System.Console.WriteLine(""get_P2""); remove => System.Console.WriteLine(""set_P2""); } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.P1 += null; i1.P1 -= null; I2 i2 = new Test2(); i2.P2 += null; i2.P2 -= null; } public event System.Action P1 { add => throw null; remove => throw null; } } class Test2 : I2 { public event System.Action P2 { add => throw null; remove => throw null; } } "; ValidateEventModifiers_13(source1); } private void ValidateEventModifiers_13(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate(ModuleSymbol m) { for (int i = 1; i <= 2; i++) { var test1 = m.GlobalNamespace.GetTypeMember("Test" + i); var i1 = m.GlobalNamespace.GetTypeMember("I" + i); var p1 = GetSingleEvent(i1); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); ValidateAccessor(p1.AddMethod); ValidateAccessor(p1.RemoveMethod); void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 set_P2 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); } [Fact] public void EventModifiers_14() { var source1 = @" public interface I1 { public sealed event System.Action P1 = null; } public interface I2 { abstract sealed event System.Action P2 {add; remove;} } public interface I3 { virtual sealed event System.Action P3 { add {} remove {} } } class Test1 : I1, I2, I3 { event System.Action I1.P1 { add => throw null; remove => throw null; } event System.Action I2.P2 { add => throw null; remove => throw null; } event System.Action I3.P3 { add => throw null; remove => throw null; } } class Test2 : I1, I2, I3 {} "; ValidateEventModifiers_14(source1, // (4,39): error CS0068: 'I1.P1': instance event in interface cannot have initializer // public sealed event System.Action P1 = null; Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "P1").WithArguments("I1.P1").WithLocation(4, 39), // (4,39): error CS0065: 'I1.P1': event property must have both add and remove accessors // public sealed event System.Action P1; Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P1").WithArguments("I1.P1").WithLocation(4, 39), // (8,41): error CS0238: 'I2.P2' cannot be sealed because it is not an override // abstract sealed event System.Action P2 {add; remove;} Diagnostic(ErrorCode.ERR_SealedNonOverride, "P2").WithArguments("I2.P2").WithLocation(8, 41), // (8,44): error CS8712: 'I2.P2': abstract event cannot use event accessor syntax // abstract sealed event System.Action P2 {add; remove;} Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.P2").WithLocation(8, 44), // (12,40): error CS0238: 'I3.P3' cannot be sealed because it is not an override // virtual sealed event System.Action P3 Diagnostic(ErrorCode.ERR_SealedNonOverride, "P3").WithArguments("I3.P3").WithLocation(12, 40), // (21,28): error CS0539: 'Test1.P1' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.P1 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("Test1.P1").WithLocation(21, 28), // (22,28): error CS0539: 'Test1.P2' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I2.P2 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P2").WithArguments("Test1.P2").WithLocation(22, 28), // (23,28): error CS0539: 'Test1.P3' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I3.P3 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test1.P3").WithLocation(23, 28), // (4,39): warning CS0067: The event 'I1.P1' is never used // public sealed event System.Action P1 = null; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P1").WithArguments("I1.P1").WithLocation(4, 39) ); } private void ValidateEventModifiers_14(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var p1 = GetSingleEvent(compilation1, "I1"); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Null(test2.FindImplementationForInterfaceMember(p1)); Validate1(p1.AddMethod); Validate1(p1.RemoveMethod); void Validate1(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p2 = GetSingleEvent(compilation1, "I2"); var test1P2 = test1.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); Assert.True(p2.IsAbstract); Assert.False(p2.IsVirtual); Assert.True(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2)); Assert.Null(test2.FindImplementationForInterfaceMember(p2)); Validate2(p2.AddMethod); Validate2(p2.RemoveMethod); void Validate2(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.True(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p3 = GetSingleEvent(compilation1, "I3"); var test1P3 = test1.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I3.")).Single(); Assert.False(p3.IsAbstract); Assert.True(p3.IsVirtual); Assert.True(p3.IsSealed); Assert.False(p3.IsStatic); Assert.False(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); Validate3(p3.AddMethod); Validate3(p3.RemoveMethod); void Validate3(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.True(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } } [Fact] public void EventModifiers_15() { var source1 = @" public interface I0 { abstract virtual event System.Action P0; } public interface I1 { abstract virtual event System.Action P1 { add { throw null; } } } public interface I2 { virtual abstract event System.Action P2 { add { throw null; } remove { throw null; } } } public interface I3 { abstract virtual event System.Action P3 { remove { throw null; } } } public interface I4 { abstract virtual event System.Action P4 { add => throw null; } } public interface I5 { abstract virtual event System.Action P5 { add => throw null; remove => throw null; } } public interface I6 { abstract virtual event System.Action P6 { remove => throw null; } } public interface I7 { abstract virtual event System.Action P7 { add; } } public interface I8 { abstract virtual event System.Action P8 { remove; } } class Test1 : I0, I1, I2, I3, I4, I5, I6, I7, I8 { event System.Action I0.P0 { add { throw null; } remove { throw null; } } event System.Action I1.P1 { add { throw null; } } event System.Action I2.P2 { add { throw null; } remove { throw null; } } event System.Action I3.P3 { remove { throw null; } } event System.Action I4.P4 { add { throw null; } } event System.Action I5.P5 { add { throw null; } remove { throw null; } } event System.Action I6.P6 { remove { throw null; } } event System.Action I7.P7 { add { throw null; } } event System.Action I8.P8 { remove { throw null; } } } class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 {} "; ValidateEventModifiers_15(source1, // (4,42): error CS0503: The abstract event 'I0.P0' cannot be marked virtual // abstract virtual event System.Action P0; Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P0").WithArguments("event", "I0.P0").WithLocation(4, 42), // (8,42): error CS0503: The abstract event 'I1.P1' cannot be marked virtual // abstract virtual event System.Action P1 { add { throw null; } } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P1").WithArguments("event", "I1.P1").WithLocation(8, 42), // (8,45): error CS8712: 'I1.P1': abstract event cannot use event accessor syntax // abstract virtual event System.Action P1 { add { throw null; } } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.P1").WithLocation(8, 45), // (12,42): error CS0503: The abstract event 'I2.P2' cannot be marked virtual // virtual abstract event System.Action P2 Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P2").WithArguments("event", "I2.P2").WithLocation(12, 42), // (13,5): error CS8712: 'I2.P2': abstract event cannot use event accessor syntax // { Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.P2").WithLocation(13, 5), // (20,42): error CS0503: The abstract event 'I3.P3' cannot be marked virtual // abstract virtual event System.Action P3 { remove { throw null; } } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P3").WithArguments("event", "I3.P3").WithLocation(20, 42), // (20,45): error CS8712: 'I3.P3': abstract event cannot use event accessor syntax // abstract virtual event System.Action P3 { remove { throw null; } } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I3.P3").WithLocation(20, 45), // (24,42): error CS0503: The abstract event 'I4.P4' cannot be marked virtual // abstract virtual event System.Action P4 { add => throw null; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P4").WithArguments("event", "I4.P4").WithLocation(24, 42), // (24,45): error CS8712: 'I4.P4': abstract event cannot use event accessor syntax // abstract virtual event System.Action P4 { add => throw null; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I4.P4").WithLocation(24, 45), // (28,42): error CS0503: The abstract event 'I5.P5' cannot be marked virtual // abstract virtual event System.Action P5 Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P5").WithArguments("event", "I5.P5").WithLocation(28, 42), // (29,5): error CS8712: 'I5.P5': abstract event cannot use event accessor syntax // { Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I5.P5").WithLocation(29, 5), // (36,42): error CS0503: The abstract event 'I6.P6' cannot be marked virtual // abstract virtual event System.Action P6 { remove => throw null; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P6").WithArguments("event", "I6.P6").WithLocation(36, 42), // (36,45): error CS8712: 'I6.P6': abstract event cannot use event accessor syntax // abstract virtual event System.Action P6 { remove => throw null; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I6.P6").WithLocation(36, 45), // (40,42): error CS0503: The abstract event 'I7.P7' cannot be marked virtual // abstract virtual event System.Action P7 { add; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P7").WithArguments("event", "I7.P7").WithLocation(40, 42), // (40,45): error CS8712: 'I7.P7': abstract event cannot use event accessor syntax // abstract virtual event System.Action P7 { add; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I7.P7").WithLocation(40, 45), // (44,42): error CS0503: The abstract event 'I8.P8' cannot be marked virtual // abstract virtual event System.Action P8 { remove; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P8").WithArguments("event", "I8.P8").WithLocation(44, 42), // (44,45): error CS8712: 'I8.P8': abstract event cannot use event accessor syntax // abstract virtual event System.Action P8 { remove; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I8.P8").WithLocation(44, 45), // (54,28): error CS0065: 'Test1.I1.P1': event property must have both add and remove accessors // event System.Action I1.P1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P1").WithArguments("Test1.I1.P1").WithLocation(54, 28), // (63,28): error CS0065: 'Test1.I3.P3': event property must have both add and remove accessors // event System.Action I3.P3 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P3").WithArguments("Test1.I3.P3").WithLocation(63, 28), // (67,28): error CS0065: 'Test1.I4.P4': event property must have both add and remove accessors // event System.Action I4.P4 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P4").WithArguments("Test1.I4.P4").WithLocation(67, 28), // (76,28): error CS0065: 'Test1.I6.P6': event property must have both add and remove accessors // event System.Action I6.P6 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P6").WithArguments("Test1.I6.P6").WithLocation(76, 28), // (80,28): error CS0065: 'Test1.I7.P7': event property must have both add and remove accessors // event System.Action I7.P7 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P7").WithArguments("Test1.I7.P7").WithLocation(80, 28), // (84,28): error CS0065: 'Test1.I8.P8': event property must have both add and remove accessors // event System.Action I8.P8 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P8").WithArguments("Test1.I8.P8").WithLocation(84, 28), // (90,15): error CS0535: 'Test2' does not implement interface member 'I0.P0' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I0").WithArguments("Test2", "I0.P0").WithLocation(90, 15), // (90,19): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(90, 19), // (90,23): error CS0535: 'Test2' does not implement interface member 'I2.P2' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I2.P2").WithLocation(90, 23), // (90,27): error CS0535: 'Test2' does not implement interface member 'I3.P3' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test2", "I3.P3").WithLocation(90, 27), // (90,31): error CS0535: 'Test2' does not implement interface member 'I4.P4' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test2", "I4.P4").WithLocation(90, 31), // (90,35): error CS0535: 'Test2' does not implement interface member 'I5.P5' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I5").WithArguments("Test2", "I5.P5").WithLocation(90, 35), // (90,39): error CS0535: 'Test2' does not implement interface member 'I6.P6' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I6").WithArguments("Test2", "I6.P6").WithLocation(90, 39), // (90,43): error CS0535: 'Test2' does not implement interface member 'I7.P7' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I7").WithArguments("Test2", "I7.P7").WithLocation(90, 43), // (90,47): error CS0535: 'Test2' does not implement interface member 'I8.P8' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I8").WithArguments("Test2", "I8.P8").WithLocation(90, 47) ); } private void ValidateEventModifiers_15(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); for (int i = 0; i <= 8; i++) { var i1 = compilation1.GetTypeByMetadataName("I" + i); var p2 = GetSingleEvent(i1); var test1P2 = test1.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith(i1.Name)).Single(); Assert.True(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Same(test1P2, test1.FindImplementationForInterfaceMember(p2)); Assert.Null(test2.FindImplementationForInterfaceMember(p2)); switch (i) { case 3: case 6: case 8: Assert.Null(p2.AddMethod); ValidateAccessor(p2.RemoveMethod, test1P2.RemoveMethod); break; case 1: case 4: case 7: Assert.Null(p2.RemoveMethod); ValidateAccessor(p2.AddMethod, test1P2.AddMethod); break; default: ValidateAccessor(p2.AddMethod, test1P2.AddMethod); ValidateAccessor(p2.RemoveMethod, test1P2.RemoveMethod); break; } void ValidateAccessor(MethodSymbol accessor, MethodSymbol implementedBy) { Assert.True(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(implementedBy, test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } } } [Fact] public void EventModifiers_16() { var source1 = @" public interface I1 { extern event System.Action P1; } public interface I2 { virtual extern event System.Action P2; } public interface I3 { static extern event System.Action P3; } public interface I4 { private extern event System.Action P4; } public interface I5 { extern sealed event System.Action P5; } public interface I6 { static event System.Action P6 { add => throw null; remove => throw null; } } class Test1 : I1, I2, I3, I4, I5 { } class Test2 : I1, I2, I3, I4, I5 { event System.Action I1.P1 { add{} remove{} } event System.Action I2.P2 { add{} remove{} } } "; ValidateEventModifiers_16(source1); } private void ValidateEventModifiers_16(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test2 = m.GlobalNamespace.GetTypeMember("Test2"); bool isSource = !(m is PEModuleSymbol); var p1 = GetSingleEvent(m, "I1"); var test2P1 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I1.")).Single(); Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.Equal(isSource, p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test2P1, test2.FindImplementationForInterfaceMember(p1)); ValidateP1Accessor(p1.AddMethod, test2P1.AddMethod); ValidateP1Accessor(p1.RemoveMethod, test2P1.RemoveMethod); void ValidateP1Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.Equal(isSource, accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(accessor, test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p2 = GetSingleEvent(m, "I2"); var test2P2 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); Assert.False(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.Equal(isSource, p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Same(p2, test1.FindImplementationForInterfaceMember(p2)); Assert.Same(test2P2, test2.FindImplementationForInterfaceMember(p2)); ValidateP2Accessor(p2.AddMethod, test2P2.AddMethod); ValidateP2Accessor(p2.RemoveMethod, test2P2.RemoveMethod); void ValidateP2Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.Equal(isSource, accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(accessor, test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var i3 = m.ContainingAssembly.GetTypeByMetadataName("I3"); var p3 = GetSingleEvent(i3); Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.False(p3.IsSealed); Assert.True(p3.IsStatic); Assert.Equal(isSource, p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.AddMethod); ValidateP3Accessor(p3.RemoveMethod); void ValidateP3Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.Equal(isSource, accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p4 = GetSingleEvent(m, "I4"); Assert.False(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.False(p4.IsStatic); Assert.Equal(isSource, p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Private, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); Assert.Null(test2.FindImplementationForInterfaceMember(p4)); ValidateP4Accessor(p4.AddMethod); ValidateP4Accessor(p4.RemoveMethod); void ValidateP4Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.Equal(isSource, accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p5 = GetSingleEvent(m, "I5"); Assert.False(p5.IsAbstract); Assert.False(p5.IsVirtual); Assert.False(p5.IsSealed); Assert.False(p5.IsStatic); Assert.Equal(isSource, p5.IsExtern); Assert.False(p5.IsOverride); Assert.Equal(Accessibility.Public, p5.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5)); Assert.Null(test2.FindImplementationForInterfaceMember(p5)); ValidateP5Accessor(p5.AddMethod); ValidateP5Accessor(p5.RemoveMethod); void ValidateP5Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.Equal(isSource, accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern event System.Action P1; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("extern", "7.3", "8.0").WithLocation(4, 32), // (8,40): error CS8703: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern event System.Action P2; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P2").WithArguments("extern", "7.3", "8.0").WithLocation(8, 40), // (8,40): error CS8703: The modifier 'virtual' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern event System.Action P2; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P2").WithArguments("virtual", "7.3", "8.0").WithLocation(8, 40), // (12,39): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static extern event System.Action P3; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P3").WithArguments("static", "7.3", "8.0").WithLocation(12, 39), // (12,39): error CS8703: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static extern event System.Action P3; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P3").WithArguments("extern", "7.3", "8.0").WithLocation(12, 39), // (16,40): error CS8703: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern event System.Action P4; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P4").WithArguments("private", "7.3", "8.0").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern event System.Action P4; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P4").WithArguments("extern", "7.3", "8.0").WithLocation(16, 40), // (20,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed event System.Action P5; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P5").WithArguments("sealed", "7.3", "8.0").WithLocation(20, 39), // (20,39): error CS8703: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed event System.Action P5; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P5").WithArguments("extern", "7.3", "8.0").WithLocation(20, 39), // (24,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static event System.Action P6 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "P6").WithArguments("default interface implementation", "8.0").WithLocation(24, 32), // (8,40): warning CS0626: Method, operator, or accessor 'I2.P2.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern event System.Action P2; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P2").WithArguments("I2.P2.remove").WithLocation(8, 40), // (12,39): warning CS0626: Method, operator, or accessor 'I3.P3.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern event System.Action P3; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P3").WithArguments("I3.P3.remove").WithLocation(12, 39), // (16,40): warning CS0626: Method, operator, or accessor 'I4.P4.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern event System.Action P4; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P4").WithArguments("I4.P4.remove").WithLocation(16, 40), // (20,39): warning CS0626: Method, operator, or accessor 'I5.P5.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed event System.Action P5; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P5").WithArguments("I5.P5.remove").WithLocation(20, 39), // (4,32): warning CS0626: Method, operator, or accessor 'I1.P1.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P1; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P1").WithArguments("I1.P1.remove").WithLocation(4, 32) ); Validate(compilation2.SourceModule); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (4,32): error CS8701: Target runtime doesn't support default interface implementation. // extern event System.Action P1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P1").WithLocation(4, 32), // (8,40): error CS8701: Target runtime doesn't support default interface implementation. // virtual extern event System.Action P2; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P2").WithLocation(8, 40), // (16,40): error CS8701: Target runtime doesn't support default interface implementation. // private extern event System.Action P4; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P4").WithLocation(16, 40), // (20,39): error CS8701: Target runtime doesn't support default interface implementation. // extern sealed event System.Action P5; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P5").WithLocation(20, 39), // (8,40): warning CS0626: Method, operator, or accessor 'I2.P2.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern event System.Action P2; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P2").WithArguments("I2.P2.remove").WithLocation(8, 40), // (12,39): error CS8701: Target runtime doesn't support default interface implementation. // static extern event System.Action P3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P3").WithLocation(12, 39), // (12,39): warning CS0626: Method, operator, or accessor 'I3.P3.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern event System.Action P3; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P3").WithArguments("I3.P3.remove").WithLocation(12, 39), // (16,40): warning CS0626: Method, operator, or accessor 'I4.P4.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern event System.Action P4; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P4").WithArguments("I4.P4.remove").WithLocation(16, 40), // (20,39): warning CS0626: Method, operator, or accessor 'I5.P5.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed event System.Action P5; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P5").WithArguments("I5.P5.remove").WithLocation(20, 39), // (4,32): warning CS0626: Method, operator, or accessor 'I1.P1.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P1; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P1").WithArguments("I1.P1.remove").WithLocation(4, 32), // (26,9): error CS8701: Target runtime doesn't support default interface implementation. // add => throw null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(26, 9), // (27,9): error CS8701: Target runtime doesn't support default interface implementation. // remove => throw null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(27, 9) ); Validate(compilation3.SourceModule); } [Fact] public void EventModifiers_17() { var source1 = @" public interface I1 { abstract extern event System.Action P1; } public interface I2 { extern event System.Action P2 = null; } public interface I3 { static extern event System.Action P3 {add => throw null; remove => throw null;} } public interface I4 { private extern event System.Action P4 { add {throw null;} remove {throw null;}} } class Test1 : I1, I2, I3, I4 { } class Test2 : I1, I2, I3, I4 { event System.Action I1.P1 { add => throw null; remove => throw null;} event System.Action I2.P2 { add => throw null; remove => throw null;} event System.Action I3.P3 { add => throw null; remove => throw null;} event System.Action I4.P4 { add => throw null; remove => throw null;} } "; ValidateEventModifiers_17(source1, // (4,41): error CS0180: 'I1.P1' cannot be both extern and abstract // abstract extern event System.Action P1; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P1").WithArguments("I1.P1").WithLocation(4, 41), // (8,32): error CS0068: 'I2.P2': instance event in interface cannot have initializer // extern event System.Action P2 = null; Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "P2").WithArguments("I2.P2").WithLocation(8, 32), // (12,43): error CS0179: 'I3.P3.add' cannot be extern and declare a body // static extern event System.Action P3 {add => throw null; remove => throw null;} Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("I3.P3.add").WithLocation(12, 43), // (12,62): error CS0179: 'I3.P3.remove' cannot be extern and declare a body // static extern event System.Action P3 {add => throw null; remove => throw null;} Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("I3.P3.remove").WithLocation(12, 62), // (16,45): error CS0179: 'I4.P4.add' cannot be extern and declare a body // private extern event System.Action P4 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("I4.P4.add").WithLocation(16, 45), // (16,63): error CS0179: 'I4.P4.remove' cannot be extern and declare a body // private extern event System.Action P4 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("I4.P4.remove").WithLocation(16, 63), // (19,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1, I2, I3, I4 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(19, 15), // (27,28): error CS0539: 'Test2.P3' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I3.P3 { add => throw null; remove => throw null;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test2.P3").WithLocation(27, 28), // (28,28): error CS0539: 'Test2.P4' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I4.P4 { add => throw null; remove => throw null;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P4").WithArguments("Test2.P4").WithLocation(28, 28), // (8,32): warning CS0626: Method, operator, or accessor 'I2.P2.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P2 = null; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P2").WithArguments("I2.P2.remove").WithLocation(8, 32), // (8,32): warning CS0067: The event 'I2.P2' is never used // extern event System.Action P2 = null; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P2").WithArguments("I2.P2").WithLocation(8, 32) ); } private void ValidateEventModifiers_17(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var p1 = GetSingleEvent(compilation1, "I1"); var test2P1 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I1.")).Single(); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.True(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test2P1, test2.FindImplementationForInterfaceMember(p1)); ValidateP1Accessor(p1.AddMethod, test2P1.AddMethod); ValidateP1Accessor(p1.RemoveMethod, test2P1.RemoveMethod); void ValidateP1Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p2 = GetSingleEvent(compilation1, "I2"); var test2P2 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); Assert.False(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.True(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Same(p2, test1.FindImplementationForInterfaceMember(p2)); Assert.Same(test2P2, test2.FindImplementationForInterfaceMember(p2)); ValidateP2Accessor(p2.AddMethod, test2P2.AddMethod); ValidateP2Accessor(p2.RemoveMethod, test2P2.RemoveMethod); void ValidateP2Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(accessor, test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p3 = GetSingleEvent(compilation1, "I3"); var test2P3 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I3.")).Single(); Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.False(p3.IsSealed); Assert.True(p3.IsStatic); Assert.True(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.AddMethod); ValidateP3Accessor(p3.RemoveMethod); void ValidateP3Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p4 = GetSingleEvent(compilation1, "I4"); Assert.False(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.False(p4.IsStatic); Assert.True(p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Private, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); Assert.Null(test2.FindImplementationForInterfaceMember(p4)); ValidateP4Accessor(p4.AddMethod); ValidateP4Accessor(p4.RemoveMethod); void ValidateP4Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } } [Fact] public void EventModifiers_18() { var source1 = @" public interface I1 { abstract event System.Action P1 {add => throw null; remove => throw null;} } public interface I2 { abstract private event System.Action P2 = null; } public interface I3 { static extern event System.Action P3; } public interface I4 { abstract static event System.Action P4 { add {throw null;} remove {throw null;}} } public interface I5 { override sealed event System.Action P5 { add {throw null;} remove {throw null;}} } class Test1 : I1, I2, I3, I4, I5 { } class Test2 : I1, I2, I3, I4, I5 { event System.Action I1.P1 { add {throw null;} remove {throw null;}} event System.Action I2.P2 { add {throw null;} remove {throw null;}} event System.Action I3.P3 { add {throw null;} remove {throw null;}} event System.Action I4.P4 { add {throw null;} remove {throw null;}} event System.Action I5.P5 { add {throw null;} remove {throw null;}} } "; ValidateEventModifiers_18(source1, // (4,37): error CS8712: 'I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action P1 {add => throw null; remove => throw null;} Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.P1").WithLocation(4, 37), // (8,42): error CS0068: 'I2.P2': instance event in interface cannot have initializer // abstract private event System.Action P2 = null; Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "P2").WithArguments("I2.P2").WithLocation(8, 42), // (8,42): error CS0621: 'I2.P2': virtual or abstract members cannot be private // abstract private event System.Action P2 = null; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P2").WithArguments("I2.P2").WithLocation(8, 42), // (16,44): error CS8712: 'I4.P4': abstract event cannot use event accessor syntax // abstract static event System.Action P4 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I4.P4").WithLocation(16, 44), // (16,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P4 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P4").WithArguments("abstract", "9.0", "preview").WithLocation(16, 41), // (20,41): error CS0106: The modifier 'override' is not valid for this item // override sealed event System.Action P5 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_BadMemberFlag, "P5").WithArguments("override").WithLocation(20, 41), // (23,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(23, 15), // (23,19): error CS0535: 'Test1' does not implement interface member 'I2.P2' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I2.P2").WithLocation(23, 19), // (30,28): error CS0122: 'I2.P2' is inaccessible due to its protection level // event System.Action I2.P2 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I2.P2").WithLocation(30, 28), // (31,28): error CS0539: 'Test2.P3' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I3.P3 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test2.P3").WithLocation(31, 28), // (32,28): error CS0539: 'Test2.P4' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I4.P4 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P4").WithArguments("Test2.P4").WithLocation(32, 28), // (33,28): error CS0539: 'Test2.P5' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I5.P5 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P5").WithArguments("Test2.P5").WithLocation(33, 28), // (12,39): warning CS0626: Method, operator, or accessor 'I3.P3.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern event System.Action P3; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P3").WithArguments("I3.P3.remove").WithLocation(12, 39), // (23,27): error CS0535: 'Test1' does not implement interface member 'I4.P4' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test1", "I4.P4").WithLocation(23, 27), // (27,27): error CS0535: 'Test2' does not implement interface member 'I4.P4' // class Test2 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test2", "I4.P4").WithLocation(27, 27), // (8,42): warning CS0067: The event 'I2.P2' is never used // abstract private event System.Action P2 = null; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P2").WithArguments("I2.P2").WithLocation(8, 42) ); } private void ValidateEventModifiers_18(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var p1 = GetSingleEvent(compilation1, "I1"); var test2P1 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I1.")).Single(); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test2P1, test2.FindImplementationForInterfaceMember(p1)); ValidateP1Accessor(p1.AddMethod, test2P1.AddMethod); ValidateP1Accessor(p1.RemoveMethod, test2P1.RemoveMethod); void ValidateP1Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p2 = GetSingleEvent(compilation1, "I2"); var test2P2 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); Assert.True(p2.IsAbstract); Assert.False(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Private, p2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2)); Assert.Same(test2P2, test2.FindImplementationForInterfaceMember(p2)); ValidateP2Accessor(p2.AddMethod, test2P2.AddMethod); ValidateP2Accessor(p2.RemoveMethod, test2P2.RemoveMethod); void ValidateP2Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p3 = GetSingleEvent(compilation1, "I3"); var test2P3 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I3.")).Single(); Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.False(p3.IsSealed); Assert.True(p3.IsStatic); Assert.True(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.AddMethod); ValidateP3Accessor(p3.RemoveMethod); void ValidateP3Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p4 = GetSingleEvent(compilation1, "I4"); var test2P4 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I4.")).Single(); Assert.True(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.True(p4.IsStatic); Assert.False(p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Public, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); Assert.Null(test2.FindImplementationForInterfaceMember(p4)); ValidateP4Accessor(p4.AddMethod); ValidateP4Accessor(p4.RemoveMethod); void ValidateP4Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p5 = GetSingleEvent(compilation1, "I5"); Assert.False(p5.IsAbstract); Assert.False(p5.IsVirtual); Assert.False(p5.IsSealed); Assert.False(p5.IsStatic); Assert.False(p5.IsExtern); Assert.False(p5.IsOverride); Assert.Equal(Accessibility.Public, p5.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5)); Assert.Null(test2.FindImplementationForInterfaceMember(p5)); ValidateP5Accessor(p5.AddMethod); ValidateP5Accessor(p5.RemoveMethod); void ValidateP5Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } } [Fact] public void EventModifiers_20() { var source1 = @" public interface I1 { internal event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } void M2() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidateEventModifiers_20(source1, source2, Accessibility.Internal); } private void ValidateEventModifiers_20(string source1, string source2, Accessibility accessibility) { var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var p1 = GetSingleEvent(i1); var p1add = p1.AddMethod; var p1remove = p1.RemoveMethod; ValidateEvent(p1); ValidateMethod(p1add); ValidateMethod(p1remove); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(p1add, test1.FindImplementationForInterfaceMember(p1add)); Assert.Same(p1remove, test1.FindImplementationForInterfaceMember(p1remove)); } void ValidateEvent(EventSymbol p1) { Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(accessibility, p1.DeclaredAccessibility); } void ValidateMethod(MethodSymbol m1) { Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(accessibility, m1.DeclaredAccessibility); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var p1 = GetSingleEvent(i1); ValidateEvent(p1); ValidateMethod(p1.AddMethod); ValidateMethod(p1.RemoveMethod); } var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation3.SourceModule); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation4.SourceModule); } [Fact] public void EventModifiers_21() { var source1 = @" public interface I1 { private static event System.Action P1 { add => throw null; remove => throw null; } internal static event System.Action P2 { add => throw null; remove => throw null; } public static event System.Action P3 { add => throw null; remove => throw null; } static event System.Action P4 { add => throw null; remove => throw null; } } class Test1 { static void Main() { I1.P1 += null; I1.P1 -= null; I1.P2 += null; I1.P2 -= null; I1.P3 += null; I1.P3 -= null; I1.P4 += null; I1.P4 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (17,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(17, 12), // (18,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(18, 12) ); var source2 = @" class Test2 { static void Main() { I1.P1 += null; I1.P1 -= null; I1.P2 += null; I1.P2 -= null; I1.P3 += null; I1.P3 -= null; I1.P4 += null; I1.P4 -= null; } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(6, 12), // (7,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(7, 12), // (8,12): error CS0122: 'I1.P2' is inaccessible due to its protection level // I1.P2 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(8, 12), // (9,12): error CS0122: 'I1.P2' is inaccessible due to its protection level // I1.P2 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(9, 12) ); } [Fact] public void EventModifiers_22() { var source0 = @" public interface I1 { protected static event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } protected internal static event System.Action P2 { add { System.Console.WriteLine(""get_P2""); } remove { System.Console.WriteLine(""set_P2""); } } private protected static event System.Action P3 { add => System.Console.WriteLine(""get_P3""); remove => System.Console.WriteLine(""set_P3""); } } "; var source1 = @" class Test1 : I1 { static void Main() { I1.P1 += null; I1.P1 -= null; I1.P2 += null; I1.P2 -= null; I1.P3 += null; I1.P3 -= null; } } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 set_P2 get_P3 set_P3", symbolValidator: validate, verify: VerifyOnMonoOrCoreClr); validate(compilation1.SourceModule); var source2 = @" class Test1 { static void Main() { I1.P2 += null; I1.P2 -= null; } } "; var compilation2 = CreateCompilation(source0 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P2 set_P2", verify: VerifyOnMonoOrCoreClr); var compilation3 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); var source3 = @" class Test1 : I1 { static void Main() { I1.P1 += null; I1.P1 -= null; I1.P2 += null; I1.P2 -= null; } } "; var source4 = @" class Test1 { static void Main() { I1.P1 += null; I1.P1 -= null; I1.P2 += null; I1.P2 -= null; I1.P3 += null; I1.P3 -= null; } } "; foreach (var reference in new[] { compilation3.ToMetadataReference(), compilation3.EmitToImageReference() }) { var compilation4 = CreateCompilation(source3, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 set_P2", verify: VerifyOnMonoOrCoreClr); var compilation5 = CreateCompilation(source4, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (6,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(6, 12), // (7,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(7, 12), // (8,12): error CS0122: 'I1.P2' is inaccessible due to its protection level // I1.P2 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(8, 12), // (9,12): error CS0122: 'I1.P2' is inaccessible due to its protection level // I1.P2 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(9, 12), // (10,12): error CS0122: 'I1.P3' is inaccessible due to its protection level // I1.P3 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(10, 12), // (11,12): error CS0122: 'I1.P3' is inaccessible due to its protection level // I1.P3 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(11, 12) ); var compilation6 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (10,12): error CS0122: 'I1.P3' is inaccessible due to its protection level // I1.P3 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(10, 12), // (11,12): error CS0122: 'I1.P3' is inaccessible due to its protection level // I1.P3 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(11, 12) ); } void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); foreach (var tuple in new[] { (name: "P1", access: Accessibility.Protected), (name: "P2", access: Accessibility.ProtectedOrInternal), (name: "P3", access: Accessibility.ProtectedAndInternal)}) { var p1 = i1.GetMember<EventSymbol>(tuple.name); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.True(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(tuple.access, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); ValidateAccessor(p1.AddMethod); ValidateAccessor(p1.RemoveMethod); void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(tuple.access, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } } [Fact] public void EventModifiers_23() { var source1 = @" public interface I1 { protected abstract event System.Action P1; sealed void Test() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11(source1, source2, Accessibility.Protected, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } [Fact] public void EventModifiers_24() { var source1 = @" public interface I1 { protected internal abstract event System.Action P1; sealed void Test() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11(source1, source2, Accessibility.ProtectedOrInternal, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } [Fact] public void EventModifiers_25() { var source1 = @" public interface I1 { private protected abstract event System.Action P1; sealed void Test() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11(source1, source2, Accessibility.ProtectedAndInternal, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } [Fact] public void EventModifiers_26() { var source1 = @" public interface I1 { protected abstract event System.Action P1; public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } event System.Action I1.P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_03(source1, source2, TargetFramework.NetCoreApp); } [Fact] public void EventModifiers_27() { var source1 = @" public interface I1 { protected internal abstract event System.Action P1; public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } event System.Action I1.P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_03(source1, source2, TargetFramework.NetCoreApp); } [Fact] public void EventModifiers_28() { var source1 = @" public interface I1 { private protected abstract event System.Action P1; public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } event System.Action I1.P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_03(source1, source2, TargetFramework.NetCoreApp, // (9,28): error CS0122: 'I1.P1' is inaccessible due to its protection level // event System.Action I1.P1 Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(9, 28) ); } [Fact] public void EventModifiers_29() { var source1 = @" public interface I1 { protected event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } void M2() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidateEventModifiers_20(source1, source2, Accessibility.Protected); } [Fact] public void EventModifiers_30() { var source1 = @" public interface I1 { protected internal event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } void M2() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidateEventModifiers_20(source1, source2, Accessibility.ProtectedOrInternal); } [Fact] public void EventModifiers_31() { var source1 = @" public interface I1 { private protected event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } void M2() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidateEventModifiers_20(source1, source2, Accessibility.ProtectedAndInternal); } [Fact] public void NestedTypes_01() { var source1 = @" public interface I1 { interface T1 { void M1(); } class T2 {} struct T3 {} enum T4 { B } delegate void T5(); } class Test1 : I1.T1 { static void Main() { I1.T1 a = new Test1(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } public void M1() { System.Console.WriteLine(""M1""); } } "; ValidateNestedTypes_01(source1); } private void ValidateNestedTypes_01(string source1, Accessibility expected = Accessibility.Public, TargetFramework targetFramework = TargetFramework.Standard, bool execute = true, Verification verify = Verification.Passes) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: targetFramework); for (int i = 1; i <= 5; i++) { Assert.Equal(expected, compilation1.GetMember("I1.T" + i).DeclaredAccessibility); } CompileAndVerify(compilation1, expectedOutput: !execute ? null : @"M1 I1+T2 I1+T3 B I1+T5", verify: verify); } [Fact] public void NestedTypes_02() { var source1 = @" public interface I1 { interface T1 { void M1(); } class T2 {} struct T3 {} enum T4 { B } } class Test1 : I1.T1 { static void Main() { I1.T1 a = new Test1(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); } public void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); for (int i = 1; i <= 4; i++) { Assert.Equal(Accessibility.Public, compilation1.GetMember("I1.T" + i).DeclaredAccessibility); } compilation1.VerifyDiagnostics( // (4,15): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // interface T1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T1").WithArguments("default interface implementation", "8.0").WithLocation(4, 15), // (9,11): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // class T2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T2").WithArguments("default interface implementation", "8.0").WithLocation(9, 11), // (12,12): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // struct T3 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T3").WithArguments("default interface implementation", "8.0").WithLocation(12, 12), // (15,10): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // enum T4 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T4").WithArguments("default interface implementation", "8.0").WithLocation(15, 10) ); } [Fact] public void NestedTypes_03() { var source1 = @" public interface I1 { public interface T1 { void M1(); } public class T2 {} public struct T3 {} public enum T4 { B } public delegate void T5(); } class Test1 : I1.T1 { static void Main() { I1.T1 a = new Test1(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } public void M1() { System.Console.WriteLine(""M1""); } } "; ValidateNestedTypes_01(source1); } [Fact] public void NestedTypes_04() { var source0 = @" public interface I1 { protected interface T1 { void M1(); } protected class T2 {} protected struct T3 {} protected enum T4 { B } protected delegate void T5(); } "; var source1 = @" class Test1 : I1 { static void Main() { I1.T1 a = new Test2(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } class Test2 : I1.T1 { public void M1() { System.Console.WriteLine(""M1""); } } } "; ValidateNestedTypes_01(source0 + source1, Accessibility.Protected, targetFramework: TargetFramework.NetCoreApp, execute: ExecutionConditionUtil.IsMonoOrCoreClr, verify: VerifyOnMonoOrCoreClr); var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); for (int i = 1; i <= 5; i++) { Assert.Equal(Accessibility.Protected, compilation1.GetMember("I1.T" + i).DeclaredAccessibility); } compilation1.VerifyDiagnostics( // (4,25): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected interface T1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T1").WithLocation(4, 25), // (9,21): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected class T2 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T2").WithLocation(9, 21), // (12,22): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected struct T3 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T3").WithLocation(12, 22), // (15,20): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected enum T4 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T4").WithLocation(15, 20), // (20,29): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected delegate void T5(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T5").WithLocation(20, 29) ); var source2 = @" class Test1 { static void Main() { I1.T1 a = new Test2(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } class Test2 : I1.T1 { public void M1() { System.Console.WriteLine(""M1""); } } } "; var compilation2 = CreateCompilation(source2 + source0, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var expected = new DiagnosticDescription[] { // (6,12): error CS0122: 'I1.T1' is inaccessible due to its protection level // I1.T1 a = new Test2(); Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(6, 12), // (7,11): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // a.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(7, 11), // (8,41): error CS0122: 'I1.T2' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T2()); Diagnostic(ErrorCode.ERR_BadAccess, "T2").WithArguments("I1.T2").WithLocation(8, 41), // (9,41): error CS0122: 'I1.T3' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T3()); Diagnostic(ErrorCode.ERR_BadAccess, "T3").WithArguments("I1.T3").WithLocation(9, 41), // (10,37): error CS0122: 'I1.T4' is inaccessible due to its protection level // System.Console.WriteLine(I1.T4.B); Diagnostic(ErrorCode.ERR_BadAccess, "T4").WithArguments("I1.T4").WithLocation(10, 37), // (11,41): error CS0122: 'I1.T5' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "T5").WithArguments("I1.T5").WithLocation(11, 41), // (11,46): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(11, 46), // (14,22): error CS0122: 'I1.T1' is inaccessible due to its protection level // class Test2 : I1.T1 Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(14, 22) }; compilation2.VerifyDiagnostics(expected); var compilation3 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); foreach (var reference in new[] { compilation3.ToMetadataReference(), compilation3.EmitToImageReference() }) { var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics(); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 I1+T2 I1+T3 B I1+T5", verify: VerifyOnMonoOrCoreClr); var compilation5 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics(expected); } } [Fact] public void NestedTypes_05() { var source0 = @" public interface I1 { protected internal interface T1 { void M1(); } protected internal class T2 {} protected internal struct T3 {} protected internal enum T4 { B } protected internal delegate void T5(); } "; var source1 = @" class Test1 : I1 { static void Main() { I1.T1 a = new Test2(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } class Test2 : I1.T1 { public void M1() { System.Console.WriteLine(""M1""); } } } "; var source2 = @" class Test1 { static void Main() { I1.T1 a = new Test2(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } class Test2 : I1.T1 { public void M1() { System.Console.WriteLine(""M1""); } } } "; ValidateNestedTypes_01(source0 + source1, Accessibility.ProtectedOrInternal, targetFramework: TargetFramework.NetCoreApp, execute: ExecutionConditionUtil.IsMonoOrCoreClr, verify: VerifyOnMonoOrCoreClr); ValidateNestedTypes_01(source0 + source2, Accessibility.ProtectedOrInternal, targetFramework: TargetFramework.NetCoreApp, execute: ExecutionConditionUtil.IsMonoOrCoreClr, verify: VerifyOnMonoOrCoreClr); var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); for (int i = 1; i <= 5; i++) { Assert.Equal(Accessibility.ProtectedOrInternal, compilation1.GetMember("I1.T" + i).DeclaredAccessibility); } compilation1.VerifyDiagnostics( // (4,34): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal interface T1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T1").WithLocation(4, 34), // (9,30): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal class T2 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T2").WithLocation(9, 30), // (12,31): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal struct T3 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T3").WithLocation(12, 31), // (15,29): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal enum T4 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T4").WithLocation(15, 29), // (20,38): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal delegate void T5(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T5").WithLocation(20, 38) ); var compilation3 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); foreach (var reference in new[] { compilation3.ToMetadataReference(), compilation3.EmitToImageReference() }) { var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics(); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 I1+T2 I1+T3 B I1+T5", verify: VerifyOnMonoOrCoreClr); var compilation5 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (6,12): error CS0122: 'I1.T1' is inaccessible due to its protection level // I1.T1 a = new Test2(); Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(6, 12), // (7,11): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // a.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(7, 11), // (8,41): error CS0122: 'I1.T2' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T2()); Diagnostic(ErrorCode.ERR_BadAccess, "T2").WithArguments("I1.T2").WithLocation(8, 41), // (9,41): error CS0122: 'I1.T3' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T3()); Diagnostic(ErrorCode.ERR_BadAccess, "T3").WithArguments("I1.T3").WithLocation(9, 41), // (10,37): error CS0122: 'I1.T4' is inaccessible due to its protection level // System.Console.WriteLine(I1.T4.B); Diagnostic(ErrorCode.ERR_BadAccess, "T4").WithArguments("I1.T4").WithLocation(10, 37), // (11,41): error CS0122: 'I1.T5' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "T5").WithArguments("I1.T5").WithLocation(11, 41), // (11,46): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(11, 46), // (14,22): error CS0122: 'I1.T1' is inaccessible due to its protection level // class Test2 : I1.T1 Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(14, 22) ); } } [Fact] public void NestedTypes_06() { var source1 = @" public interface I1 { internal interface T1 { void M1(); } internal class T2 {} internal struct T3 {} internal enum T4 { B } internal delegate void T5(); } "; var source2 = @" class Test1 : I1.T1 { static void Main() { I1.T1 a = new Test1(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } public void M1() { System.Console.WriteLine(""M1""); } } "; ValidateNestedTypes_01(source1 + source2, Accessibility.Internal); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe); var expected = new[] { // (2,18): error CS0122: 'I1.T1' is inaccessible due to its protection level // class Test1 : I1.T1 Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(2, 18), // (6,12): error CS0122: 'I1.T1' is inaccessible due to its protection level // I1.T1 a = new Test1(); Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(6, 12), // (7,11): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // a.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(7, 11), // (8,41): error CS0122: 'I1.T2' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T2()); Diagnostic(ErrorCode.ERR_BadAccess, "T2").WithArguments("I1.T2").WithLocation(8, 41), // (9,41): error CS0122: 'I1.T3' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T3()); Diagnostic(ErrorCode.ERR_BadAccess, "T3").WithArguments("I1.T3").WithLocation(9, 41), // (10,37): error CS0122: 'I1.T4' is inaccessible due to its protection level // System.Console.WriteLine(I1.T4.B); Diagnostic(ErrorCode.ERR_BadAccess, "T4").WithArguments("I1.T4").WithLocation(10, 37), // (11,41): error CS0122: 'I1.T5' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "T5").WithArguments("I1.T5").WithLocation(11, 41), // (11,46): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(11, 46) }; compilation2.VerifyDiagnostics(expected); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe); compilation3.VerifyDiagnostics(expected); } [Fact] public void NestedTypes_07() { var source1 = @" public interface I1 { private interface T1 { void M1(); } private class T2 {} private struct T3 {} private enum T4 { B } private delegate void T5(); class Test1 : I1.T1 { static void Main() { I1.T1 a = new Test1(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } public void M1() { System.Console.WriteLine(""M1""); } } } "; ValidateNestedTypes_01(source1, Accessibility.Private); } [Fact] public void NestedTypes_08() { var source1 = @" public interface I1 { private interface T1 { void M1(); } private class T2 {} private struct T3 {} private enum T4 { B } } class Test1 : I1.T1 { static void Main() { I1.T1 a = new Test1(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); } public void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (21,18): error CS0122: 'I1.T1' is inaccessible due to its protection level // class Test1 : I1.T1 Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(21, 18), // (25,12): error CS0122: 'I1.T1' is inaccessible due to its protection level // I1.T1 a = new Test1(); Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(25, 12), // (26,11): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // a.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(26, 11), // (27,41): error CS0122: 'I1.T2' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T2()); Diagnostic(ErrorCode.ERR_BadAccess, "T2").WithArguments("I1.T2").WithLocation(27, 41), // (28,41): error CS0122: 'I1.T3' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T3()); Diagnostic(ErrorCode.ERR_BadAccess, "T3").WithArguments("I1.T3").WithLocation(28, 41), // (29,37): error CS0122: 'I1.T4' is inaccessible due to its protection level // System.Console.WriteLine(I1.T4.B); Diagnostic(ErrorCode.ERR_BadAccess, "T4").WithArguments("I1.T4").WithLocation(29, 37) ); } [Fact] public void NestedTypes_09() { var source0 = @" public interface I1 { private protected interface T1 { void M1(); } private protected class T2 {} private protected struct T3 {} private protected enum T4 { B } private protected delegate void T5(); } "; var source1 = @" class Test1 : I1 { static void Main() { I1.T1 a = new Test2(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } class Test2 : I1.T1 { public void M1() { System.Console.WriteLine(""M1""); } } } "; var source2 = @" class Test1 { static void Main() { I1.T1 a = new Test2(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } class Test2 : I1.T1 { public void M1() { System.Console.WriteLine(""M1""); } } } "; ValidateNestedTypes_01(source0 + source1, Accessibility.ProtectedAndInternal, targetFramework: TargetFramework.NetCoreApp, execute: ExecutionConditionUtil.IsMonoOrCoreClr, verify: VerifyOnMonoOrCoreClr); var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); for (int i = 1; i <= 5; i++) { Assert.Equal(Accessibility.ProtectedAndInternal, compilation1.GetMember("I1.T" + i).DeclaredAccessibility); } compilation1.VerifyDiagnostics( // (4,33): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected interface T1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T1").WithLocation(4, 33), // (9,29): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected class T2 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T2").WithLocation(9, 29), // (12,30): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected struct T3 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T3").WithLocation(12, 30), // (15,28): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected enum T4 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T4").WithLocation(15, 28), // (20,37): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected delegate void T5(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T5").WithLocation(20, 37) ); var compilation2 = CreateCompilation(source2 + source0, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var expected = new DiagnosticDescription[] { // (6,12): error CS0122: 'I1.T1' is inaccessible due to its protection level // I1.T1 a = new Test2(); Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(6, 12), // (7,11): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // a.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(7, 11), // (8,41): error CS0122: 'I1.T2' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T2()); Diagnostic(ErrorCode.ERR_BadAccess, "T2").WithArguments("I1.T2").WithLocation(8, 41), // (9,41): error CS0122: 'I1.T3' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T3()); Diagnostic(ErrorCode.ERR_BadAccess, "T3").WithArguments("I1.T3").WithLocation(9, 41), // (10,37): error CS0122: 'I1.T4' is inaccessible due to its protection level // System.Console.WriteLine(I1.T4.B); Diagnostic(ErrorCode.ERR_BadAccess, "T4").WithArguments("I1.T4").WithLocation(10, 37), // (11,41): error CS0122: 'I1.T5' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "T5").WithArguments("I1.T5").WithLocation(11, 41), // (11,46): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(11, 46), // (14,22): error CS0122: 'I1.T1' is inaccessible due to its protection level // class Test2 : I1.T1 Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(14, 22) }; compilation2.VerifyDiagnostics(expected); var compilation3 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); foreach (var reference in new[] { compilation3.ToMetadataReference(), compilation3.EmitToImageReference() }) { var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics(expected); var compilation5 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics(expected); } } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_10() { var source1 = @" interface I1 { protected interface I2 { } } class C1 { protected interface I2 { } } interface I3 : I1, I1.I2 { private void M1(I1.I2 x) { } } interface I4 : I1, I2 { I2 MI4(); } interface I5 : I1.I2, I1 { private void M1(I1.I2 x) { } } interface I6 : I2, I1 { I2 MI6(); } class C3 : I1, I1.I2 { private void M1(I1.I2 x) { } } class C4 : I1, I2 { void MC4(I2 x) { } } class C5 : I1.I2, I1 { private void M1(I1.I2 x) { } } class C6 : I2, I1 { void MC6(I2 x) { } } class C33 : C1, C1.I2 { protected void M1(C1.I2 x) { } } class C44 : C1, I2 { void M1(I2 x) { } } interface I7 : I8 { public interface I8 : I7 { } } class C7 : I8 { public interface I8 { } } interface I9 : I9.I10 { public interface I10 : I9 { } } interface I11 { public interface I12 : I13 { } public interface I13 { } public interface I14 : I11.I13 { } } class C11 { public interface I12 : I13 { } public interface I13 { } public interface I14 : I11.I13 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (16,23): error CS0122: 'I1.I2' is inaccessible due to its protection level // interface I3 : I1, I1.I2 Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1.I2").WithLocation(16, 23), // (21,20): error CS0246: The type or namespace name 'I2' could not be found (are you missing a using directive or an assembly reference?) // interface I4 : I1, I2 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("I2").WithLocation(21, 20), // (23,8): error CS0050: Inconsistent accessibility: return type 'I1.I2' is less accessible than method 'I4.MI4()' // I2 MI4(); Diagnostic(ErrorCode.ERR_BadVisReturnType, "MI4").WithArguments("I4.MI4()", "I1.I2").WithLocation(23, 8), // (26,19): error CS0122: 'I1.I2' is inaccessible due to its protection level // interface I5 : I1.I2, I1 Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1.I2").WithLocation(26, 19), // (31,16): error CS0246: The type or namespace name 'I2' could not be found (are you missing a using directive or an assembly reference?) // interface I6 : I2, I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("I2").WithLocation(31, 16), // (33,8): error CS0050: Inconsistent accessibility: return type 'I1.I2' is less accessible than method 'I6.MI6()' // I2 MI6(); Diagnostic(ErrorCode.ERR_BadVisReturnType, "MI6").WithArguments("I6.MI6()", "I1.I2").WithLocation(33, 8), // (36,19): error CS0122: 'I1.I2' is inaccessible due to its protection level // class C3 : I1, I1.I2 Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1.I2").WithLocation(36, 19), // (41,16): error CS0246: The type or namespace name 'I2' could not be found (are you missing a using directive or an assembly reference?) // class C4 : I1, I2 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("I2").WithLocation(41, 16), // (43,14): error CS0246: The type or namespace name 'I2' could not be found (are you missing a using directive or an assembly reference?) // void MC4(I2 x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("I2").WithLocation(43, 14), // (46,15): error CS0122: 'I1.I2' is inaccessible due to its protection level // class C5 : I1.I2, I1 Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1.I2").WithLocation(46, 15), // (51,12): error CS0246: The type or namespace name 'I2' could not be found (are you missing a using directive or an assembly reference?) // class C6 : I2, I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("I2").WithLocation(51, 12), // (53,14): error CS0246: The type or namespace name 'I2' could not be found (are you missing a using directive or an assembly reference?) // void MC6(I2 x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("I2").WithLocation(53, 14), // (56,20): error CS0122: 'C1.I2' is inaccessible due to its protection level // class C33 : C1, C1.I2 Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("C1.I2").WithLocation(56, 20), // (61,17): error CS0246: The type or namespace name 'I2' could not be found (are you missing a using directive or an assembly reference?) // class C44 : C1, I2 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("I2").WithLocation(61, 17), // (66,16): error CS0246: The type or namespace name 'I8' could not be found (are you missing a using directive or an assembly reference?) // interface I7 : I8 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I8").WithArguments("I8").WithLocation(66, 16), // (73,12): error CS0246: The type or namespace name 'I8' could not be found (are you missing a using directive or an assembly reference?) // class C7 : I8 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I8").WithArguments("I8").WithLocation(73, 12), // (80,11): error CS0529: Inherited interface 'I9.I10' causes a cycle in the interface hierarchy of 'I9' // interface I9 : I9.I10 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I9").WithArguments("I9", "I9.I10").WithLocation(80, 11), // (82,22): error CS0529: Inherited interface 'I9' causes a cycle in the interface hierarchy of 'I9.I10' // public interface I10 : I9 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I10").WithArguments("I9.I10", "I9").WithLocation(82, 22) ); } [Fact] [WorkItem(38735, "https://github.com/dotnet/roslyn/issues/38735")] public void NestedTypes_52() { var source1 = @" interface I1 : IA<int>.NF { } interface IQ<T> { } interface IA<T> : IB<IQ<T>> { } interface IB<T> : IA<IQ<T>> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (2,24): error CS0426: The type name 'NF' does not exist in the type 'IA<int>' // interface I1 : IA<int>.NF { } Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "NF").WithArguments("NF", "IA<int>").WithLocation(2, 24), // (6,11): error CS0529: Inherited interface 'IB<IQ<T>>' causes a cycle in the interface hierarchy of 'IA<T>' // interface IA<T> : IB<IQ<T>> { } Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IA").WithArguments("IA<T>", "IB<IQ<T>>").WithLocation(6, 11), // (8,11): error CS0529: Inherited interface 'IA<IQ<T>>' causes a cycle in the interface hierarchy of 'IB<T>' // interface IB<T> : IA<IQ<T>> { } Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IB").WithArguments("IB<T>", "IA<IQ<T>>").WithLocation(8, 11) ); } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void MethodImplementationInDerived_01() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I5 : I4 { } public interface I1 : I2, I5 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source2 = @" class Test1 : I1 { static void Main() { I2 i2 = new Test1(); i2.M1(); I4 i4 = new Test1(); i4.M1(); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); } private static void ValidateMethodImplementationInDerived_01(ModuleSymbol m) { ValidateMethodImplementationInDerived_01(m, i4M1IsAbstract: false); } private static void ValidateMethodImplementationInDerived_01(ModuleSymbol m, bool i4M1IsAbstract) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var i1i2m1 = i1.GetMember<MethodSymbol>("I2.M1"); var i1i4m1 = i1.GetMember<MethodSymbol>("I4.M1"); var i2 = i1.AllInterfacesNoUseSiteDiagnostics.Where(i => i.Name == "I2").Single(); var i2m1 = i2.GetMembers().OfType<MethodSymbol>().Single(); var i4 = i1.AllInterfacesNoUseSiteDiagnostics.Where(i => i.Name == "I4").Single(); var i4m1 = i4.GetMembers().OfType<MethodSymbol>().Single(); var i3 = i1.ContainingNamespace.GetTypeMember("I3"); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); ValidateExplicitImplementation(i1i2m1); ValidateExplicitImplementation(i1i4m1, i4M1IsAbstract); Assert.Null(test1.FindImplementationForInterfaceMember(i1i2m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1i4m1)); Assert.Same(i1i2m1, test1.FindImplementationForInterfaceMember(i2m1)); Assert.Same(i4M1IsAbstract ? null : i1i4m1, test1.FindImplementationForInterfaceMember(i4m1)); Assert.Null(i1.FindImplementationForInterfaceMember(i1i2m1)); Assert.Null(i1.FindImplementationForInterfaceMember(i1i4m1)); Assert.Same(i1i2m1, i1.FindImplementationForInterfaceMember(i2m1)); Assert.Same(i4M1IsAbstract ? null : i1i4m1, i1.FindImplementationForInterfaceMember(i4m1)); Assert.Null(i2.FindImplementationForInterfaceMember(i2m1)); Assert.Null(i4.FindImplementationForInterfaceMember(i4m1)); Assert.Same(i1i2m1, i3.FindImplementationForInterfaceMember(i2m1)); Assert.Same(i4M1IsAbstract ? null : i1i4m1, i3.FindImplementationForInterfaceMember(i4m1)); } private static void ValidateExplicitImplementation(MethodSymbol m1, bool isAbstract = false) { Assert.True(m1.IsMetadataVirtual()); Assert.True(m1.IsMetadataFinal); Assert.False(m1.IsMetadataNewSlot()); Assert.Equal(isAbstract, m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.Equal(isAbstract, m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); if (m1.ContainingModule is PEModuleSymbol peModule) { int rva; peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)m1.OriginalDefinition).Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); } } [Fact] public void MethodImplementationInDerived_02() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I1 : I2, I4 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // void I2.M1() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M1").WithArguments("default interface implementation", "8.0").WithLocation(14, 13), // (18,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // void I4.M1() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M1").WithArguments("default interface implementation", "8.0").WithLocation(18, 13) ); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); var source2 = @" public interface I3 : I1 { } class Test1 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (6,15): error CS8506: 'I1.I2.M1()' cannot implement interface member 'I2.M1()' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1()", "I2.M1()", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15), // (6,15): error CS8506: 'I1.I4.M1()' cannot implement interface member 'I4.M1()' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1()", "I4.M1()", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15) ); ValidateMethodImplementationInDerived_01(compilation2.SourceModule); } [Fact] public void MethodImplementationInDerived_03() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I1 : I2, I4 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,13): error CS8501: Target runtime doesn't support default interface implementation. // void I2.M1() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(14, 13), // (18,13): error CS8501: Target runtime doesn't support default interface implementation. // void I4.M1() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(18, 13) ); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); var source2 = @" public interface I3 : I1 { } class Test1 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (6,15): error CS8502: 'I1.I2.M1()' cannot implement interface member 'I2.M1()' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1()", "I2.M1()", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I4.M1()' cannot implement interface member 'I4.M1()' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1()", "I4.M1()", "Test1").WithLocation(6, 15) ); } [Fact] public void MethodImplementationInDerived_04() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I1 : I2, I4 { void I2.M1(); void I4.M1(); } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (15,13): error CS0501: 'I1.I4.M1()' must declare a body because it is not marked abstract, extern, or partial // void I4.M1(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M1").WithArguments("I1.I4.M1()").WithLocation(15, 13), // (14,13): error CS0501: 'I1.I2.M1()' must declare a body because it is not marked abstract, extern, or partial // void I2.M1(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M1").WithArguments("I1.I2.M1()").WithLocation(14, 13) ); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); } [Fact] public void MethodImplementationInDerived_05() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I1 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I2.M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (18,10): error CS0540: 'I1.I4.M1()': containing type does not implement interface 'I4' // void I4.M1() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I4").WithArguments("I1.I4.M1()", "I4").WithLocation(18, 10), // (14,10): error CS0540: 'I1.I2.M1()': containing type does not implement interface 'I2' // void I2.M1() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.I2.M1()", "I2").WithLocation(14, 10) ); } [Fact] public void MethodImplementationInDerived_06() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I1 : I2, I4 { public static void I2.M1() { System.Console.WriteLine(""I2.M1""); } internal virtual void I4.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,27): error CS0106: The modifier 'static' is not valid for this item // public static void I2.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("static").WithLocation(14, 27), // (14,27): error CS0106: The modifier 'public' is not valid for this item // public static void I2.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("public").WithLocation(14, 27), // (18,30): error CS0106: The modifier 'internal' is not valid for this item // internal virtual void I4.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("internal").WithLocation(18, 30), // (18,30): error CS0106: The modifier 'virtual' is not valid for this item // internal virtual void I4.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("virtual").WithLocation(18, 30) ); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); } [Fact] public void MethodImplementationInDerived_07() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I1 : I2, I4 { private sealed void I2.M1() { System.Console.WriteLine(""I2.M1""); } protected abstract void I4.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,28): error CS0106: The modifier 'sealed' is not valid for this item // private sealed void I2.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("sealed").WithLocation(14, 28), // (14,28): error CS0106: The modifier 'private' is not valid for this item // private sealed void I2.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("private").WithLocation(14, 28), // (18,32): error CS0106: The modifier 'protected' is not valid for this item // protected abstract void I4.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected").WithLocation(18, 32), // (18,32): error CS0500: 'I1.I4.M1()' cannot declare a body because it is marked abstract // protected abstract void I4.M1() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M1").WithArguments("I1.I4.M1()").WithLocation(18, 32), // (28,15): error CS0535: 'Test1' does not implement interface member 'I4.M1()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I4.M1()").WithLocation(28, 15) ); ValidateMethodImplementationInDerived_01(compilation1.SourceModule, i4M1IsAbstract: true); } [Fact] public void MethodImplementationInDerived_08() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I1 : I2, I4 { private protected void I2.M1() { System.Console.WriteLine(""I2.M1""); } internal protected override void I4.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,31): error CS0106: The modifier 'private protected' is not valid for this item // private protected void I2.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("private protected").WithLocation(14, 31), // (18,41): error CS0106: The modifier 'protected internal' is not valid for this item // internal protected override void I4.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected internal").WithLocation(18, 41), // (18,41): error CS0106: The modifier 'override' is not valid for this item // internal protected override void I4.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("override").WithLocation(18, 41) ); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); } [Fact] public void MethodImplementationInDerived_09() { var source1 = @" public interface I2 { void M1(); } public interface I1 : I2 { extern void I2.M1(); } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (9,20): warning CS0626: Method, operator, or accessor 'I1.I2.M1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void I2.M1(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M1").WithArguments("I1.I2.M1()").WithLocation(9, 20) ); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var i1i2m1 = i1.GetMember<MethodSymbol>("I2.M1"); var i2 = i1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I2").Single(); var i2m1 = i2.GetMembers().OfType<MethodSymbol>().Single(); var i3 = i1.ContainingNamespace.GetTypeMember("I3"); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); ValidateExplicitExternImplementation(i1i2m1); Assert.Null(test1.FindImplementationForInterfaceMember(i1i2m1)); Assert.Same(i1i2m1, test1.FindImplementationForInterfaceMember(i2m1)); Assert.Null(i1.FindImplementationForInterfaceMember(i1i2m1)); Assert.Same(i1i2m1, i1.FindImplementationForInterfaceMember(i2m1)); Assert.Null(i2.FindImplementationForInterfaceMember(i2m1)); Assert.Same(i1i2m1, i3.FindImplementationForInterfaceMember(i2m1)); } CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (9,20): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // extern void I2.M1(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M1").WithArguments("default interface implementation", "8.0").WithLocation(9, 20), // (9,20): warning CS0626: Method, operator, or accessor 'I1.I2.M1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void I2.M1(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M1").WithArguments("I1.I2.M1()").WithLocation(9, 20) ); Validate1(compilation2.SourceModule); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (9,20): error CS8501: Target runtime doesn't support default interface implementation. // extern void I2.M1(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(9, 20), // (9,20): warning CS0626: Method, operator, or accessor 'I1.I2.M1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void I2.M1(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M1").WithArguments("I1.I2.M1()").WithLocation(9, 20) ); Validate1(compilation3.SourceModule); var source2 = @" public interface I2 { void M1(); } public interface I1 : I2 { extern void I2.M1() {} } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation4 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics( // (9,20): error CS0179: 'I1.I2.M1()' cannot be extern and declare a body // extern void I2.M1() Diagnostic(ErrorCode.ERR_ExternHasBody, "M1").WithArguments("I1.I2.M1()").WithLocation(9, 20) ); Validate1(compilation4.SourceModule); } private static void ValidateExplicitExternImplementation(MethodSymbol m1) { Assert.True(m1.IsMetadataVirtual()); Assert.True(m1.IsMetadataFinal); Assert.False(m1.IsMetadataNewSlot()); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.NotEqual(m1.OriginalDefinition is PEMethodSymbol, m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); if (m1.ContainingModule is PEModuleSymbol peModule) { int rva; peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)m1).Handle, out _, out _, out _, out rva); Assert.Equal(0, rva); } } [Fact] public void MethodImplementationInDerived_10() { var source1 = @" using System.Threading.Tasks; public interface I2 { Task M1(); } public interface I1 : I2 { async Task I2.M1() { await Task.Factory.StartNew(() => System.Console.WriteLine(""I2.M1"")); } } public interface I3 : I1 { } class Test1 : I1 { static void Main() { I2 i2 = new Test1(); i2.M1().Wait(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var i1i2m1 = i1.GetMember<MethodSymbol>("I2.M1"); var i2 = i1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I2").Single(); var i2m1 = i2.GetMembers().OfType<MethodSymbol>().Single(); var i3 = i1.ContainingNamespace.GetTypeMember("I3"); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); Validate2(i1i2m1); Assert.Null(test1.FindImplementationForInterfaceMember(i1i2m1)); Assert.Equal("System.Threading.Tasks.Task I1.I2.M1()", test1.FindImplementationForInterfaceMember(i2m1).ToTestDisplayString()); Assert.Null(i1.FindImplementationForInterfaceMember(i1i2m1)); Assert.Equal("System.Threading.Tasks.Task I1.I2.M1()", i1.FindImplementationForInterfaceMember(i2m1).ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i2m1)); Assert.Equal("System.Threading.Tasks.Task I1.I2.M1()", i3.FindImplementationForInterfaceMember(i2m1).ToTestDisplayString()); } void Validate2(MethodSymbol m1) { Assert.True(m1.IsMetadataVirtual()); Assert.True(m1.IsMetadataFinal); Assert.False(m1.IsMetadataNewSlot()); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.NotEqual(m1 is PEMethodSymbol, m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); if (m1.ContainingModule is PEModuleSymbol peModule) { int rva; peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)m1).Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); } } CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "I2.M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void MethodImplementationInDerived_11() { var source1 = @" public interface I2 { internal void M1(); } public interface I4 { internal void M1(); } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { i2.M1(); i4.M1(); } } "; var source2 = @" public interface I1 : I2, I5 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { TestHelper.Test(new Test1(), new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); var compilation2 = CreateCompilation(source3, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); var compilation3 = CreateCompilation(source3, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); var compilation5 = CreateCompilation(source2 + source3, new[] { compilation4.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics( // (8,13): error CS0122: 'I4.M1()' is inaccessible due to its protection level // void I4.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I4.M1()").WithLocation(8, 13), // (4,13): error CS0122: 'I2.M1()' is inaccessible due to its protection level // void I2.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1()").WithLocation(4, 13) ); var compilation6 = CreateCompilation(source2 + source3, new[] { compilation4.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation6.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation6.SourceModule); compilation6.VerifyDiagnostics( // (8,13): error CS0122: 'I4.M1()' is inaccessible due to its protection level // void I4.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I4.M1()").WithLocation(8, 13), // (4,13): error CS0122: 'I2.M1()' is inaccessible due to its protection level // void I2.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1()").WithLocation(4, 13) ); } [Fact] [WorkItem(20083, "https://github.com/dotnet/roslyn/issues/20083")] public void MethodImplementationInDerived_12() { var source1 = @" public interface I1 { void M1(){ System.Console.WriteLine(""Unexpected!!!""); } } public interface I2 : I1 { void I1.M1() { System.Console.WriteLine(""I2.I1.M1""); } } public interface I3 : I1 { void I1.M1() { System.Console.WriteLine(""I3.I1.M1""); } } public interface I4 : I1 { void I1.M1() { System.Console.WriteLine(""I4.I1.M1""); } } public interface I5 : I2, I3 { void I1.M1() { System.Console.WriteLine(""I5.I1.M1""); } } public interface I6 : I1, I2, I3, I5 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = i1.GetMember<MethodSymbol>("M1"); var i2 = FindType(m, "I2"); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); var i5 = FindType(m, "I5"); var i5m1 = i5.GetMember<MethodSymbol>("I1.M1"); var i6 = FindType(m, "I6"); ValidateExplicitImplementation(i2m1); ValidateExplicitImplementation(i5m1); Assert.Same(i1m1, i1.FindImplementationForInterfaceMember(i1m1)); Assert.Same(i2m1, i2.FindImplementationForInterfaceMember(i1m1)); Assert.Same(i5m1, i5.FindImplementationForInterfaceMember(i1m1)); Assert.Same(i5m1, i6.FindImplementationForInterfaceMember(i1m1)); } CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var refs1 = new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }; var source2 = @" public interface I7 : I2, I3 {} public interface I8 : I1, I2, I3, I5, I4 {} "; var source3 = @" class Test1 : I2, I3 {} class Test2 : I7 {} class Test3 : I1, I2, I3, I4 {} class Test4 : I1, I2, I3, I5, I4 {} class Test5 : I8 {} "; var source4 = @" class Test5 : I2 {} class Test6 : I1, I2, I3, I5 {} class Test7 : I6 { static void Main() { I1 i1 = new Test5(); i1.M1(); i1 = new Test6(); i1.M1(); i1 = new Test7(); i1.M1(); } } "; var source5 = @" class Test8 : I2, I3 { void I1.M1() { System.Console.WriteLine(""Test8.I1.M1""); } static void Main() { I1 i1 = new Test8(); i1.M1(); i1 = new Test9(); i1.M1(); i1 = new Test10(); i1.M1(); i1 = new Test11(); i1.M1(); i1 = new Test12(); i1.M1(); } } class Test9 : I7 { void I1.M1() { System.Console.WriteLine(""Test9.I1.M1""); } } class Test10 : I1, I2, I3, I4 { public void M1() { System.Console.WriteLine(""Test10.M1""); } } class Test11 : I1, I2, I3, I5, I4 { public void M1() { System.Console.WriteLine(""Test11.M1""); } } class Test12 : I8 { public virtual void M1() { System.Console.WriteLine(""Test12.M1""); } } "; foreach (var ref1 in refs1) { var compilation2 = CreateCompilation(source2, new[] { ref1 }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // According to LDM decision captured at https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-06-14.md, // we do not require interfaces to have a most specific implementation of all members. Therefore, there are no // errors in this compilation. compilation2.VerifyDiagnostics(); Validate2(compilation2.SourceModule); void Validate2(ModuleSymbol m) { Validate1(m); var i1 = FindType(m, "I1"); var i1m1 = i1.GetMember<MethodSymbol>("M1"); var i7 = FindType(m, "I7"); var i8 = FindType(m, "I8"); Assert.Null(i7.FindImplementationForInterfaceMember(i1m1)); Assert.Null(i8.FindImplementationForInterfaceMember(i1m1)); } CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); compilation2 = CreateCompilation(source2, new[] { ref1 }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); Validate2(compilation2.SourceModule); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); var refs2 = new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }; var compilation4 = CreateCompilation(source4, new[] { ref1 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); Validate4(compilation4.SourceModule); void Validate4(ModuleSymbol m) { Validate1(m); var i1 = FindType(m, "I1"); var i1m1 = i1.GetMember<MethodSymbol>("M1"); var i2 = FindType(m, "I2"); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); var i5 = FindType(m, "I5"); var i5m1 = i5.GetMember<MethodSymbol>("I1.M1"); var test5 = FindType(m, "Test5"); var test6 = FindType(m, "Test6"); var test7 = FindType(m, "Test7"); Assert.Same(i2m1, test5.FindImplementationForInterfaceMember(i1m1)); Assert.Same(i5m1, test6.FindImplementationForInterfaceMember(i1m1)); Assert.Same(i5m1, test7.FindImplementationForInterfaceMember(i1m1)); } CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.I1.M1 I5.I1.M1 I5.I1.M1 " , verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate4); foreach (var ref2 in refs2) { var compilation3 = CreateCompilation(source3, new[] { ref1, ref2 }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8505: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I2.I1.M1()', nor 'I3.I1.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1()", "I2.I1.M1()", "I3.I1.M1()").WithLocation(2, 15), // (5,15): error CS8505: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I2.I1.M1()', nor 'I3.I1.M1()' are most specific. // class Test2 : I7 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I7").WithArguments("I1.M1()", "I2.I1.M1()", "I3.I1.M1()").WithLocation(5, 15), // (8,15): error CS8505: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I2.I1.M1()', nor 'I3.I1.M1()' are most specific. // class Test3 : I1, I2, I3, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.M1()", "I2.I1.M1()", "I3.I1.M1()").WithLocation(8, 15), // (11,15): error CS8505: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I5.I1.M1()', nor 'I4.I1.M1()' are most specific. // class Test4 : I1, I2, I3, I5, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.M1()", "I5.I1.M1()", "I4.I1.M1()").WithLocation(11, 15), // (14,15): error CS8505: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I5.I1.M1()', nor 'I4.I1.M1()' are most specific. // class Test5 : I8 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I8").WithArguments("I1.M1()", "I5.I1.M1()", "I4.I1.M1()").WithLocation(14, 15) ); Validate3(compilation3.SourceModule); void Validate3(ModuleSymbol m) { Validate1(m); Validate2(m); var i1 = FindType(m, "I1"); var i1m1 = i1.GetMember<MethodSymbol>("M1"); var test1 = FindType(m, "Test1"); var test2 = FindType(m, "Test2"); var test3 = FindType(m, "Test3"); var test4 = FindType(m, "Test4"); var test5 = FindType(m, "Test5"); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test3.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test4.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test5.FindImplementationForInterfaceMember(i1m1)); } var compilation5 = CreateCompilation(source5, new[] { ref1, ref2 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics(); Validate5(compilation5.SourceModule); void Validate5(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = i1.GetMember<MethodSymbol>("M1"); var test8 = FindType(m, "Test8"); var test9 = FindType(m, "Test9"); var test10 = FindType(m, "Test10"); var test11 = FindType(m, "Test11"); var test12 = FindType(m, "Test12"); Assert.Same(test8.GetMember<MethodSymbol>("I1.M1"), test8.FindImplementationForInterfaceMember(i1m1)); Assert.Same(test9.GetMember<MethodSymbol>("I1.M1"), test9.FindImplementationForInterfaceMember(i1m1)); Assert.Same(test10.GetMember<MethodSymbol>("M1"), test10.FindImplementationForInterfaceMember(i1m1)); Assert.Same(test11.GetMember<MethodSymbol>("M1"), test11.FindImplementationForInterfaceMember(i1m1)); Assert.Same(test12.GetMember<MethodSymbol>("M1"), test12.FindImplementationForInterfaceMember(i1m1)); } CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"Test8.I1.M1 Test9.I1.M1 Test10.M1 Test11.M1 Test12.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate5); } } } private static NamedTypeSymbol FindType(ModuleSymbol m, string name) { var result = m.GlobalNamespace.GetMember<NamedTypeSymbol>(name); if ((object)result != null) { return result; } foreach (var assembly in m.ReferencedAssemblySymbols) { result = assembly.Modules[0].GlobalNamespace.GetMember<NamedTypeSymbol>(name); if ((object)result != null) { return result; } } Assert.NotNull(result); return result; } [Fact] public void MethodImplementationInDerived_13() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { void I1.M1() { } } public interface I3 : I1 { void I1.M1() { } } "; var source2 = @" class Test1 : I2, I3 { public int M1() => 1; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (2,15): error CS8505: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I2.I1.M1()', nor 'I3.I1.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1()", "I2.I1.M1()", "I3.I1.M1()").WithLocation(2, 15), // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implement 'I1.M1()' because it does not have the matching return type of 'void'. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test1", "I1.M1()", "Test1.M1()", "void").WithLocation(2, 15) ); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8505: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I2.I1.M1()', nor 'I3.I1.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1()", "I2.I1.M1()", "I3.I1.M1()").WithLocation(2, 15), // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implement 'I1.M1()' because it does not have the matching return type of 'void'. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test1", "I1.M1()", "Test1.M1()", "void").WithLocation(2, 15) ); } [Fact] [WorkItem(20084, "https://github.com/dotnet/roslyn/issues/20084")] public void MethodImplementationInDerived_14() { var source1 = @" public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } void M2<S>() { System.Console.WriteLine(""I1.M2""); } } public interface I2<T> : I1<T> { void I1<T>.M1() { System.Console.WriteLine(""I2.I1.M1""); } void I1<T>.M2<S>() { System.Console.WriteLine(""I2.I1.M2""); } } public interface I3<T> : I1<T> {} "; var source2 = @" class Test1 : I1<int> { static void Main() { I1<int> i1Int = new Test1(); i1Int.M1(); i1Int.M2<int>(); I1<long> i1Long = new Test2(); i1Long.M1(); i1Long.M2<int>(); } } class Test2 : I2<long> {} "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = i1.GetMember<MethodSymbol>("M1"); var i1m2 = i1.GetMember<MethodSymbol>("M2"); var i2 = FindType(m, "I2"); var i2m1 = i2.GetMember<MethodSymbol>("I1<T>.M1"); var i2m2 = i2.GetMember<MethodSymbol>("I1<T>.M2"); var i2i1 = i2.InterfacesNoUseSiteDiagnostics().Single(); var i2i1m1 = i2i1.GetMember<MethodSymbol>("M1"); var i2i1m2 = i2i1.GetMember<MethodSymbol>("M2"); var i3 = FindType(m, "I3"); var i3i1 = i3.InterfacesNoUseSiteDiagnostics().Single(); var i3i1m1 = i3i1.GetMember<MethodSymbol>("M1"); var i3i1m2 = i3i1.GetMember<MethodSymbol>("M2"); Assert.Same(i1m1, i1.FindImplementationForInterfaceMember(i1m1)); Assert.Same(i1m2, i1.FindImplementationForInterfaceMember(i1m2)); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(i2.FindImplementationForInterfaceMember(i1m2)); Assert.Null(i2.FindImplementationForInterfaceMember(i3i1m1)); Assert.Null(i2.FindImplementationForInterfaceMember(i3i1m2)); Assert.Same(i2m1, i2.FindImplementationForInterfaceMember(i2i1m1)); Assert.Same(i2m2, i2.FindImplementationForInterfaceMember(i2i1m2)); Assert.Null(i3.FindImplementationForInterfaceMember(i1m1)); Assert.Null(i3.FindImplementationForInterfaceMember(i1m2)); Assert.Null(i3.FindImplementationForInterfaceMember(i2i1m1)); Assert.Null(i3.FindImplementationForInterfaceMember(i2i1m2)); Assert.Same(i3i1m1, i3.FindImplementationForInterfaceMember(i3i1m1)); Assert.Same(i3i1m2, i3.FindImplementationForInterfaceMember(i3i1m2)); ValidateExplicitImplementation(i2m1); ValidateExplicitImplementation(i2m2); var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test1i1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)); var test1i1m1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)).GetMember<MethodSymbol>("M1"); var test1i1m2 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)).GetMember<MethodSymbol>("M2"); var test2 = m.GlobalNamespace.GetTypeMember("Test2"); var test2i1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)); var test2i1m1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)).GetMember<MethodSymbol>("M1"); var test2i1m2 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)).GetMember<MethodSymbol>("M2"); var test2i2 = i2.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)); var test2i2m1 = i2.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)).GetMember<MethodSymbol>("I1<T>.M1"); var test2i2m2 = i2.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)).GetMember<MethodSymbol>("I1<T>.M2"); Assert.NotSame(test1i1, test1i1m1.ContainingType); Assert.NotSame(test1i1, test1i1m2.ContainingType); Assert.NotSame(test2i1, test2i1m1.ContainingType); Assert.NotSame(test2i1, test2i1m2.ContainingType); Assert.NotSame(test2i2, test2i2m1.ContainingType); Assert.NotSame(test2i2, test2i2m2.ContainingType); Assert.Null(test1i1.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1i1.FindImplementationForInterfaceMember(i1m2)); Assert.Equal(test1i1m1, test1i1.FindImplementationForInterfaceMember(test1i1m1)); Assert.Equal(test1i1m2, test1i1.FindImplementationForInterfaceMember(test1i1m2)); Assert.Equal(test2i1m1, test2i1.FindImplementationForInterfaceMember(test2i1m1)); Assert.Equal(test2i1m2, test2i1.FindImplementationForInterfaceMember(test2i1m2)); Assert.Null(test2i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test2i2.FindImplementationForInterfaceMember(i1m2)); Assert.Equal(test2i2m1, test2i2.FindImplementationForInterfaceMember(test2i1m1)); Assert.Equal(test2i2m2, test2i2.FindImplementationForInterfaceMember(test2i1m2)); ValidateExplicitImplementation(test2i2m1); ValidateExplicitImplementation(test2i2m2); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m2)); Assert.Equal(test1i1m1, test1.FindImplementationForInterfaceMember(test1i1m1)); Assert.Equal(test1i1m2, test1.FindImplementationForInterfaceMember(test1i1m2)); Assert.Null(test2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1m2)); Assert.Equal(test2i2m1, test2.FindImplementationForInterfaceMember(test2i1m1)); Assert.Equal(test2i2m2, test2.FindImplementationForInterfaceMember(test2i1m2)); } CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1 I1.M2 I2.I1.M1 I2.I1.M2 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1 I1.M2 I2.I1.M1 I2.I1.M2 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1 I1.M2 I2.I1.M1 I2.I1.M2 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); } [Fact] public void MethodImplementationInDerived_15() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2 : I1<string> { void I1<string>.M1() { } } public interface I3 : I1<string?> { void I1<string?>.M1() { } } "; var source2 = @"#nullable enable warnings class Test1 : I2, I3 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (2,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(2, 7), // (2,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(2, 15), // (2,19): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I3").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(2, 19) ); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (2,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(2, 7), // (2,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(2, 15), // (2,19): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I3").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(2, 19) ); test1 = compilation3.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); } [Fact] public void MethodImplementationInDerived_16() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2 : I1<string> { void I1<string>.M1() { } } public interface I3 : I1<string?> { void I1<string?>.M1() { } } "; var source2 = @"#nullable enable warnings class Test1 : I2, I3, I1<string> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (2,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(2, 7), // (2,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(2, 15), // (2,19): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I3").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(2, 19), // (2,23): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1<string>").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(2, 23) ); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[4].GetMember("M1"))); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (2,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(2, 7), // (2,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(2, 15), // (2,19): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I3").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(2, 19), // (2,23): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1<string>").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(2, 23) ); test1 = compilation3.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[4].GetMember("M1"))); } [Fact] public void MethodImplementationInDerived_17() { var source1 = @" public interface I1<T> { void M1(); } public interface I2 : I1<string> { void I1<string>.M1() { } } #nullable enable public interface I3 : I1<string?> { void I1<string?>.M1() { } } "; var source2 = @" #nullable enable class Test1 : I2, I3, I1<string> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (3,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(3, 15), // (3,19): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I3").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(3, 19), // (3,23): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1<string>").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(3, 23) ); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[4].GetMember("M1"))); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (3,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(3, 15), // (3,19): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I3").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(3, 19), // (3,23): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1<string>").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(3, 23) ); test1 = compilation3.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[4].GetMember("M1"))); } [Fact] public void MethodImplementationInDerived_18() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2 : I1<string> { void I1<string>.M1() { } } public interface I3 : I1<string?> { void I1<string?>.M1() { } } "; var source2 = @" #nullable enable class Test1 : I2, I3, I1<string?> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3, I1<string?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7), // (4,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string?> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(4, 15), // (4,23): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string?> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1<string?>").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(4, 23) ); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3, I1<string?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7), // (4,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string?> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(4, 15), // (4,23): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string?> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1<string?>").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(4, 23) ); test1 = compilation3.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); } [Fact] public void MethodImplementationInDerived_19() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2 : I1<string> { } public interface I3 : I2, I1<string?> { void I1<string>.M1() { } void I1<string?>.M1() { } } "; var source2 = @" #nullable enable class Test1 : I3 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (13,18): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'I3' with different nullability of reference types. // public interface I3 : I2, I1<string?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "I3").WithArguments("I1<string?>", "I3").WithLocation(13, 18), // (13,18): error CS8646: 'I1<string>.M1()' is explicitly implemented more than once. // public interface I3 : I2, I1<string?> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "I3").WithArguments("I1<string>.M1()").WithLocation(13, 18), // (13,18): error CS8646: 'I1<string?>.M1()' is explicitly implemented more than once. // public interface I3 : I2, I1<string?> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "I3").WithArguments("I1<string?>.M1()").WithLocation(13, 18) ); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7), // (4,15): error CS0535: 'Test1' does not implement interface member 'I1<string>.M1()' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1<string>.M1()").WithLocation(4, 15), // (4,15): error CS0535: 'Test1' does not implement interface member 'I1<string?>.M1()' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1<string?>.M1()").WithLocation(4, 15) ); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I3", "I2", "I1<System.String>", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[2].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); } [Fact] public void MethodImplementationInDerived_20() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2 : I1<string> { } public interface I3 : I1<string?> { void I1<string?>.M1() { System.Console.WriteLine(""I3.M1""); } } "; var source2 = @" #nullable enable class Test1 : I2, I3 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I3.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I3.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7), // (4,15): warning CS8644: 'Test1' does not implement interface member 'I1<string>.M1()'. Nullability of reference types in interface implemented by the base type doesn't match. // class Test1 : I2, I3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, "I2").WithArguments("Test1", "I1<string>.M1()").WithLocation(4, 15) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I3.M1 I3.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_21() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2 : I1<string> { } public interface I3 : I1<string?> { void I1<string?>.M1() { System.Console.WriteLine(""I3.M1""); } } "; var source2 = @" #nullable enable class Test1 : I3, I2 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I3", "I1<System.String?>", "I2", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I3.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I3.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I3, I2 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string>", "Test1").WithLocation(4, 7), // (4,19): warning CS8644: 'Test1' does not implement interface member 'I1<string>.M1()'. Nullability of reference types in interface implemented by the base type doesn't match. // class Test1 : I3, I2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, "I2").WithArguments("Test1", "I1<string>.M1()").WithLocation(4, 19) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I3.M1 I3.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_22() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2<T> : I1<T> { void I1<T>.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3 : I2<string> { } public interface I4 : I2<string?> { } "; var source2 = @" #nullable enable class Test1 : I3, I4 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I3", "I2<System.String>", "I1<System.String>", "I4", "I2<System.String?>", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I2<System.String?>.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[2].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I2<System.String?>.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[5].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I2<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I3, I4 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I2<string?>", "Test1").WithLocation(4, 7), // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I3, I4 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I2.M1 I2.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_23() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2<T> : I1<T> { void I1<T>.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3 : I2<string> { } public interface I4 : I2<string?> { } "; var source2 = @" #nullable enable class Test1 : I4, I3 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I4", "I2<System.String?>", "I1<System.String?>", "I3", "I2<System.String>", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I2<System.String>.I1<System.String>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[2].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I2<System.String>.I1<System.String>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[5].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I2<string>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I4, I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I2<string>", "Test1").WithLocation(4, 7), // (4,7): warning CS8645: 'I1<string>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I4, I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string>", "Test1").WithLocation(4, 7) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I2.M1 I2.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_24() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2 : I1<string> { void I1<string?>.M1() { System.Console.WriteLine(""I2.M1""); } } "; var source2 = @" #nullable enable class Test1 : I2 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (11,10): warning CS8643: Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type. // void I1<string?>.M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInExplicitlyImplementedInterface, "I1<string?>").WithLocation(11, 10) ); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I2.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I2.M1 I2.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_25() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2 : I1<string> { void I1<string>.M1() { System.Console.WriteLine(""I2.M1""); } } "; var source2 = @" #nullable enable class Test1 : I2, I1<string?> { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I1<string?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7), // (4,19): warning CS8644: 'Test1' does not implement interface member 'I1<string?>.M1()'. Nullability of reference types in interface implemented by the base type doesn't match. // class Test1 : I2, I1<string?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, "I1<string?>").WithArguments("Test1", "I1<string?>.M1()").WithLocation(4, 19) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I2.M1 I2.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_26() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2 : I1<string?> { void I1<string>.M1() { System.Console.WriteLine(""I2.M1""); } } "; var source2 = @" #nullable enable class Test1 : I2, I1<string?> { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (11,10): warning CS8643: Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type. // void I1<string>.M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInExplicitlyImplementedInterface, "I1<string>").WithLocation(11, 10) ); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I2.M1 I2.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_27() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2<T>: I1<T> { void I1<T>.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3<T> : I1<T> { void I1<T>.M1() { System.Console.WriteLine(""I3.M1""); } } public interface I4 : I2<string?>, I3<string?> { void I1<string?>.M1() { System.Console.WriteLine(""I4.M1""); } } "; var source2 = @" #nullable enable class Test1 : I2<string>, I3<string>, I4 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2<System.String>", "I3<System.String>", "I1<System.String>", "I4", "I2<System.String?>", "I3<System.String?>", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I4.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[2].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I4.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[6].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I2<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2<string>, I3<string>, I4 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I2<string?>", "Test1").WithLocation(4, 7), // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2<string>, I3<string>, I4 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7), // (4,7): warning CS8645: 'I3<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2<string>, I3<string>, I4 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I3<string?>", "Test1").WithLocation(4, 7), // (4,15): warning CS8644: 'Test1' does not implement interface member 'I1<string>.M1()'. Nullability of reference types in interface implemented by the base type doesn't match. // class Test1 : I2<string>, I3<string>, I4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, "I2<string>").WithArguments("Test1", "I1<string>.M1()").WithLocation(4, 15) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I4.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_28() { var source1 = @" public interface I2 { protected void M1(); } public interface I4 { protected void M1(); } public interface I5 : I4 { static void Test(I5 i4) { i4.M1(); } } public interface I6 : I2 { static void Test(I6 i2) { i2.M1(); } } "; var source2 = @" public interface I1 : I6, I5 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { I6.Test(new Test1()); I5.Test(new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); } var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); foreach (var reference in new[] { compilation4.ToMetadataReference(), compilation4.EmitToImageReference() }) { var compilation5 = CreateCompilation(source2 + source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics(); CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); } } [Fact] public void MethodImplementationInDerived_29() { var source1 = @" public interface I2 { protected internal void M1(); } public interface I4 { protected internal void M1(); } public interface I5 : I4 { static void Test(I5 i4) { i4.M1(); } } public interface I6 : I2 { static void Test(I6 i2) { i2.M1(); } } "; var source2 = @" public interface I1 : I6, I5 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { I6.Test(new Test1()); I5.Test(new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); } var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); foreach (var reference in new[] { compilation4.ToMetadataReference(), compilation4.EmitToImageReference() }) { var compilation5 = CreateCompilation(source2 + source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics(); CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); } } [Fact] public void MethodImplementationInDerived_30() { var source1 = @" public interface I2 { private protected void M1(); } public interface I4 { private protected void M1(); } public interface I5 : I4 { static void Test(I5 i4) { i4.M1(); } } public interface I6 : I2 { static void Test(I6 i2) { i2.M1(); } } "; var source2 = @" public interface I1 : I6, I5 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { I6.Test(new Test1()); I5.Test(new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); } var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); foreach (var reference in new[] { compilation4.ToMetadataReference(), compilation4.EmitToImageReference() }) { var compilation5 = CreateCompilation(source2 + source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics( // (4,13): error CS0122: 'I2.M1()' is inaccessible due to its protection level // void I2.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1()").WithLocation(4, 13), // (8,13): error CS0122: 'I4.M1()' is inaccessible due to its protection level // void I4.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I4.M1()").WithLocation(8, 13) ); } } [Fact] public void MethodImplementationInDerived_31() { var source1 = @" public interface I1 { void M1(); void M2(); } public interface I2 : I1 { public virtual void M1() {} new public virtual void M2() {} } public interface I3 : I1, I2 { } class Test1 : I1, I2 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (10,25): warning CS0108: 'I2.M1()' hides inherited member 'I1.M1()'. Use the new keyword if hiding was intended. // public virtual void M1() Diagnostic(ErrorCode.WRN_NewRequired, "M1").WithArguments("I2.M1()", "I1.M1()").WithLocation(10, 25), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.M2()' // class Test1 : I1, I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M2()").WithLocation(20, 15), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I1, I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M1()").WithLocation(20, 15) ); } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void PropertyImplementationInDerived_01() { var source1 = @" public interface I2 { int M1 {get;} } public interface I4 { int M1 {set;} } public interface I5 : I4 { } public interface I1 : I2, I5 { int I2.M1 { get { System.Console.WriteLine(""I2.M1""); return 1; } } int I4.M1 { set => System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source2 = @" class Test1 : I1 { static void Main() { I2 i2 = new Test1(); _ = i2.M1; I4 i4 = new Test1(); i4.M1 = 0; } } "; ValidatePropertyImplementationInDerived_01(source1, source2); } private void ValidatePropertyImplementationInDerived_01(string source1, string source2) { foreach (var options in new[] { TestOptions.DebugExe, TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All) }) { var compilation1 = CreateCompilation(source1 + source2, options: options, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidatePropertyImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationInDerived_01); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: options, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidatePropertyImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationInDerived_01); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: options, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidatePropertyImplementationInDerived_01(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationInDerived_01); } } private static void ValidatePropertyImplementationInDerived_01(ModuleSymbol m) { ValidatePropertyImplementationInDerived_01(m, i4M1IsAbstract: false); } private static void ValidatePropertyImplementationInDerived_01(ModuleSymbol m, bool i4M1IsAbstract) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var i1i2m1 = i1.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); var i1i4m1 = i1.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I4.")).Single(); var i2 = i1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I2").Single(); var i2m1 = i2.GetMembers().OfType<PropertySymbol>().Single(); var i4 = i1.AllInterfacesNoUseSiteDiagnostics.Where(i => i.Name == "I4").Single(); var i4m1 = i4.GetMembers().OfType<PropertySymbol>().Single(); var i3 = i1.ContainingNamespace.GetTypeMember("I3"); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); ValidateExplicitImplementation(i1i2m1); ValidateExplicitImplementation(i1i4m1, i4M1IsAbstract); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1i2m1); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1i4m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, test1, i2m1); VerifyFindImplementationForInterfaceMemberSame(i4M1IsAbstract ? null : i1i4m1, test1, i4m1); VerifyFindImplementationForInterfaceMemberSame(null, i1, i1i2m1); VerifyFindImplementationForInterfaceMemberSame(null, i1, i1i4m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, i1, i2m1); VerifyFindImplementationForInterfaceMemberSame(i4M1IsAbstract ? null : i1i4m1, i1, i4m1); VerifyFindImplementationForInterfaceMemberSame(i2m1.IsAbstract ? null : i2m1, i2, i2m1); VerifyFindImplementationForInterfaceMemberSame(i4m1.IsAbstract ? null : i4m1, i4, i4m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, i3, i2m1); VerifyFindImplementationForInterfaceMemberSame(i4M1IsAbstract ? null : i1i4m1, i3, i4m1); } private static void VerifyFindImplementationForInterfaceMemberSame(PropertySymbol expected, NamedTypeSymbol implementingType, PropertySymbol interfaceProperty) { Assert.Same(expected, implementingType.FindImplementationForInterfaceMember(interfaceProperty)); ValidateAccessor(expected?.GetMethod, interfaceProperty.GetMethod); ValidateAccessor(expected?.SetMethod, interfaceProperty.SetMethod); void ValidateAccessor(MethodSymbol accessor, MethodSymbol interfaceAccessor) { if ((object)interfaceAccessor != null) { Assert.Same(interfaceAccessor.DeclaredAccessibility == Accessibility.Private ? null : accessor, implementingType.FindImplementationForInterfaceMember(interfaceAccessor)); } else { Assert.Null(accessor); } } } private static void VerifyFindImplementationForInterfaceMemberEqual(PropertySymbol expected, NamedTypeSymbol implementingType, PropertySymbol interfaceProperty) { Assert.Equal(expected, implementingType.FindImplementationForInterfaceMember(interfaceProperty)); ValidateAccessor(expected?.GetMethod, interfaceProperty.GetMethod); ValidateAccessor(expected?.SetMethod, interfaceProperty.SetMethod); void ValidateAccessor(MethodSymbol accessor, MethodSymbol interfaceAccessor) { if ((object)interfaceAccessor != null) { Assert.Equal(accessor, implementingType.FindImplementationForInterfaceMember(interfaceAccessor)); } else { Assert.Null(accessor); } } } private static void ValidateExplicitImplementation(PropertySymbol m1, bool isAbstract = false) { Assert.Equal(isAbstract, m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.Equal(isAbstract, m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); ValidateAccessor(m1.GetMethod, isAbstract); ValidateAccessor(m1.SetMethod, isAbstract); static void ValidateAccessor(MethodSymbol accessor, bool isAbstract) { if ((object)accessor != null) { ValidateExplicitImplementation(accessor, isAbstract); } } } [Fact] public void PropertyImplementationInDerived_02() { var source1 = @" public interface I2 { int M1 {get;} } public interface I4 { int M1 {set;} } public interface I1 : I2, I4 { int I2.M1 => Getter(); private int Getter() { System.Console.WriteLine(""I2.M1""); return 1; } int I4.M1 { set { System.Console.WriteLine(""I2.M1""); } } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_02(source1, new DiagnosticDescription[] { // (14,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int I2.M1 => Getter(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "Getter()").WithArguments("default interface implementation", "8.0").WithLocation(14, 18), // (16,17): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // private int Getter() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "Getter").WithArguments("default interface implementation", "8.0").WithLocation(16, 17), // (24,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // set Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(24, 9) }, // (6,15): error CS8506: 'I1.I2.M1.get' cannot implement interface member 'I2.M1.get' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1.get", "I2.M1.get", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15), // (6,15): error CS8506: 'I1.I4.M1.set' cannot implement interface member 'I4.M1.set' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1.set", "I4.M1.set", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15) ); } private void ValidatePropertyImplementationInDerived_02(string source1, DiagnosticDescription[] expected1, params DiagnosticDescription[] expected2) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected1); ValidatePropertyImplementationInDerived_01(compilation1.SourceModule); var source2 = @" public interface I3 : I1 { } class Test1 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(expected2); ValidatePropertyImplementationInDerived_01(compilation2.SourceModule); } [Fact] public void PropertyImplementationInDerived_03() { var source1 = @" public interface I2 { int M1 {get; set;} } public interface I4 { int M1 {set;} } public interface I1 : I2, I4 { int I2.M1 { get { System.Console.WriteLine(""I2.M1""); return 1; } set { System.Console.WriteLine(""I2.M1""); } } int I4.M1 { set { System.Console.WriteLine(""I2.M1""); } } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_03(source1, new DiagnosticDescription[] { // (16,9): error CS8501: Target runtime doesn't support default interface implementation. // get Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(16, 9), // (21,9): error CS8501: Target runtime doesn't support default interface implementation. // set Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(21, 9), // (29,9): error CS8501: Target runtime doesn't support default interface implementation. // set Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(29, 9) }, // (6,15): error CS8502: 'I1.I2.M1.set' cannot implement interface member 'I2.M1.set' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1.set", "I2.M1.set", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I2.M1.get' cannot implement interface member 'I2.M1.get' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1.get", "I2.M1.get", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I4.M1.set' cannot implement interface member 'I4.M1.set' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1.set", "I4.M1.set", "Test1").WithLocation(6, 15) ); } private void ValidatePropertyImplementationInDerived_03(string source1, DiagnosticDescription[] expected1, params DiagnosticDescription[] expected2) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected1); ValidatePropertyImplementationInDerived_01(compilation1.SourceModule); var source2 = @" public interface I3 : I1 { } class Test1 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(expected2); } [Fact] public void PropertyImplementationInDerived_04() { var source1 = @" public interface I2 { int M1 {get;} } public interface I4 { int M1 {set;} } public interface I1 : I2, I4 { int I2.M1 {get;} int I4.M1 {set;} } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (14,16): error CS0501: 'I1.I2.M1.get' must declare a body because it is not marked abstract, extern, or partial // int I2.M1 {get;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.I2.M1.get").WithLocation(14, 16), // (15,16): error CS0501: 'I1.I4.M1.set' must declare a body because it is not marked abstract, extern, or partial // int I4.M1 {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.I4.M1.set").WithLocation(15, 16) ); } private void ValidatePropertyImplementationInDerived_04(string source1, params DiagnosticDescription[] expected) { ValidatePropertyImplementationInDerived_04(source1, i4M1IsAbstract: false, expected); } private void ValidatePropertyImplementationInDerived_04(string source1, bool i4M1IsAbstract, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); ValidatePropertyImplementationInDerived_01(compilation1.SourceModule, i4M1IsAbstract); } [Fact] public void PropertyImplementationInDerived_05() { var source1 = @" public interface I2 { int M1 {get;} } public interface I4 { int M1 {set;} } public interface I1 { int I2.M1 {get => throw null;} int I4.M1 {set => throw null;} } "; ValidatePropertyImplementationInDerived_05(source1, // (14,9): error CS0540: 'I1.I2.M1': containing type does not implement interface 'I2' // int I2.M1 {get => throw null;} Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.I2.M1", "I2").WithLocation(14, 9), // (15,9): error CS0540: 'I1.I4.M1': containing type does not implement interface 'I4' // int I4.M1 {set => throw null;} Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I4").WithArguments("I1.I4.M1", "I4").WithLocation(15, 9) ); } private void ValidatePropertyImplementationInDerived_05(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); } [Fact] public void PropertyImplementationInDerived_06() { var source1 = @" public interface I2 { int M1 {get; set;} } public interface I4 { int M1 {get; set;} } public interface I1 : I2, I4 { public static int I2.M1 { internal get => throw null; set => throw null; } internal virtual int I4.M1 { public get => throw null; set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (14,26): error CS0106: The modifier 'static' is not valid for this item // public static int I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("static").WithLocation(14, 26), // (14,26): error CS0106: The modifier 'public' is not valid for this item // public static int I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("public").WithLocation(14, 26), // (16,18): error CS0106: The modifier 'internal' is not valid for this item // internal get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("internal").WithLocation(16, 18), // (19,29): error CS0106: The modifier 'internal' is not valid for this item // internal virtual int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("internal").WithLocation(19, 29), // (19,29): error CS0106: The modifier 'virtual' is not valid for this item // internal virtual int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("virtual").WithLocation(19, 29), // (21,16): error CS0106: The modifier 'public' is not valid for this item // public get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("public").WithLocation(21, 16) ); } [Fact] public void PropertyImplementationInDerived_07() { var source1 = @" public interface I2 { int M1 {get; set;} } public interface I4 { int M1 {get; set;} } public interface I1 : I2, I4 { private sealed int I2.M1 { private get => throw null; set => throw null; } protected abstract int I4.M1 { get => throw null; protected set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, i4M1IsAbstract: true, // (14,27): error CS0106: The modifier 'sealed' is not valid for this item // private sealed int I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("sealed").WithLocation(14, 27), // (14,27): error CS0106: The modifier 'private' is not valid for this item // private sealed int I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("private").WithLocation(14, 27), // (16,17): error CS0106: The modifier 'private' is not valid for this item // private get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("private").WithLocation(16, 17), // (19,31): error CS0106: The modifier 'protected' is not valid for this item // protected abstract int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected").WithLocation(19, 31), // (21,9): error CS0500: 'I1.I4.M1.get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.I4.M1.get").WithLocation(21, 9), // (22,19): error CS0106: The modifier 'protected' is not valid for this item // protected set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("protected").WithLocation(22, 19), // (22,19): error CS0500: 'I1.I4.M1.set' cannot declare a body because it is marked abstract // protected set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I1.I4.M1.set").WithLocation(22, 19), // (30,15): error CS0535: 'Test1' does not implement interface member 'I4.M1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I4.M1").WithLocation(30, 15) ); } [Fact] public void PropertyImplementationInDerived_08() { var source1 = @" public interface I2 { int M1 {get; set;} } public interface I4 { int M1 {get; set;} } public interface I1 : I2, I4 { private protected int I2.M1 { private protected get => throw null; set => throw null; } internal protected override int I4.M1 { get => throw null; internal protected set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (14,30): error CS0106: The modifier 'private protected' is not valid for this item // private protected int I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("private protected").WithLocation(14, 30), // (16,27): error CS0106: The modifier 'private protected' is not valid for this item // private protected get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("private protected").WithLocation(16, 27), // (19,40): error CS0106: The modifier 'protected internal' is not valid for this item // internal protected override int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected internal").WithLocation(19, 40), // (19,40): error CS0106: The modifier 'override' is not valid for this item // internal protected override int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("override").WithLocation(19, 40), // (22,28): error CS0106: The modifier 'protected internal' is not valid for this item // internal protected set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("protected internal").WithLocation(22, 28) ); } [Fact] public void PropertyImplementationInDerived_09() { var source1 = @" public interface I2 { int M1 {get;} } public interface I1 : I2 { extern int I2.M1 {get;} } public interface I3 : I1 { } class Test1 : I1 {} "; var source2 = @" public interface I2 { int M1 {set;} } public interface I1 : I2 { extern int I2.M1 { set {}} } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_09(source1, source2, new DiagnosticDescription[] { // (9,23): warning CS0626: Method, operator, or accessor 'I1.I2.M1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int I2.M1 {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.I2.M1.get").WithLocation(9, 23) }, new DiagnosticDescription[] { // (9,23): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // extern int I2.M1 {get;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(9, 23), // (9,23): warning CS0626: Method, operator, or accessor 'I1.I2.M1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int I2.M1 {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.I2.M1.get").WithLocation(9, 23) }, new DiagnosticDescription[] { // (9,23): error CS8501: Target runtime doesn't support default interface implementation. // extern int I2.M1 {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(9, 23), // (9,23): warning CS0626: Method, operator, or accessor 'I1.I2.M1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int I2.M1 {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.I2.M1.get").WithLocation(9, 23) }, // (10,7): error CS0179: 'I1.I2.M1.set' cannot be extern and declare a body // { set {}} Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("I1.I2.M1.set").WithLocation(10, 7) ); } private void ValidatePropertyImplementationInDerived_09(string source1, string source2, DiagnosticDescription[] expected1, DiagnosticDescription[] expected2, DiagnosticDescription[] expected3, params DiagnosticDescription[] expected4) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected1); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var i1i2m1 = GetSingleProperty(i1); var i2 = i1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I2").Single(); var i2m1 = GetSingleProperty(i2); var i3 = i1.ContainingNamespace.GetTypeMember("I3"); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); ValidateExplicitExternImplementation(i1i2m1); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1i2m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, test1, i2m1); VerifyFindImplementationForInterfaceMemberSame(null, i1, i1i2m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, i1, i2m1); VerifyFindImplementationForInterfaceMemberSame(null, i2, i2m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, i3, i2m1); } CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(expected2); Validate1(compilation2.SourceModule); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected3); Validate1(compilation3.SourceModule); var compilation4 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(expected4); Validate1(compilation4.SourceModule); } private static void ValidateExplicitExternImplementation(PropertySymbol m1) { Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.NotEqual(m1.OriginalDefinition is PEPropertySymbol, m1.IsExtern); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); ValidateAccessor(m1.GetMethod); ValidateAccessor(m1.SetMethod); void ValidateAccessor(MethodSymbol accessor) { if ((object)accessor != null) { ValidateExplicitExternImplementation(accessor); } } } [Fact] public void PropertyImplementationInDerived_10() { var source1 = @" public interface I1 { int M1 {get;set;} int M2 {get;set;} } public interface I2 : I1 { int I1.M1 { get => throw null; } int I1.M2 { set => throw null; } } class Test1 : I2 {} public interface I3 { int M1 {get;} int M2 {set;} int M3 {get;set;} int M4 {get;set;} } public interface I4 : I3 { int I3.M1 { get => throw null; set => throw null; } int I3.M2 { get => throw null; set => throw null; } int I3.M3 {get; set;} int I3.M4 {get; set;} = 0; } class Test2 : I4 {} "; ValidatePropertyImplementationInDerived_05(source1, // (10,12): error CS0551: Explicit interface implementation 'I2.I1.M1' is missing accessor 'I1.M1.set' // int I1.M1 Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M1").WithArguments("I2.I1.M1", "I1.M1.set").WithLocation(10, 12), // (14,12): error CS0551: Explicit interface implementation 'I2.I1.M2' is missing accessor 'I1.M2.get' // int I1.M2 Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M2").WithArguments("I2.I1.M2", "I1.M2.get").WithLocation(14, 12), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.M1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1").WithLocation(20, 15), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.M2' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M2").WithLocation(20, 15), // (36,9): error CS0550: 'I4.I3.M1.set' adds an accessor not found in interface member 'I3.M1' // set => throw null; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I4.I3.M1.set", "I3.M1").WithLocation(36, 9), // (40,9): error CS0550: 'I4.I3.M2.get' adds an accessor not found in interface member 'I3.M2' // get => throw null; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I4.I3.M2.get", "I3.M2").WithLocation(40, 9), // (43,16): error CS0501: 'I4.I3.M3.get' must declare a body because it is not marked abstract, extern, or partial // int I3.M3 {get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I4.I3.M3.get").WithLocation(43, 16), // (43,21): error CS0501: 'I4.I3.M3.set' must declare a body because it is not marked abstract, extern, or partial // int I3.M3 {get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I4.I3.M3.set").WithLocation(43, 21), // (44,12): error CS8053: Instance properties in interfaces cannot have initializers. // int I3.M4 {get; set;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "M4").WithArguments("I4.I3.M4").WithLocation(44, 12), // (44,16): error CS0501: 'I4.I3.M4.get' must declare a body because it is not marked abstract, extern, or partial // int I3.M4 {get; set;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I4.I3.M4.get").WithLocation(44, 16), // (44,21): error CS0501: 'I4.I3.M4.set' must declare a body because it is not marked abstract, extern, or partial // int I3.M4 {get; set;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I4.I3.M4.set").WithLocation(44, 21) ); } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void PropertyImplementationInDerived_11() { var source1 = @" public interface I2 { internal int M1 {get;} } public interface I4 { int M1 {get; internal set;} } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { _ = i2.M1; i4.M1 = i4.M1; } } "; var source2 = @" public interface I1 : I2, I5 { int I2.M1 => Getter(); private int Getter() { System.Console.WriteLine(""I2.M1""); return 1; } int I4.M1 { get { System.Console.WriteLine(""I4.M1""); return 1; } set => System.Console.WriteLine(""I4.M1.set""); } } public interface I3 : I1 { } "; ValidatePropertyImplementationInDerived_11(source1, source2, // (4,12): error CS0122: 'I2.M1' is inaccessible due to its protection level // int I2.M1 => Getter(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1").WithLocation(4, 12), // (11,12): error CS0122: 'I4.M1.set' is inaccessible due to its protection level // int I4.M1 Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I4.M1.set").WithLocation(11, 12) ); } private void ValidatePropertyImplementationInDerived_11(string source1, string source2, params DiagnosticDescription[] expected) { var source3 = @" class Test1 : I1 { static void Main() { TestHelper.Test(new Test1(), new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidatePropertyImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 I4.M1.set ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationInDerived_01); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidatePropertyImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 I4.M1.set ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationInDerived_01); } var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); foreach (var reference in new[] { compilation4.ToMetadataReference(), compilation4.EmitToImageReference() }) { var compilation5 = CreateCompilation(source2 + source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidatePropertyImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics(expected); if (expected.Length == 0) { CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 I4.M1.set ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationInDerived_01); } } } [Fact] [WorkItem(20083, "https://github.com/dotnet/roslyn/issues/20083")] public void PropertyImplementationInDerived_12() { var source1 = @" public interface I1 { int M1 { get => throw null; set => throw null;} } public interface I2 : I1 { int I1.M1 { get { System.Console.WriteLine(""I2.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I2.I1.M1.set""); } } } public interface I3 : I1 { int I1.M1 { get { System.Console.WriteLine(""I3.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I3.I1.M1.set""); } } } public interface I4 : I1 { int I1.M1 { get { System.Console.WriteLine(""I4.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I4.I1.M1.set""); } } } public interface I5 : I2, I3 { int I1.M1 { get { System.Console.WriteLine(""I5.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I5.I1.M1.set""); } } } public interface I6 : I1, I2, I3, I5 {} "; var source4 = @" class Test5 : I2 {} class Test6 : I1, I2, I3, I5 {} class Test7 : I6 { static void Main() { I1 i1 = new Test5(); i1.M1 = i1.M1; i1 = new Test6(); i1.M1 = i1.M1; i1 = new Test7(); i1.M1 = i1.M1; } } "; var source5 = @" class Test8 : I2, I3 { int I1.M1 { get { System.Console.WriteLine(""Test8.I1.M1.get""); return 1; } set { System.Console.WriteLine(""Test8.I1.M1.set""); } } static void Main() { I1 i1 = new Test8(); i1.M1 = i1.M1; i1 = new Test9(); i1.M1 = i1.M1; i1 = new Test10(); i1.M1 = i1.M1; i1 = new Test11(); i1.M1 = i1.M1; i1 = new Test12(); i1.M1 = i1.M1; } } class Test9 : I7 { int I1.M1 { get { System.Console.WriteLine(""Test9.I1.M1.get""); return 1; } set { System.Console.WriteLine(""Test9.I1.M1.set""); } } } class Test10 : I1, I2, I3, I4 { public int M1 { get { System.Console.WriteLine(""Test10.M1.get""); return 1; } set { System.Console.WriteLine(""Test10.M1.set""); } } } class Test11 : I1, I2, I3, I5, I4 { public int M1 { get { System.Console.WriteLine(""Test11.M1.get""); return 1; } set { System.Console.WriteLine(""Test11.M1.set""); } } } class Test12 : I8 { public virtual int M1 { get { System.Console.WriteLine(""Test12.M1.get""); return 1; } set { System.Console.WriteLine(""Test12.M1.set""); } } } "; ValidatePropertyImplementationInDerived_12(source1, source4, source5, new DiagnosticDescription[] { // (2,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(2, 15), // (5,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test2 : I7 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I7").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(5, 15), // (8,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test3 : I1, I2, I3, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(8, 15), // (11,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I5.I1.M1', nor 'I4.I1.M1' are most specific. // class Test4 : I1, I2, I3, I5, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.M1", "I5.I1.M1", "I4.I1.M1").WithLocation(11, 15), // (14,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I5.I1.M1', nor 'I4.I1.M1' are most specific. // class Test5 : I8 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I8").WithArguments("I1.M1", "I5.I1.M1", "I4.I1.M1").WithLocation(14, 15) } ); } private void ValidatePropertyImplementationInDerived_12(string source1, string source4, string source5, DiagnosticDescription[] expected1, DiagnosticDescription[] expected2 = null) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = GetSingleProperty(i1); var i2 = FindType(m, "I2"); var i2m1 = GetSingleProperty(i2); var i5 = FindType(m, "I5"); var i5m1 = GetSingleProperty(i5); var i6 = FindType(m, "I6"); ValidateExplicitImplementation(i2m1); ValidateExplicitImplementation(i5m1); VerifyFindImplementationForInterfaceMemberSame(i1m1, i1, i1m1); VerifyFindImplementationForInterfaceMemberSame(i2m1, i2, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, i5, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, i6, i1m1); } CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var refs1 = new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }; var source2 = @" public interface I7 : I2, I3 {} public interface I8 : I1, I2, I3, I5, I4 {} "; var source3 = @" class Test1 : I2, I3 {} class Test2 : I7 {} class Test3 : I1, I2, I3, I4 {} class Test4 : I1, I2, I3, I5, I4 {} class Test5 : I8 {} "; foreach (var ref1 in refs1) { var compilation2 = CreateCompilation(source2, new[] { ref1 }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // According to LDM decision captured at https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-06-14.md, // we do not require interfaces to have a most specific implementation of all members. Therefore, there are no // errors in this compilation. compilation2.VerifyDiagnostics(); Validate2(compilation2.SourceModule); void Validate2(ModuleSymbol m) { Validate1(m); var i1 = FindType(m, "I1"); var i1m1 = GetSingleProperty(i1); var i7 = FindType(m, "I7"); var i8 = FindType(m, "I8"); VerifyFindImplementationForInterfaceMemberSame(null, i7, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i8, i1m1); } CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); compilation2 = CreateCompilation(source2, new[] { ref1 }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); Validate2(compilation2.SourceModule); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); var refs2 = new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }; var compilation4 = CreateCompilation(source4, new[] { ref1 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); Validate4(compilation4.SourceModule); void Validate4(ModuleSymbol m) { Validate1(m); var i1 = FindType(m, "I1"); var i1m1 = GetSingleProperty(i1); var i2 = FindType(m, "I2"); var i2m1 = GetSingleProperty(i2); var i5 = FindType(m, "I5"); var i5m1 = GetSingleProperty(i5); var test5 = FindType(m, "Test5"); var test6 = FindType(m, "Test6"); var test7 = FindType(m, "Test7"); VerifyFindImplementationForInterfaceMemberSame(i2m1, test5, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, test6, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, test7, i1m1); } CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.I1.M1.get I2.I1.M1.set I5.I1.M1.get I5.I1.M1.set I5.I1.M1.get I5.I1.M1.set " , verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate4); foreach (var ref2 in refs2) { var compilation3 = CreateCompilation(source3, new[] { ref1, ref2 }, options: TestOptions.DebugDll.WithConcurrentBuild(false), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(ref1 is CompilationReference ? expected1 : expected2 ?? expected1); Validate3(compilation3.SourceModule); void Validate3(ModuleSymbol m) { Validate1(m); Validate2(m); var i1 = FindType(m, "I1"); var i1m1 = GetSingleProperty(i1); var test1 = FindType(m, "Test1"); var test2 = FindType(m, "Test2"); var test3 = FindType(m, "Test3"); var test4 = FindType(m, "Test4"); var test5 = FindType(m, "Test5"); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test2, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test3, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test4, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test5, i1m1); } var compilation5 = CreateCompilation(source5, new[] { ref1, ref2 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics(); Validate5(compilation5.SourceModule); void Validate5(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = GetSingleProperty(i1); var test8 = FindType(m, "Test8"); var test9 = FindType(m, "Test9"); var test10 = FindType(m, "Test10"); var test11 = FindType(m, "Test11"); var test12 = FindType(m, "Test12"); VerifyFindImplementationForInterfaceMemberSame(GetSingleProperty(test8), test8, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleProperty(test9), test9, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleProperty(test10), test10, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleProperty(test11), test11, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleProperty(test12), test12, i1m1); } CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"Test8.I1.M1.get Test8.I1.M1.set Test9.I1.M1.get Test9.I1.M1.set Test10.M1.get Test10.M1.set Test11.M1.get Test11.M1.set Test12.M1.get Test12.M1.set ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate5); } } } [Fact] public void PropertyImplementationInDerived_13() { var source1 = @" public interface I1 { int M1 {get;} } public interface I2 : I1 { int I1.M1 => throw null; } public interface I3 : I1 { int I1.M1 => throw null; } "; var source2 = @" class Test1 : I2, I3 { public long M1 => 1; } "; ValidatePropertyImplementationInDerived_13(source1, source2, new DiagnosticDescription[] { // (2,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(2, 15), // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.M1'. 'Test1.M1' cannot implement 'I1.M1' because it does not have the matching return type of 'int'. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test1", "I1.M1", "Test1.M1", "int").WithLocation(2, 15) } ); } private void ValidatePropertyImplementationInDerived_13(string source1, string source2, DiagnosticDescription[] expected1, DiagnosticDescription[] expected2 = null) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(expected1); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected2 ?? expected1); } [Fact] [WorkItem(20084, "https://github.com/dotnet/roslyn/issues/20084")] public void PropertyImplementationInDerived_14() { var source1 = @" public interface I1<T> { int M1 { get { System.Console.WriteLine(""I1.M1.get""); return 1; } set => System.Console.WriteLine(""I1.M1.set""); } } public interface I2<T> : I1<T> { int I1<T>.M1 { get { System.Console.WriteLine(""I2.I1.M1.get""); return 1; } set => System.Console.WriteLine(""I2.I1.M1.set""); } } public interface I3<T> : I1<T> {} "; var source2 = @" class Test1 : I1<int> { static void Main() { I1<int> i1Int = new Test1(); i1Int.M1 = i1Int.M1; I1<long> i1Long = new Test2(); i1Long.M1 = i1Long.M1; } } class Test2 : I2<long> {} "; ValidatePropertyImplementationInDerived_14(source1, source2); } private void ValidatePropertyImplementationInDerived_14(string source1, string source2) { var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = GetSingleProperty(i1); var i2 = FindType(m, "I2"); var i2m1 = GetSingleProperty(i2); var i2i1 = i2.InterfacesNoUseSiteDiagnostics().Single(); var i2i1m1 = GetSingleProperty(i2i1); var i3 = FindType(m, "I3"); var i3i1 = i3.InterfacesNoUseSiteDiagnostics().Single(); var i3i1m1 = GetSingleProperty(i3i1); VerifyFindImplementationForInterfaceMemberSame(i1m1, i1, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i2, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i2, i3i1m1); VerifyFindImplementationForInterfaceMemberSame(i2m1, i2, i2i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i3, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i3, i2i1m1); VerifyFindImplementationForInterfaceMemberEqual(i3i1m1, i3, i3i1m1); ValidateExplicitImplementation(i2m1); var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test1i1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)); var test1i1m1 = GetSingleProperty(i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32))); var test2 = m.GlobalNamespace.GetTypeMember("Test2"); var test2i1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)); var test2i1m1 = GetSingleProperty(i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64))); var test2i2 = i2.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)); var test2i2m1 = GetSingleProperty(i2.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64))); Assert.NotSame(test1i1, test1i1m1.ContainingType); Assert.NotSame(test2i1, test2i1m1.ContainingType); Assert.NotSame(test2i2, test2i2m1.ContainingType); VerifyFindImplementationForInterfaceMemberSame(null, test1i1, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test1i1m1, test1i1, test1i1m1); VerifyFindImplementationForInterfaceMemberEqual(test2i1m1, test2i1, test2i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test2i2, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test2i2m1, test2i2, test2i1m1); ValidateExplicitImplementation(test2i2m1); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test1i1m1, test1, test1i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test2, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test2i2m1, test2, test2i1m1); } CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1.get I1.M1.set I2.I1.M1.get I2.I1.M1.set ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1.get I1.M1.set I2.I1.M1.get I2.I1.M1.set ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1.get I1.M1.set I2.I1.M1.get I2.I1.M1.set ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); } [Fact] public void PropertyImplementationInDerived_15() { var source1 = @" public interface I2 { virtual int M1 {get => throw null; private set => throw null;} } public interface I4 { int M1 {set => throw null; private get => throw null;} } public interface I5 : I4 { } public interface I1 : I2, I5 { int I2.M1 { get { System.Console.WriteLine(""I2.M1""); return 1; } } int I4.M1 { set => System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source2 = @" class Test1 : I1 { static void Main() { I2 i2 = new Test1(); _ = i2.M1; I4 i4 = new Test1(); i4.M1 = 0; } } "; ValidatePropertyImplementationInDerived_01(source1, source2); } [Fact] public void PropertyImplementationInDerived_16() { var source1 = @" public interface I2 { int M1 {get; set;} } public interface I4 { int M1 {get; set;} } public interface I1 : I2, I4 { int I2.M1 { protected get => throw null; set => throw null; } protected int I4.M1 { get => throw null; set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (16,19): error CS0106: The modifier 'protected' is not valid for this item // protected get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("protected").WithLocation(16, 19), // (19,22): error CS0106: The modifier 'protected' is not valid for this item // protected int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected").WithLocation(19, 22) ); } [Fact] public void PropertyImplementationInDerived_17() { var source1 = @" public interface I2 { int M1 {get; set;} } public interface I4 { int M1 {get; set;} } public interface I1 : I2, I4 { int I2.M1 { get => throw null; protected internal set => throw null; } protected internal int I4.M1 { get => throw null; set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (17,28): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("protected internal").WithLocation(17, 28), // (19,31): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected internal").WithLocation(19, 31) ); } [Fact] public void PropertyImplementationInDerived_18() { var source1 = @" public interface I2 { int M1 {get; set;} } public interface I4 { int M1 {get; set;} } public interface I1 : I2, I4 { int I2.M1 { private protected get => throw null; set => throw null; } private protected int I4.M1 { get => throw null; set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (16,27): error CS0106: The modifier 'private protected' is not valid for this item // private protected get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("private protected").WithLocation(16, 27), // (19,30): error CS0106: The modifier 'private protected' is not valid for this item // private protected int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("private protected").WithLocation(19, 30) ); } [Fact] public void PropertyImplementationInDerived_19() { var source1 = @" #nullable enable public interface I1<T> { int M1 {get; set;} } public interface I2 : I1<string> { } public interface I3 : I2, I1<string?> { int I1<string>.M1 { get => throw null!; set => throw null!; } int I1<string?>.M1 { get => throw null!; set => throw null!; } } "; var source2 = @" #nullable enable class Test1 : I3 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (13,18): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'I3' with different nullability of reference types. // public interface I3 : I2, I1<string?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "I3").WithArguments("I1<string?>", "I3").WithLocation(13, 18), // (13,18): error CS8646: 'I1<string>.M1' is explicitly implemented more than once. // public interface I3 : I2, I1<string?> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "I3").WithArguments("I1<string>.M1").WithLocation(13, 18), // (13,18): error CS8646: 'I1<string?>.M1' is explicitly implemented more than once. // public interface I3 : I2, I1<string?> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "I3").WithArguments("I1<string?>.M1").WithLocation(13, 18), // (21,21): error CS0102: The type 'I3' already contains a definition for 'I1<System.String>.M1' // int I1<string?>.M1 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "M1").WithArguments("I3", "I1<System.String>.M1").WithLocation(21, 21) ); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7), // (4,15): error CS0535: 'Test1' does not implement interface member 'I1<string>.M1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1<string>.M1").WithLocation(4, 15), // (4,15): error CS0535: 'Test1' does not implement interface member 'I1<string?>.M1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1<string?>.M1").WithLocation(4, 15) ); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I3", "I2", "I1<System.String>", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[2].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); } [Fact] public void PropertyImplementationInDerived_20() { var source1 = @" public interface I2 { protected int M1 {get;} public static void Test(I2 i2) { _ = i2.M1; } } public interface I4 { int M1 {get; protected set;} public static void Test(I4 i4) { i4.M1 = i4.M1; } } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { I2.Test(i2); I4.Test(i4); } } "; var source2 = @" public interface I1 : I2, I5 { int I2.M1 => Getter(); private int Getter() { System.Console.WriteLine(""I2.M1""); return 1; } int I4.M1 { get { System.Console.WriteLine(""I4.M1""); return 1; } set => System.Console.WriteLine(""I4.M1.set""); } } public interface I3 : I1 { } "; ValidatePropertyImplementationInDerived_11(source1, source2); } [Fact] public void PropertyImplementationInDerived_21() { var source1 = @" public interface I2 { protected internal int M1 {get;} public static void Test(I2 i2) { _ = i2.M1; } } public interface I4 { int M1 {get; protected internal set;} public static void Test(I4 i4) { i4.M1 = i4.M1; } } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { I2.Test(i2); I4.Test(i4); } } "; var source2 = @" public interface I1 : I2, I5 { int I2.M1 => Getter(); private int Getter() { System.Console.WriteLine(""I2.M1""); return 1; } int I4.M1 { get { System.Console.WriteLine(""I4.M1""); return 1; } set => System.Console.WriteLine(""I4.M1.set""); } } public interface I3 : I1 { } "; ValidatePropertyImplementationInDerived_11(source1, source2); } [Fact] public void PropertyImplementationInDerived_22() { var source1 = @" public interface I2 { private protected int M1 {get;} public static void Test(I2 i2) { _ = i2.M1; } } public interface I4 { int M1 {get; private protected set;} public static void Test(I4 i4) { i4.M1 = i4.M1; } } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { I2.Test(i2); I4.Test(i4); } } "; var source2 = @" public interface I1 : I2, I5 { int I2.M1 => Getter(); private int Getter() { System.Console.WriteLine(""I2.M1""); return 1; } int I4.M1 { get { System.Console.WriteLine(""I4.M1""); return 1; } set => System.Console.WriteLine(""I4.M1.set""); } } public interface I3 : I1 { } "; ValidatePropertyImplementationInDerived_11(source1, source2, // (4,12): error CS0122: 'I2.M1' is inaccessible due to its protection level // int I2.M1 => Getter(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1").WithLocation(4, 12), // (11,12): error CS0122: 'I4.M1.set' is inaccessible due to its protection level // int I4.M1 Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I4.M1.set").WithLocation(11, 12) ); } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void EventImplementationInDerived_01() { var source1 = @" public interface I2 { event System.Action M1; } public interface I4 { event System.Action M1; } public interface I5 : I4 { } public interface I1 : I2, I5 { event System.Action I2.M1 { add { System.Console.WriteLine(""I2.M1.add""); } remove { System.Console.WriteLine(""I2.M1.remove""); } } event System.Action I4.M1 { add => System.Console.WriteLine(""I4.M1.add""); remove => System.Console.WriteLine(""I4.M1.remove""); } } public interface I3 : I1 { } "; var source2 = @" class Test1 : I1 { static void Main() { I2 i2 = new Test1(); i2.M1 += null; i2.M1 -= null; I4 i4 = new Test1(); i4.M1 += null; i4.M1 -= null; } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateEventImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); } private static void ValidateEventImplementationInDerived_01(ModuleSymbol m) { ValidateEventImplementationInDerived_01(m, i4M1IsAbstract: false); } private static void ValidateEventImplementationInDerived_01(ModuleSymbol m, bool i4M1IsAbstract) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var i1i2m1 = i1.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); var i1i4m1 = i1.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I4.")).Single(); var i2 = i1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I2").Single(); var i2m1 = i2.GetMembers().OfType<EventSymbol>().Single(); var i4 = i1.AllInterfacesNoUseSiteDiagnostics.Where(i => i.Name == "I4").Single(); var i4m1 = i4.GetMembers().OfType<EventSymbol>().Single(); var i3 = i1.ContainingNamespace.GetTypeMember("I3"); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); ValidateExplicitImplementation(i1i2m1); ValidateExplicitImplementation(i1i4m1, i4M1IsAbstract); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1i2m1); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1i4m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, test1, i2m1); VerifyFindImplementationForInterfaceMemberSame(i4M1IsAbstract ? null : i1i4m1, test1, i4m1); VerifyFindImplementationForInterfaceMemberSame(null, i1, i1i2m1); VerifyFindImplementationForInterfaceMemberSame(null, i1, i1i4m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, i1, i2m1); VerifyFindImplementationForInterfaceMemberSame(i4M1IsAbstract ? null : i1i4m1, i1, i4m1); VerifyFindImplementationForInterfaceMemberSame(null, i2, i2m1); VerifyFindImplementationForInterfaceMemberSame(null, i4, i4m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, i3, i2m1); VerifyFindImplementationForInterfaceMemberSame(i4M1IsAbstract ? null : i1i4m1, i3, i4m1); } private static void VerifyFindImplementationForInterfaceMemberSame(EventSymbol expected, NamedTypeSymbol implementingType, EventSymbol interfaceEvent) { Assert.Same(expected, implementingType.FindImplementationForInterfaceMember(interfaceEvent)); ValidateAccessor(expected?.AddMethod, interfaceEvent.AddMethod); ValidateAccessor(expected?.RemoveMethod, interfaceEvent.RemoveMethod); void ValidateAccessor(MethodSymbol accessor, MethodSymbol interfaceAccessor) { if ((object)interfaceAccessor != null) { Assert.Same(accessor, implementingType.FindImplementationForInterfaceMember(interfaceAccessor)); } else { Assert.Null(accessor); } } } private static void VerifyFindImplementationForInterfaceMemberEqual(EventSymbol expected, NamedTypeSymbol implementingType, EventSymbol interfaceEvent) { Assert.Equal(expected, implementingType.FindImplementationForInterfaceMember(interfaceEvent)); ValidateAccessor(expected?.AddMethod, interfaceEvent.AddMethod); ValidateAccessor(expected?.RemoveMethod, interfaceEvent.RemoveMethod); void ValidateAccessor(MethodSymbol accessor, MethodSymbol interfaceAccessor) { if ((object)interfaceAccessor != null) { Assert.Equal(accessor, implementingType.FindImplementationForInterfaceMember(interfaceAccessor)); } else { Assert.Null(accessor); } } } private static void ValidateExplicitImplementation(EventSymbol m1, bool isAbstract = false) { Assert.Equal(isAbstract, m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.Equal(isAbstract, m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); ValidateAccessor(m1.AddMethod, isAbstract); ValidateAccessor(m1.RemoveMethod, isAbstract); static void ValidateAccessor(MethodSymbol accessor, bool isAbstract) { if ((object)accessor != null) { ValidateExplicitImplementation(accessor, isAbstract); } } } [Fact] public void EventImplementationInDerived_02() { var source1 = @" public interface I2 { event System.Action M1; } public interface I4 { event System.Action M1; } public interface I1 : I2, I4 { event System.Action I2.M1 { add => throw null; remove => throw null; } event System.Action I4.M1 { add => throw null; remove => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (16,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // add => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(16, 9), // (17,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // remove => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(17, 9), // (22,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // add => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(22, 9), // (23,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // remove => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(23, 9) ); ValidateEventImplementationInDerived_01(compilation1.SourceModule); var source2 = @" public interface I3 : I1 { } class Test1 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (6,15): error CS8506: 'I1.I2.M1.remove' cannot implement interface member 'I2.M1.remove' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1.remove", "I2.M1.remove", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15), // (6,15): error CS8506: 'I1.I2.M1.add' cannot implement interface member 'I2.M1.add' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1.add", "I2.M1.add", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15), // (6,15): error CS8506: 'I1.I4.M1.remove' cannot implement interface member 'I4.M1.remove' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1.remove", "I4.M1.remove", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15), // (6,15): error CS8506: 'I1.I4.M1.add' cannot implement interface member 'I4.M1.add' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1.add", "I4.M1.add", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15) ); ValidateEventImplementationInDerived_01(compilation2.SourceModule); } [Fact] public void EventImplementationInDerived_03() { var source1 = @" public interface I2 { event System.Action M1; } public interface I4 { event System.Action M1; } public interface I1 : I2, I4 { event System.Action I2.M1 { add => throw null; remove => throw null; } event System.Action I4.M1 { add => throw null; remove => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (16,9): error CS8501: Target runtime doesn't support default interface implementation. // add => throw null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(16, 9), // (17,9): error CS8501: Target runtime doesn't support default interface implementation. // remove => throw null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(17, 9), // (22,9): error CS8501: Target runtime doesn't support default interface implementation. // add => throw null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(22, 9), // (23,9): error CS8501: Target runtime doesn't support default interface implementation. // remove => throw null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(23, 9) ); ValidateEventImplementationInDerived_01(compilation1.SourceModule); var source2 = @" public interface I3 : I1 { } class Test1 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (6,15): error CS8502: 'I1.I2.M1.remove' cannot implement interface member 'I2.M1.remove' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1.remove", "I2.M1.remove", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I2.M1.add' cannot implement interface member 'I2.M1.add' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1.add", "I2.M1.add", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I4.M1.remove' cannot implement interface member 'I4.M1.remove' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1.remove", "I4.M1.remove", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I4.M1.add' cannot implement interface member 'I4.M1.add' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1.add", "I4.M1.add", "Test1").WithLocation(6, 15) ); } [Fact] public void EventImplementationInDerived_04() { var source1 = @" public interface I2 { event System.Action M1; } public interface I4 { event System.Action M1; } public interface I1 : I2, I4 { event System.Action I2.M1 { add; remove; } event System.Action I4.M1 { add; remove {} } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (16,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(16, 12), // (17,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(17, 15), // (21,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(21, 12) ); ValidateEventImplementationInDerived_01(compilation1.SourceModule); } [Fact] public void EventImplementationInDerived_05() { var source1 = @" public interface I2 { event System.Action M1; } public interface I1 { event System.Action I2.M1 { add => throw null; remove => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (9,25): error CS0540: 'I1.I2.M1': containing type does not implement interface 'I2' // event System.Action I2.M1 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.I2.M1", "I2").WithLocation(9, 25) ); } [Fact] public void EventImplementationInDerived_06() { var source1 = @" public interface I2 { event System.Action M1; } public interface I4 { event System.Action M1; } public interface I1 : I2, I4 { public static event System.Action I2.M1 { add => throw null; remove => throw null; } internal virtual event System.Action I4.M1 { add => throw null; remove => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,42): error CS0106: The modifier 'static' is not valid for this item // public static event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("static").WithLocation(14, 42), // (14,42): error CS0106: The modifier 'public' is not valid for this item // public static event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("public").WithLocation(14, 42), // (19,45): error CS0106: The modifier 'internal' is not valid for this item // internal virtual event System.Action I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("internal").WithLocation(19, 45), // (19,45): error CS0106: The modifier 'virtual' is not valid for this item // internal virtual event System.Action I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("virtual").WithLocation(19, 45) ); ValidateEventImplementationInDerived_01(compilation1.SourceModule); } [Fact] public void EventImplementationInDerived_07() { var source1 = @" public interface I2 { event System.Action M1; } public interface I4 { event System.Action M1; } public interface I1 : I2, I4 { private sealed event System.Action I2.M1 { add => throw null; remove => throw null; } protected abstract event System.Action I4.M1 { add => throw null; remove => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,43): error CS0106: The modifier 'sealed' is not valid for this item // private sealed event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("sealed").WithLocation(14, 43), // (14,43): error CS0106: The modifier 'private' is not valid for this item // private sealed event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("private").WithLocation(14, 43), // (19,47): error CS0106: The modifier 'protected' is not valid for this item // protected abstract event System.Action I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected").WithLocation(19, 47), // (20,5): error CS8712: 'I1.I4.M1': abstract event cannot use event accessor syntax // { Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.I4.M1").WithLocation(20, 5), // (30,15): error CS0535: 'Test1' does not implement interface member 'I4.M1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I4.M1").WithLocation(30, 15) ); ValidateEventImplementationInDerived_01(compilation1.SourceModule, i4M1IsAbstract: true); } [Fact] public void EventImplementationInDerived_08() { var source1 = @" public interface I2 { event System.Action M1; } public interface I4 { event System.Action M1; } public interface I1 : I2, I4 { private protected extern event System.Action I2.M1 { add => throw null; remove => throw null; } internal protected override event System.Action I4.M1 { add => throw null; remove => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,53): error CS0106: The modifier 'private protected' is not valid for this item // private protected extern event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("private protected").WithLocation(14, 53), // (14,53): error CS0106: The modifier 'extern' is not valid for this item // private protected extern event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("extern").WithLocation(14, 53), // (19,56): error CS0106: The modifier 'protected internal' is not valid for this item // internal protected override event System.Action I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected internal").WithLocation(19, 56), // (19,56): error CS0106: The modifier 'override' is not valid for this item // internal protected override event System.Action I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("override").WithLocation(19, 56) ); ValidateEventImplementationInDerived_01(compilation1.SourceModule); } [Fact] public void EventImplementationInDerived_10() { var source1 = @" public interface I1 { event System.Action M1; event System.Action M2; } public interface I2 : I1 { event System.Action I1.M1 { add => throw null; } event System.Action I1.M2 { remove => throw null; } } class Test1 : I2 {} public interface I3 { event System.Action M1; } public interface I4 : I3 { event System.Action I3.M1; } class Test2 : I4 {} public interface I5 : I3 { event System.Action I3.M1 } class Test3 : I5 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (30,28): error CS0071: An explicit interface implementation of an event must use event accessor syntax // event System.Action I3.M1; Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "M1").WithLocation(30, 28), // (10,28): error CS0065: 'I2.I1.M1': event property must have both add and remove accessors // event System.Action I1.M1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M1").WithArguments("I2.I1.M1").WithLocation(10, 28), // (14,28): error CS0065: 'I2.I1.M2': event property must have both add and remove accessors // event System.Action I1.M2 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M2").WithArguments("I2.I1.M2").WithLocation(14, 28), // (33,15): error CS0535: 'Test2' does not implement interface member 'I3.M1' // class Test2 : I4 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test2", "I3.M1").WithLocation(33, 15), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.M1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1").WithLocation(20, 15), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.M2' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M2").WithLocation(20, 15), // (38,27): error CS0071: An explicit interface implementation of an event must use event accessor syntax // event System.Action I3.M1 Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, ".").WithLocation(38, 27), // (41,15): error CS0535: 'Test3' does not implement interface member 'I3.M1' // class Test3 : I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I5").WithArguments("Test3", "I3.M1").WithLocation(41, 15) ); } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void EventImplementationInDerived_11() { var source1 = @" public interface I2 { internal event System.Action M1; } public interface I4 { event System.Action M1; } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { i2.M1 += null; i2.M1 -= null; i4.M1 += null; i4.M1 -= null; } } "; var source2 = @" public interface I1 : I2, I5 { event System.Action I2.M1 { add { System.Console.WriteLine(""I2.M1.add""); } remove => System.Console.WriteLine(""I2.M1.remove""); } event System.Action I4.M1 { add { System.Console.WriteLine(""I4.M1.add""); } remove => System.Console.WriteLine(""I4.M1.remove""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { TestHelper.Test(new Test1(), new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateEventImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); var compilation2 = CreateCompilation(source3, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); var compilation3 = CreateCompilation(source3, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); var compilation5 = CreateCompilation(source2 + source3, new[] { compilation4.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics( // (4,28): error CS0122: 'I2.M1' is inaccessible due to its protection level // event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1").WithLocation(4, 28) ); var compilation6 = CreateCompilation(source2 + source3, new[] { compilation4.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation6.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation6.SourceModule); compilation6.VerifyDiagnostics( // (4,28): error CS0122: 'I2.M1' is inaccessible due to its protection level // event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1").WithLocation(4, 28) ); } [Fact] [WorkItem(20083, "https://github.com/dotnet/roslyn/issues/20083")] public void EventImplementationInDerived_12() { var source1 = @" public interface I1 { event System.Action M1 { add => throw null; remove => throw null;} } public interface I2 : I1 { event System.Action I1.M1 { add { System.Console.WriteLine(""I2.I1.M1.add""); } remove { System.Console.WriteLine(""I2.I1.M1.remove""); } } } public interface I3 : I1 { event System.Action I1.M1 { add { System.Console.WriteLine(""I3.I1.M1.add""); } remove { System.Console.WriteLine(""I3.I1.M1.remove""); } } } public interface I4 : I1 { event System.Action I1.M1 { add { System.Console.WriteLine(""I4.I1.M1.add""); } remove { System.Console.WriteLine(""I4.I1.M1.remove""); } } } public interface I5 : I2, I3 { event System.Action I1.M1 { add { System.Console.WriteLine(""I5.I1.M1.add""); } remove { System.Console.WriteLine(""I5.I1.M1.remove""); } } } public interface I6 : I1, I2, I3, I5 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = GetSingleEvent(i1); var i2 = FindType(m, "I2"); var i2m1 = GetSingleEvent(i2); var i5 = FindType(m, "I5"); var i5m1 = GetSingleEvent(i5); var i6 = FindType(m, "I6"); ValidateExplicitImplementation(i2m1); ValidateExplicitImplementation(i5m1); VerifyFindImplementationForInterfaceMemberSame(i1m1, i1, i1m1); VerifyFindImplementationForInterfaceMemberSame(i2m1, i2, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, i5, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, i6, i1m1); } CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var refs1 = new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }; var source2 = @" public interface I7 : I2, I3 {} public interface I8 : I1, I2, I3, I5, I4 {} "; var source3 = @" class Test1 : I2, I3 {} class Test2 : I7 {} class Test3 : I1, I2, I3, I4 {} class Test4 : I1, I2, I3, I5, I4 {} class Test5 : I8 {} "; var source4 = @" class Test5 : I2 {} class Test6 : I1, I2, I3, I5 {} class Test7 : I6 { static void Main() { I1 i1 = new Test5(); i1.M1 += null; i1.M1 -= null; i1 = new Test6(); i1.M1 += null; i1.M1 -= null; i1 = new Test7(); i1.M1 += null; i1.M1 -= null; } } "; var source5 = @" class Test8 : I2, I3 { event System.Action I1.M1 { add { System.Console.WriteLine(""Test8.I1.M1.add""); } remove { System.Console.WriteLine(""Test8.I1.M1.remove""); } } static void Main() { I1 i1 = new Test8(); i1.M1 += null; i1.M1 -= null; i1 = new Test9(); i1.M1 += null; i1.M1 -= null; i1 = new Test10(); i1.M1 += null; i1.M1 -= null; i1 = new Test11(); i1.M1 += null; i1.M1 -= null; i1 = new Test12(); i1.M1 += null; i1.M1 -= null; } } class Test9 : I7 { event System.Action I1.M1 { add { System.Console.WriteLine(""Test9.I1.M1.add""); } remove { System.Console.WriteLine(""Test9.I1.M1.remove""); } } } class Test10 : I1, I2, I3, I4 { public event System.Action M1 { add { System.Console.WriteLine(""Test10.M1.add""); } remove { System.Console.WriteLine(""Test10.M1.remove""); } } } class Test11 : I1, I2, I3, I5, I4 { public event System.Action M1 { add { System.Console.WriteLine(""Test11.M1.add""); } remove { System.Console.WriteLine(""Test11.M1.remove""); } } } class Test12 : I8 { public virtual event System.Action M1 { add { System.Console.WriteLine(""Test12.M1.add""); } remove { System.Console.WriteLine(""Test12.M1.remove""); } } } "; foreach (var ref1 in refs1) { var compilation2 = CreateCompilation(source2, new[] { ref1 }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // According to LDM decision captured at https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-06-14.md, // we do not require interfaces to have a most specific implementation of all members. Therefore, there are no // errors in this compilation. compilation2.VerifyDiagnostics(); Validate2(compilation2.SourceModule); void Validate2(ModuleSymbol m) { Validate1(m); var i1 = FindType(m, "I1"); var i1m1 = GetSingleEvent(i1); var i7 = FindType(m, "I7"); var i8 = FindType(m, "I8"); VerifyFindImplementationForInterfaceMemberSame(null, i7, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i8, i1m1); } CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); compilation2 = CreateCompilation(source2, new[] { ref1 }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); Validate2(compilation2.SourceModule); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); var refs2 = new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }; var compilation4 = CreateCompilation(source4, new[] { ref1 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); Validate4(compilation4.SourceModule); void Validate4(ModuleSymbol m) { Validate1(m); var i1 = FindType(m, "I1"); var i1m1 = GetSingleEvent(i1); var i2 = FindType(m, "I2"); var i2m1 = GetSingleEvent(i2); var i5 = FindType(m, "I5"); var i5m1 = GetSingleEvent(i5); var test5 = FindType(m, "Test5"); var test6 = FindType(m, "Test6"); var test7 = FindType(m, "Test7"); VerifyFindImplementationForInterfaceMemberSame(i2m1, test5, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, test6, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, test7, i1m1); } CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.I1.M1.add I2.I1.M1.remove I5.I1.M1.add I5.I1.M1.remove I5.I1.M1.add I5.I1.M1.remove " , verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate4); foreach (var ref2 in refs2) { var compilation3 = CreateCompilation(source3, new[] { ref1, ref2 }, options: TestOptions.DebugDll.WithConcurrentBuild(false), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(2, 15), // (5,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test2 : I7 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I7").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(5, 15), // (8,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test3 : I1, I2, I3, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(8, 15), // (11,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I5.I1.M1', nor 'I4.I1.M1' are most specific. // class Test4 : I1, I2, I3, I5, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.M1", "I5.I1.M1", "I4.I1.M1").WithLocation(11, 15), // (14,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I5.I1.M1', nor 'I4.I1.M1' are most specific. // class Test5 : I8 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I8").WithArguments("I1.M1", "I5.I1.M1", "I4.I1.M1").WithLocation(14, 15) ); Validate3(compilation3.SourceModule); void Validate3(ModuleSymbol m) { Validate1(m); Validate2(m); var i1 = FindType(m, "I1"); var i1m1 = GetSingleEvent(i1); var test1 = FindType(m, "Test1"); var test2 = FindType(m, "Test2"); var test3 = FindType(m, "Test3"); var test4 = FindType(m, "Test4"); var test5 = FindType(m, "Test5"); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test2, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test3, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test4, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test5, i1m1); } var compilation5 = CreateCompilation(source5, new[] { ref1, ref2 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics(); Validate5(compilation5.SourceModule); void Validate5(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = GetSingleEvent(i1); var test8 = FindType(m, "Test8"); var test9 = FindType(m, "Test9"); var test10 = FindType(m, "Test10"); var test11 = FindType(m, "Test11"); var test12 = FindType(m, "Test12"); VerifyFindImplementationForInterfaceMemberSame(GetSingleEvent(test8), test8, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleEvent(test9), test9, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleEvent(test10), test10, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleEvent(test11), test11, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleEvent(test12), test12, i1m1); } CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"Test8.I1.M1.add Test8.I1.M1.remove Test9.I1.M1.add Test9.I1.M1.remove Test10.M1.add Test10.M1.remove Test11.M1.add Test11.M1.remove Test12.M1.add Test12.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate5); } } } [Fact] public void EventImplementationInDerived_13() { var source1 = @" public interface I1 { event System.Action M1; } public interface I2 : I1 { event System.Action I1.M1 { add => throw null; remove => throw null;} } public interface I3 : I1 { event System.Action I1.M1 { add => throw null; remove => throw null;} } "; var source2 = @" class Test1 : I2, I3 { public event System.Action<object> M1 { add => throw null; remove => throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (2,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(2, 15), // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.M1'. 'Test1.M1' cannot implement 'I1.M1' because it does not have the matching return type of 'Action'. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test1", "I1.M1", "Test1.M1", "System.Action").WithLocation(2, 15) ); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(2, 15), // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.M1'. 'Test1.M1' cannot implement 'I1.M1' because it does not have the matching return type of 'Action'. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test1", "I1.M1", "Test1.M1", "System.Action").WithLocation(2, 15) ); } [Fact] [WorkItem(20084, "https://github.com/dotnet/roslyn/issues/20084")] public void EventImplementationInDerived_14() { var source1 = @" public interface I1<T> { event System.Action M1 { add { System.Console.WriteLine(""I1.M1.add""); } remove => System.Console.WriteLine(""I1.M1.remove""); } } public interface I2<T> : I1<T> { event System.Action I1<T>.M1 { add { System.Console.WriteLine(""I2.I1.M1.add""); } remove => System.Console.WriteLine(""I2.I1.M1.remove""); } } public interface I3<T> : I1<T> {} "; var source2 = @" class Test1 : I1<int> { static void Main() { I1<int> i1Int = new Test1(); i1Int.M1 += null; i1Int.M1 -= null; I1<long> i1Long = new Test2(); i1Long.M1 += null; i1Long.M1 -= null; } } class Test2 : I2<long> {} "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = GetSingleEvent(i1); var i2 = FindType(m, "I2"); var i2m1 = GetSingleEvent(i2); var i2i1 = i2.InterfacesNoUseSiteDiagnostics().Single(); var i2i1m1 = GetSingleEvent(i2i1); var i3 = FindType(m, "I3"); var i3i1 = i3.InterfacesNoUseSiteDiagnostics().Single(); var i3i1m1 = GetSingleEvent(i3i1); VerifyFindImplementationForInterfaceMemberSame(i1m1, i1, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i2, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i2, i3i1m1); VerifyFindImplementationForInterfaceMemberSame(i2m1, i2, i2i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i3, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i3, i2i1m1); VerifyFindImplementationForInterfaceMemberEqual(i3i1m1, i3, i3i1m1); ValidateExplicitImplementation(i2m1); var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test1i1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)); var test1i1m1 = GetSingleEvent(i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32))); var test2 = m.GlobalNamespace.GetTypeMember("Test2"); var test2i1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)); var test2i1m1 = GetSingleEvent(i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64))); var test2i2 = i2.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)); var test2i2m1 = GetSingleEvent(i2.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64))); Assert.NotSame(test1i1, test1i1m1.ContainingType); Assert.NotSame(test2i1, test2i1m1.ContainingType); Assert.NotSame(test2i2, test2i2m1.ContainingType); VerifyFindImplementationForInterfaceMemberSame(null, test1i1, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test1i1m1, test1i1, test1i1m1); VerifyFindImplementationForInterfaceMemberEqual(test2i1m1, test2i1, test2i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test2i2, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test2i2m1, test2i2, test2i1m1); ValidateExplicitImplementation(test2i2m1); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test1i1m1, test1, test1i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test2, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test2i2m1, test2, test2i1m1); } CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1.add I1.M1.remove I2.I1.M1.add I2.I1.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1.add I1.M1.remove I2.I1.M1.add I2.I1.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1.add I1.M1.remove I2.I1.M1.add I2.I1.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); } [Fact] public void EventImplementationInDerived_15() { var source1 = @" public interface I2 { protected event System.Action M1; public static void Test(I2 i2) { i2.M1 += null; i2.M1 -= null; } } public interface I4 { event System.Action M1; } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { I2.Test(i2); i4.M1 += null; i4.M1 -= null; } } "; var source2 = @" public interface I1 : I2, I5 { event System.Action I2.M1 { add { System.Console.WriteLine(""I2.M1.add""); } remove => System.Console.WriteLine(""I2.M1.remove""); } event System.Action I4.M1 { add { System.Console.WriteLine(""I4.M1.add""); } remove => System.Console.WriteLine(""I4.M1.remove""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { TestHelper.Test(new Test1(), new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateEventImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); } var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); foreach (var reference in new[] { compilation4.ToMetadataReference(), compilation4.EmitToImageReference() }) { var compilation5 = CreateCompilation(source2 + source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics(); CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); } } [Fact] public void EventImplementationInDerived_16() { var source1 = @" public interface I2 { protected internal event System.Action M1; public static void Test(I2 i2) { i2.M1 += null; i2.M1 -= null; } } public interface I4 { event System.Action M1; } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { I2.Test(i2); i4.M1 += null; i4.M1 -= null; } } "; var source2 = @" public interface I1 : I2, I5 { event System.Action I2.M1 { add { System.Console.WriteLine(""I2.M1.add""); } remove => System.Console.WriteLine(""I2.M1.remove""); } event System.Action I4.M1 { add { System.Console.WriteLine(""I4.M1.add""); } remove => System.Console.WriteLine(""I4.M1.remove""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { TestHelper.Test(new Test1(), new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateEventImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); } var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); foreach (var reference in new[] { compilation4.ToMetadataReference(), compilation4.EmitToImageReference() }) { var compilation5 = CreateCompilation(source2 + source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics(); CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); } } [Fact] public void EventImplementationInDerived_17() { var source1 = @" public interface I2 { private protected event System.Action M1; public static void Test(I2 i2) { i2.M1 += null; i2.M1 -= null; } } public interface I4 { event System.Action M1; } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { I2.Test(i2); i4.M1 += null; i4.M1 -= null; } } "; var source2 = @" public interface I1 : I2, I5 { event System.Action I2.M1 { add { System.Console.WriteLine(""I2.M1.add""); } remove => System.Console.WriteLine(""I2.M1.remove""); } event System.Action I4.M1 { add { System.Console.WriteLine(""I4.M1.add""); } remove => System.Console.WriteLine(""I4.M1.remove""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { TestHelper.Test(new Test1(), new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateEventImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); } var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); foreach (var reference in new[] { compilation4.ToMetadataReference(), compilation4.EmitToImageReference() }) { var compilation5 = CreateCompilation(source2 + source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics( // (4,28): error CS0122: 'I2.M1' is inaccessible due to its protection level // event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1").WithLocation(4, 28) ); } } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void IndexerImplementationInDerived_01() { var source1 = @" public interface I2 { int this[int x] {get;} } public interface I4 { int this[int x] {set;} } public interface I5 : I4 { } public interface I1 : I2, I5 { int I2.this[int x] { get { System.Console.WriteLine(""I2.M1""); return 1; } } int I4.this[int x] { set => System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source2 = @" class Test1 : I1 { static void Main() { I2 i2 = new Test1(); _ = i2[0]; I4 i4 = new Test1(); i4[0] = 0; } } "; ValidatePropertyImplementationInDerived_01(source1, source2); } [Fact] public void IndexerImplementationInDerived_02() { var source1 = @" public interface I2 { int this[int x] {get;} } public interface I4 { int this[int x] {set;} } public interface I1 : I2, I4 { int I2.this[int x] => Getter(); private int Getter() { System.Console.WriteLine(""I2.M1""); return 1; } int I4.this[int x] { set { System.Console.WriteLine(""I2.M1""); } } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_02(source1, new DiagnosticDescription[] { // (16,17): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // private int Getter() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "Getter").WithArguments("default interface implementation", "8.0").WithLocation(16, 17), // (14,27): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int I2.this[int x] => Getter(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "Getter()").WithArguments("default interface implementation", "8.0").WithLocation(14, 27), // (24,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // set Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(24, 9) }, // (6,15): error CS8506: 'I1.I2.this[int].get' cannot implement interface member 'I2.this[int].get' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.this[int].get", "I2.this[int].get", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15), // (6,15): error CS8506: 'I1.I4.this[int].set' cannot implement interface member 'I4.this[int].set' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.this[int].set", "I4.this[int].set", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15) ); } [Fact] public void IndexerImplementationInDerived_03() { var source1 = @" public interface I2 { int this[int x] {get; set;} } public interface I4 { int this[int x] {set;} } public interface I1 : I2, I4 { int I2.this[int x] { get { System.Console.WriteLine(""I2.M1""); return 1; } set { System.Console.WriteLine(""I2.M1""); } } int I4.this[int x] { set { System.Console.WriteLine(""I2.M1""); } } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_03(source1, new DiagnosticDescription[] { // (16,9): error CS8501: Target runtime doesn't support default interface implementation. // get Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(16, 9), // (21,9): error CS8501: Target runtime doesn't support default interface implementation. // set Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(21, 9), // (29,9): error CS8501: Target runtime doesn't support default interface implementation. // set Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(29, 9) }, // (6,15): error CS8502: 'I1.I2.this[int].set' cannot implement interface member 'I2.this[int].set' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.this[int].set", "I2.this[int].set", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I2.this[int].get' cannot implement interface member 'I2.this[int].get' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.this[int].get", "I2.this[int].get", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I4.this[int].set' cannot implement interface member 'I4.this[int].set' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.this[int].set", "I4.this[int].set", "Test1").WithLocation(6, 15) ); } [Fact] public void IndexerImplementationInDerived_04() { var source1 = @" public interface I2 { int this[int x] {get;} } public interface I4 { int this[int x] {set;} } public interface I1 : I2, I4 { int I2.this[int x] {get;} int I4.this[int x] {set;} } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (14,25): error CS0501: 'I1.I2.this[int].get' must declare a body because it is not marked abstract, extern, or partial // int I2.this[int x] {get;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.I2.this[int].get").WithLocation(14, 25), // (15,25): error CS0501: 'I1.I4.this[int].set' must declare a body because it is not marked abstract, extern, or partial // int I4.this[int x] {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.I4.this[int].set").WithLocation(15, 25) ); } [Fact] public void IndexerImplementationInDerived_05() { var source1 = @" public interface I2 { int this[int x] {get;} } public interface I4 { int this[int x] {set;} } public interface I1 { int I2.this[int x] {get => throw null;} int I4.this[int x] {set => throw null;} } "; ValidatePropertyImplementationInDerived_05(source1, // (14,9): error CS0540: 'I1.I2.this[int]': containing type does not implement interface 'I2' // int I2.this[int x] {get => throw null;} Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.I2.this[int]", "I2").WithLocation(14, 9), // (15,9): error CS0540: 'I1.I4.this[int]': containing type does not implement interface 'I4' // int I4.this[int x] {set => throw null;} Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I4").WithArguments("I1.I4.this[int]", "I4").WithLocation(15, 9) ); } [Fact] public void IndexerImplementationInDerived_06() { var source1 = @" public interface I2 { int this[int x] {get; set;} } public interface I4 { int this[int x] {get; set;} } public interface I1 : I2, I4 { public static int I2.this[int x] { internal get => throw null; set => throw null; } internal virtual int I4.this[int x] { public get => throw null; set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (14,26): error CS0106: The modifier 'static' is not valid for this item // public static int I2.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(14, 26), // (14,26): error CS0106: The modifier 'public' is not valid for this item // public static int I2.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("public").WithLocation(14, 26), // (16,18): error CS0106: The modifier 'internal' is not valid for this item // internal get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("internal").WithLocation(16, 18), // (19,29): error CS0106: The modifier 'internal' is not valid for this item // internal virtual int I4.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("internal").WithLocation(19, 29), // (19,29): error CS0106: The modifier 'virtual' is not valid for this item // internal virtual int I4.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("virtual").WithLocation(19, 29), // (21,16): error CS0106: The modifier 'public' is not valid for this item // public get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("public").WithLocation(21, 16) ); } [Fact] public void IndexerImplementationInDerived_07() { var source1 = @" public interface I2 { int this[int x] {get; set;} } public interface I4 { int this[int x] {get; set;} } public interface I1 : I2, I4 { private sealed int I2.this[int x] { private get => throw null; set => throw null; } protected abstract int I4.this[int x] { get => throw null; protected set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, i4M1IsAbstract: true, // (14,27): error CS0106: The modifier 'sealed' is not valid for this item // private sealed int I2.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("sealed").WithLocation(14, 27), // (14,27): error CS0106: The modifier 'private' is not valid for this item // private sealed int I2.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("private").WithLocation(14, 27), // (16,17): error CS0106: The modifier 'private' is not valid for this item // private get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("private").WithLocation(16, 17), // (19,31): error CS0106: The modifier 'protected' is not valid for this item // protected abstract int I4.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("protected").WithLocation(19, 31), // (21,9): error CS0500: 'I1.I4.this[int].get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.I4.this[int].get").WithLocation(21, 9), // (22,19): error CS0106: The modifier 'protected' is not valid for this item // protected set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("protected").WithLocation(22, 19), // (22,19): error CS0500: 'I1.I4.this[int].set' cannot declare a body because it is marked abstract // protected set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I1.I4.this[int].set").WithLocation(22, 19), // (30,15): error CS0535: 'Test1' does not implement interface member 'I4.this[int]' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I4.this[int]").WithLocation(30, 15) ); } [Fact] public void IndexerImplementationInDerived_08() { var source1 = @" public interface I2 { int this[int x] {get; set;} } public interface I4 { int this[int x] {get; set;} } public interface I1 : I2, I4 { private protected int I2.this[int x] { private protected get => throw null; set => throw null; } internal protected override int I4.this[int x] { get => throw null; internal protected set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (14,30): error CS0106: The modifier 'private protected' is not valid for this item // private protected int I2.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("private protected").WithLocation(14, 30), // (16,27): error CS0106: The modifier 'private protected' is not valid for this item // private protected get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("private protected").WithLocation(16, 27), // (19,40): error CS0106: The modifier 'protected internal' is not valid for this item // internal protected override int I4.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("protected internal").WithLocation(19, 40), // (19,40): error CS0106: The modifier 'override' is not valid for this item // internal protected override int I4.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("override").WithLocation(19, 40), // (22,28): error CS0106: The modifier 'protected internal' is not valid for this item // internal protected set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("protected internal").WithLocation(22, 28) ); } [Fact] public void IndexerImplementationInDerived_09() { var source1 = @" public interface I2 { int this[int x] {get;} } public interface I1 : I2 { extern int I2.this[int x] {get;} } public interface I3 : I1 { } class Test1 : I1 {} "; var source2 = @" public interface I2 { int this[int x] {set;} } public interface I1 : I2 { extern int I2.this[int x] { set {}} } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_09(source1, source2, new DiagnosticDescription[] { // (9,32): warning CS0626: Method, operator, or accessor 'I1.I2.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int I2.this[int x] {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.I2.this[int].get").WithLocation(9, 32) }, new DiagnosticDescription[] { // (9,32): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // extern int I2.this[int x] {get;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(9, 32), // (9,32): warning CS0626: Method, operator, or accessor 'I1.I2.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int I2.this[int x] {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.I2.this[int].get").WithLocation(9, 32) }, new DiagnosticDescription[] { // (9,32): error CS8501: Target runtime doesn't support default interface implementation. // extern int I2.this[int x] {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(9, 32), // (9,32): warning CS0626: Method, operator, or accessor 'I1.I2.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int I2.this[int x] {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.I2.this[int].get").WithLocation(9, 32) }, // (10,7): error CS0179: 'I1.I2.this[int].set' cannot be extern and declare a body // { set {}} Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("I1.I2.this[int].set").WithLocation(10, 7) ); } [Fact] public void IndexerImplementationInDerived_10() { var source1 = @" public interface I1 { int this[int x] {get;set;} int this[long x] {get;set;} } public interface I2 : I1 { int I1.this[int x] { get => throw null; } int I1.this[long x] { set => throw null; } } class Test1 : I2 {} public interface I3 { int this[int x] {get;} int this[long x] {set;} int this[byte x] {get;set;} int this[short x] {get;set;} } public interface I4 : I3 { int I3.this[int x] { get => throw null; set => throw null; } int I3.this[long x] { get => throw null; set => throw null; } int I3.this[byte x] {get; set;} int I3.this[short x] {get; set;} = 0; } class Test2 : I4 {} "; ValidatePropertyImplementationInDerived_05(source1, // (44,38): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // int I3.this[short x] {get; set;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(44, 38), // (10,12): error CS0551: Explicit interface implementation 'I2.I1.this[int]' is missing accessor 'I1.this[int].set' // int I1.this[int x] Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("I2.I1.this[int]", "I1.this[int].set").WithLocation(10, 12), // (14,12): error CS0551: Explicit interface implementation 'I2.I1.this[long]' is missing accessor 'I1.this[long].get' // int I1.this[long x] Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("I2.I1.this[long]", "I1.this[long].get").WithLocation(14, 12), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.this[long]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[long]").WithLocation(20, 15), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(20, 15), // (36,9): error CS0550: 'I4.I3.this[int].set' adds an accessor not found in interface member 'I3.this[int]' // set => throw null; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I4.I3.this[int].set", "I3.this[int]").WithLocation(36, 9), // (40,9): error CS0550: 'I4.I3.this[long].get' adds an accessor not found in interface member 'I3.this[long]' // get => throw null; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I4.I3.this[long].get", "I3.this[long]").WithLocation(40, 9), // (43,26): error CS0501: 'I4.I3.this[byte].get' must declare a body because it is not marked abstract, extern, or partial // int I3.this[byte x] {get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I4.I3.this[byte].get").WithLocation(43, 26), // (43,31): error CS0501: 'I4.I3.this[byte].set' must declare a body because it is not marked abstract, extern, or partial // int I3.this[byte x] {get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I4.I3.this[byte].set").WithLocation(43, 31), // (44,27): error CS0501: 'I4.I3.this[short].get' must declare a body because it is not marked abstract, extern, or partial // int I3.this[short x] {get; set;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I4.I3.this[short].get").WithLocation(44, 27), // (44,32): error CS0501: 'I4.I3.this[short].set' must declare a body because it is not marked abstract, extern, or partial // int I3.this[short x] {get; set;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I4.I3.this[short].set").WithLocation(44, 32) ); } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void IndexerImplementationInDerived_11() { var source1 = @" public interface I2 { internal int this[int x] {get;} } public interface I4 { int this[int x] {get; internal set;} } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { _ = i2[0]; i4[0] = i4[0]; } } "; var source2 = @" public interface I1 : I2, I5 { int I2.this[int x] => Getter(); private int Getter() { System.Console.WriteLine(""I2.M1""); return 1; } int I4.this[int x] { get { System.Console.WriteLine(""I4.M1""); return 1; } set => System.Console.WriteLine(""I4.M1.set""); } } public interface I3 : I1 { } "; ValidatePropertyImplementationInDerived_11(source1, source2, // (4,12): error CS0122: 'I2.this[int]' is inaccessible due to its protection level // int I2.this[int x] => Getter(); Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I2.this[int]").WithLocation(4, 12), // (11,12): error CS0122: 'I4.this[int].set' is inaccessible due to its protection level // int I4.this[int x] Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I4.this[int].set").WithLocation(11, 12) ); } [Fact] [WorkItem(20083, "https://github.com/dotnet/roslyn/issues/20083")] public void IndexerImplementationInDerived_12() { var source1 = @" public interface I1 { int this[int x] { get => throw null; set => throw null;} } public interface I2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""I2.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I2.I1.M1.set""); } } } public interface I3 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""I3.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I3.I1.M1.set""); } } } public interface I4 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""I4.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I4.I1.M1.set""); } } } public interface I5 : I2, I3 { int I1.this[int x] { get { System.Console.WriteLine(""I5.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I5.I1.M1.set""); } } } public interface I6 : I1, I2, I3, I5 {} "; var source4 = @" class Test5 : I2 {} class Test6 : I1, I2, I3, I5 {} class Test7 : I6 { static void Main() { I1 i1 = new Test5(); i1[0] = i1[0]; i1 = new Test6(); i1[0] = i1[0]; i1 = new Test7(); i1[0] = i1[0]; } } "; var source5 = @" class Test8 : I2, I3 { int I1.this[int x] { get { System.Console.WriteLine(""Test8.I1.M1.get""); return 1; } set { System.Console.WriteLine(""Test8.I1.M1.set""); } } static void Main() { I1 i1 = new Test8(); i1[0] = i1[0]; i1 = new Test9(); i1[0] = i1[0]; i1 = new Test10(); i1[0] = i1[0]; i1 = new Test11(); i1[0] = i1[0]; i1 = new Test12(); i1[0] = i1[0]; } } class Test9 : I7 { int I1.this[int x] { get { System.Console.WriteLine(""Test9.I1.M1.get""); return 1; } set { System.Console.WriteLine(""Test9.I1.M1.set""); } } } class Test10 : I1, I2, I3, I4 { public int this[int x] { get { System.Console.WriteLine(""Test10.M1.get""); return 1; } set { System.Console.WriteLine(""Test10.M1.set""); } } } class Test11 : I1, I2, I3, I5, I4 { public int this[int x] { get { System.Console.WriteLine(""Test11.M1.get""); return 1; } set { System.Console.WriteLine(""Test11.M1.set""); } } } class Test12 : I8 { public virtual int this[int x] { get { System.Console.WriteLine(""Test12.M1.get""); return 1; } set { System.Console.WriteLine(""Test12.M1.set""); } } } "; ValidatePropertyImplementationInDerived_12(source1, source4, source5, new DiagnosticDescription[] { // (2,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15), // (5,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test2 : I7 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I7").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(5, 15), // (8,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test3 : I1, I2, I3, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(8, 15), // (11,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I5.I1.this[int]', nor 'I4.I1.this[int]' are most specific. // class Test4 : I1, I2, I3, I5, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.this[int]", "I5.I1.this[int]", "I4.I1.this[int]").WithLocation(11, 15), // (14,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I5.I1.this[int]', nor 'I4.I1.this[int]' are most specific. // class Test5 : I8 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I8").WithArguments("I1.this[int]", "I5.I1.this[int]", "I4.I1.this[int]").WithLocation(14, 15) }, new DiagnosticDescription[] { // (2,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15), // (5,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test2 : I7 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I7").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(5, 15), // (8,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test3 : I1, I2, I3, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(8, 15), // (11,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I5.I1.Item[int]', nor 'I4.I1.Item[int]' are most specific. // class Test4 : I1, I2, I3, I5, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.this[int]", "I5.I1.Item[int]", "I4.I1.Item[int]").WithLocation(11, 15), // (14,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I5.I1.Item[int]', nor 'I4.I1.Item[int]' are most specific. // class Test5 : I8 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I8").WithArguments("I1.this[int]", "I5.I1.Item[int]", "I4.I1.Item[int]").WithLocation(14, 15) } ); } [Fact] public void IndexerImplementationInDerived_13() { var source1 = @" public interface I1 { int this[int x] {get;} } public interface I2 : I1 { int I1.this[int x] => throw null; } public interface I3 : I1 { int I1.this[int x] => throw null; } "; var source2 = @" class Test1 : I2, I3 { public long this[int x] => 1; } "; ValidatePropertyImplementationInDerived_13(source1, source2, new DiagnosticDescription[] { // (2,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15), // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.this[int]'. 'Test1.this[int]' cannot implement 'I1.this[int]' because it does not have the matching return type of 'int'. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test1", "I1.this[int]", "Test1.this[int]", "int").WithLocation(2, 15) }, new DiagnosticDescription[] { // (2,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15), // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.this[int]'. 'Test1.this[int]' cannot implement 'I1.this[int]' because it does not have the matching return type of 'int'. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test1", "I1.this[int]", "Test1.this[int]", "int").WithLocation(2, 15) } ); } [Fact] [WorkItem(20084, "https://github.com/dotnet/roslyn/issues/20084")] public void IndexerImplementationInDerived_14() { var source1 = @" public interface I1<T> { int this[int x] { get { System.Console.WriteLine(""I1.M1.get""); return 1; } set => System.Console.WriteLine(""I1.M1.set""); } } public interface I2<T> : I1<T> { int I1<T>.this[int x] { get { System.Console.WriteLine(""I2.I1.M1.get""); return 1; } set => System.Console.WriteLine(""I2.I1.M1.set""); } } public interface I3<T> : I1<T> {} "; var source2 = @" class Test1 : I1<int> { static void Main() { I1<int> i1Int = new Test1(); i1Int[0] = i1Int[0]; I1<long> i1Long = new Test2(); i1Long[0] = i1Long[0]; } } class Test2 : I2<long> {} "; ValidatePropertyImplementationInDerived_14(source1, source2); } [Fact] public void IndexerImplementationInDerived_15() { var source1 = @" public interface I2 { int this[int x] {get => throw null; private set => throw null;} } public interface I4 { int this[int x] {set => throw null; private get => throw null;} } public interface I5 : I4 { } public interface I1 : I2, I5 { int I2.this[int x] { get { System.Console.WriteLine(""I2.M1""); return 1; } } int I4.this[int x] { set => System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source2 = @" class Test1 : I1 { static void Main() { I2 i2 = new Test1(); _ = i2[0]; I4 i4 = new Test1(); i4[0] = 0; } } "; ValidatePropertyImplementationInDerived_01(source1, source2); } [Fact] public void Field_01() { var source1 = @" public interface I1 { int F1; protected static int F2; protected internal static int F3; private protected static int F4; int F5 = 5; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyEmitDiagnostics( // (4,9): error CS0525: Interfaces cannot contain instance fields // int F1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F1").WithLocation(4, 9), // (5,26): error CS8701: Target runtime doesn't support default interface implementation. // protected static int F2; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F2").WithLocation(5, 26), // (6,35): error CS8701: Target runtime doesn't support default interface implementation. // protected internal static int F3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F3").WithLocation(6, 35), // (7,34): error CS8701: Target runtime doesn't support default interface implementation. // private protected static int F4; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F4").WithLocation(7, 34), // (8,9): error CS0525: Interfaces cannot contain instance fields // int F5 = 5; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F5").WithLocation(8, 9) ); validate(compilation1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,9): error CS0525: Interfaces cannot contain instance fields // int F1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F1").WithLocation(4, 9), // (8,9): error CS0525: Interfaces cannot contain instance fields // int F5 = 5; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F5").WithLocation(8, 9) ); validate(compilation2); static void validate(CSharpCompilation compilation) { var i1 = compilation.GetTypeByMetadataName("I1"); var f1 = i1.GetMember<FieldSymbol>("F1"); var f2 = i1.GetMember<FieldSymbol>("F2"); var f3 = i1.GetMember<FieldSymbol>("F3"); var f4 = i1.GetMember<FieldSymbol>("F4"); Assert.False(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Protected, f2.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedAndInternal, f4.DeclaredAccessibility); } } [Fact] public void Field_02() { var source1 = @" public interface I1 { static int F1; public static int F2; internal static int F3; private static int F4; public class TestHelper { public static int F4Proxy { get => I1.F4; set => I1.F4 = value; } } } class Test1 : I1 { static void Main() { I1.F1 = 1; I1.F2 = 2; I1.F3 = 3; I1.TestHelper.F4Proxy = 4; System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.F3}{I1.TestHelper.F4Proxy}""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<FieldSymbol>("F1"); var f2 = i1.GetMember<FieldSymbol>("F2"); var f3 = i1.GetMember<FieldSymbol>("F3"); var f4 = i1.GetMember<FieldSymbol>("F4"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f4.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Null(cctor); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { I1.F1 = 11; I1.F2 = 22; I1.TestHelper.F4Proxy = 44; System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.TestHelper.F4Proxy}""); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "112244"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "112244"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,16): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static int F1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F1").WithArguments("default interface implementation", "8.0").WithLocation(4, 16), // (5,23): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static int F2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F2").WithArguments("default interface implementation", "8.0").WithLocation(5, 23), // (6,25): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // internal static int F3; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F3").WithArguments("default interface implementation", "8.0").WithLocation(6, 25), // (7,24): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // private static int F4; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F4").WithArguments("default interface implementation", "8.0").WithLocation(7, 24), // (9,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(9, 18) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,16): error CS8701: Target runtime doesn't support default interface implementation. // static int F1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F1").WithLocation(4, 16), // (5,23): error CS8701: Target runtime doesn't support default interface implementation. // public static int F2; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F2").WithLocation(5, 23), // (6,25): error CS8701: Target runtime doesn't support default interface implementation. // internal static int F3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F3").WithLocation(6, 25), // (7,24): error CS8701: Target runtime doesn't support default interface implementation. // private static int F4; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F4").WithLocation(7, 24) ); Validate1(compilation5.SourceModule); } [Fact] public void Field_03() { var source1 = @" public interface I1 { static readonly int F1 = 1; public static readonly int F2 = 2; internal static readonly int F3 = 3; private static readonly int F4 = 4; public class TestHelper { public static int F4Proxy { get => I1.F4; } } } class Test1 : I1 { static void Main() { System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.F3}{I1.TestHelper.F4Proxy}""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<FieldSymbol>("F1"); var f2 = i1.GetMember<FieldSymbol>("F2"); var f3 = i1.GetMember<FieldSymbol>("F3"); var f4 = i1.GetMember<FieldSymbol>("F4"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.True(f1.IsReadOnly); Assert.True(f2.IsReadOnly); Assert.True(f3.IsReadOnly); Assert.True(f4.IsReadOnly); Assert.False(f1.IsConst); Assert.False(f2.IsConst); Assert.False(f3.IsConst); Assert.False(f4.IsConst); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f4.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Equal(MethodKind.StaticConstructor, cctor.MethodKind); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.TestHelper.F4Proxy}""); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "124"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "124"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,25): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static readonly int F1 = 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F1").WithArguments("default interface implementation", "8.0").WithLocation(4, 25), // (5,32): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static readonly int F2 = 2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F2").WithArguments("default interface implementation", "8.0").WithLocation(5, 32), // (6,34): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // internal static readonly int F3 = 3; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F3").WithArguments("default interface implementation", "8.0").WithLocation(6, 34), // (7,33): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // private static readonly int F4 = 4; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F4").WithArguments("default interface implementation", "8.0").WithLocation(7, 33), // (9,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(9, 18) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,25): error CS8701: Target runtime doesn't support default interface implementation. // static readonly int F1 = 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F1").WithLocation(4, 25), // (5,32): error CS8701: Target runtime doesn't support default interface implementation. // public static readonly int F2 = 2; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F2").WithLocation(5, 32), // (6,34): error CS8701: Target runtime doesn't support default interface implementation. // internal static readonly int F3 = 3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F3").WithLocation(6, 34), // (7,33): error CS8701: Target runtime doesn't support default interface implementation. // private static readonly int F4 = 4; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F4").WithLocation(7, 33) ); Validate1(compilation5.SourceModule); } [Fact] public void Field_04() { var source1 = @" public interface I1 { const int F1 = 1; public const int F2 = 2; internal const int F3 = 3; private const int F4 = 4; public class TestHelper { public static int F4Proxy { get => I1.F4; } } } class Test1 : I1 { static void Main() { System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.F3}{I1.TestHelper.F4Proxy}""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<FieldSymbol>("F1"); var f2 = i1.GetMember<FieldSymbol>("F2"); var f3 = i1.GetMember<FieldSymbol>("F3"); var f4 = i1.GetMember<FieldSymbol>("F4"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.True(f1.IsConst); Assert.True(f2.IsConst); Assert.True(f3.IsConst); Assert.True(f4.IsConst); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f4.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Null(cctor); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.TestHelper.F4Proxy}""); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "124"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "124"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,15): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // const int F1 = 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F1").WithArguments("default interface implementation", "8.0").WithLocation(4, 15), // (5,22): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public const int F2 = 2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F2").WithArguments("default interface implementation", "8.0").WithLocation(5, 22), // (6,24): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // internal const int F3 = 3; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F3").WithArguments("default interface implementation", "8.0").WithLocation(6, 24), // (7,23): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // private const int F4 = 4; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F4").WithArguments("default interface implementation", "8.0").WithLocation(7, 23), // (9,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(9, 18) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,15): error CS8701: Target runtime doesn't support default interface implementation. // const int F1 = 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F1").WithLocation(4, 15), // (5,22): error CS8701: Target runtime doesn't support default interface implementation. // public const int F2 = 2; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F2").WithLocation(5, 22), // (6,24): error CS8701: Target runtime doesn't support default interface implementation. // internal const int F3 = 3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F3").WithLocation(6, 24), // (7,23): error CS8701: Target runtime doesn't support default interface implementation. // private const int F4 = 4; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F4").WithLocation(7, 23) ); Validate1(compilation5.SourceModule); } [Fact] public void Field_05() { var source0 = @" public interface I1 { static protected int F1; static protected internal int F2; static private protected int F3; } "; var source1 = @" class Test1 : I1 { static void Main() { I1.F1 = 1; I1.F2 = 2; I1.F3 = 3; System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.F3}""); Test2.Test(); } } class Test2 { public static void Test() { I1.F2 = -2; System.Console.WriteLine(I1.F2); } } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"123 -2 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var source2 = @" class Test2 : I1 { static void Main() { I1.F1 = 11; I1.F2 = 22; System.Console.WriteLine($""{I1.F1}{I1.F2}""); } } "; var references = new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }; foreach (var reference in references) { var compilation2 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "1122" : null, verify: VerifyOnMonoOrCoreClr); } var source3 = @" class Test1 { static void Main() { I1.F1 = 1; I1.F2 = 2; I1.F3 = 3; } } "; var compilation3 = CreateCompilation(source0 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (13,12): error CS0122: 'I1.F1' is inaccessible due to its protection level // I1.F1 = 1; Diagnostic(ErrorCode.ERR_BadAccess, "F1").WithArguments("I1.F1").WithLocation(13, 12), // (15,12): error CS0122: 'I1.F3' is inaccessible due to its protection level // I1.F3 = 3; Diagnostic(ErrorCode.ERR_BadAccess, "F3").WithArguments("I1.F3").WithLocation(15, 12) ); var source4 = @" class Test2 : I1 { static void Test() { I1.F3 = -3; } } "; foreach (var reference in references) { var compilation2 = CreateCompilation(source3 + source4, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,12): error CS0122: 'I1.F1' is inaccessible due to its protection level // I1.F1 = 1; Diagnostic(ErrorCode.ERR_BadAccess, "F1").WithArguments("I1.F1").WithLocation(6, 12), // (7,12): error CS0122: 'I1.F2' is inaccessible due to its protection level // I1.F2 = 2; Diagnostic(ErrorCode.ERR_BadAccess, "F2").WithArguments("I1.F2").WithLocation(7, 12), // (8,12): error CS0122: 'I1.F3' is inaccessible due to its protection level // I1.F3 = 3; Diagnostic(ErrorCode.ERR_BadAccess, "F3").WithArguments("I1.F3").WithLocation(8, 12), // (16,12): error CS0122: 'I1.F3' is inaccessible due to its protection level // I1.F3 = -3; Diagnostic(ErrorCode.ERR_BadAccess, "F3").WithArguments("I1.F3").WithLocation(16, 12) ); } var compilation4 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,26): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static protected int F1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F1").WithArguments("default interface implementation", "8.0").WithLocation(4, 26), // (5,35): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static protected internal int F2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F2").WithArguments("default interface implementation", "8.0").WithLocation(5, 35), // (6,34): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static private protected int F3; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F3").WithArguments("default interface implementation", "8.0").WithLocation(6, 34) ); validate(compilation4.SourceModule); void validate(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<FieldSymbol>("F1"); var f2 = i1.GetMember<FieldSymbol>("F2"); var f3 = i1.GetMember<FieldSymbol>("F3"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.Equal(Accessibility.Protected, f1.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, f2.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedAndInternal, f3.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Null(cctor); } } [Fact] public void Constructors_01() { var source1 = @" public interface I1 { I1(){} static I1() {} } interface I2 { I2(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,5): error CS0526: Interfaces cannot contain instance constructors // I1(){} Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I1").WithLocation(4, 5), // (10,5): error CS0501: 'I2.I2()' must declare a body because it is not marked abstract, extern, or partial // I2(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I2").WithArguments("I2.I2()").WithLocation(10, 5), // (10,5): error CS0526: Interfaces cannot contain instance constructors // I2(); Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I2").WithLocation(10, 5) ); } [Fact] public void Constructors_02() { var source1 = @" interface I1 { static I1() {} } interface I2 { static I2() => throw null; } interface I3 { I3() {} } interface I4 { I4() => throw null; } interface I5 { I5(); } interface I6 { extern static I6(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,12): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static I1() {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "I1").WithArguments("default interface implementation", "8.0").WithLocation(4, 12), // (8,12): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static I2() => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "I2").WithArguments("default interface implementation", "8.0").WithLocation(8, 12), // (12,5): error CS0526: Interfaces cannot contain instance constructors // I3() {} Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I3").WithLocation(12, 5), // (16,5): error CS0526: Interfaces cannot contain instance constructors // I4() => throw null; Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I4").WithLocation(16, 5), // (20,5): error CS0501: 'I5.I5()' must declare a body because it is not marked abstract, extern, or partial // I5(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I5").WithArguments("I5.I5()").WithLocation(20, 5), // (20,5): error CS0526: Interfaces cannot contain instance constructors // I5(); Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I5").WithLocation(20, 5), // (24,19): error CS8703: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern static I6(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I6").WithArguments("extern", "7.3", "8.0").WithLocation(24, 19), // (24,19): warning CS0824: Constructor 'I6.I6()' is marked external // extern static I6(); Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "I6").WithArguments("I6.I6()").WithLocation(24, 19) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (4,12): error CS8701: Target runtime doesn't support default interface implementation. // static I1() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "I1").WithLocation(4, 12), // (8,12): error CS8701: Target runtime doesn't support default interface implementation. // static I2() => throw null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "I2").WithLocation(8, 12), // (12,5): error CS0526: Interfaces cannot contain instance constructors // I3() {} Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I3").WithLocation(12, 5), // (16,5): error CS0526: Interfaces cannot contain instance constructors // I4() => throw null; Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I4").WithLocation(16, 5), // (20,5): error CS0501: 'I5.I5()' must declare a body because it is not marked abstract, extern, or partial // I5(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I5").WithArguments("I5.I5()").WithLocation(20, 5), // (20,5): error CS0526: Interfaces cannot contain instance constructors // I5(); Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I5").WithLocation(20, 5), // (24,19): error CS8701: Target runtime doesn't support default interface implementation. // extern static I6(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "I6").WithLocation(24, 19), // (24,19): warning CS0824: Constructor 'I6.I6()' is marked external // extern static I6(); Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "I6").WithArguments("I6.I6()").WithLocation(24, 19) ); } [Fact] public void Constructors_03() { var source1 = @" interface I1 { static I1(int i) {} } interface I2 { static void I2() {} } interface I3 { void I3() {} } interface I4 { public static I4() {} } interface I5 { internal static I5() {} } interface I6 { private static I6() {} } interface I7 { static I7(); } interface I8 { static I8(){} static void M1() { I8(); } void M2() { I8.I8(); } } interface I9 { static I9() {} => throw null; } interface I10 { abstract static I10(); } interface I11 { virtual static I11(); } interface I12 { abstract static I12() {} } interface I13 { virtual static I13() => throw null; } interface I14 { partial static I14(); } interface I15 { static partial I15(); } interface I16 { partial static I16() {} } interface I17 { static partial I17() => throw null; } interface I18 { extern static I18() {} } interface I19 { static extern I19() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,12): error CS0132: 'I1.I1(int)': a static constructor must be parameterless // static I1(int i) {} Diagnostic(ErrorCode.ERR_StaticConstParam, "I1").WithArguments("I1.I1(int)").WithLocation(4, 12), // (8,17): error CS0542: 'I2': member names cannot be the same as their enclosing type // static void I2() {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I2").WithArguments("I2").WithLocation(8, 17), // (16,19): error CS0515: 'I4.I4()': access modifiers are not allowed on static constructors // public static I4() {} Diagnostic(ErrorCode.ERR_StaticConstructorWithAccessModifiers, "I4").WithArguments("I4.I4()").WithLocation(16, 19), // (20,21): error CS0515: 'I5.I5()': access modifiers are not allowed on static constructors // internal static I5() {} Diagnostic(ErrorCode.ERR_StaticConstructorWithAccessModifiers, "I5").WithArguments("I5.I5()").WithLocation(20, 21), // (24,20): error CS0515: 'I6.I6()': access modifiers are not allowed on static constructors // private static I6() {} Diagnostic(ErrorCode.ERR_StaticConstructorWithAccessModifiers, "I6").WithArguments("I6.I6()").WithLocation(24, 20), // (28,12): error CS0501: 'I7.I7()' must declare a body because it is not marked abstract, extern, or partial // static I7(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I7").WithArguments("I7.I7()").WithLocation(28, 12), // (36,9): error CS1955: Non-invocable member 'I8' cannot be used like a method. // I8(); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "I8").WithArguments("I8").WithLocation(36, 9), // (41,12): error CS0117: 'I8' does not contain a definition for 'I8' // I8.I8(); Diagnostic(ErrorCode.ERR_NoSuchMember, "I8").WithArguments("I8", "I8").WithLocation(41, 12), // (46,5): error CS8057: Block bodies and expression bodies cannot both be provided. // static I9() {} => throw null; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "static I9() {} => throw null;").WithLocation(46, 5), // (50,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I10(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I10").WithArguments("abstract").WithLocation(50, 21), // (54,20): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I11(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I11").WithArguments("virtual").WithLocation(54, 20), // (58,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I12() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I12").WithArguments("abstract").WithLocation(58, 21), // (62,20): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I13() => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "I13").WithArguments("virtual").WithLocation(62, 20), // (66,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I14(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(66, 5), // (66,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I14(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(66, 5), // (70,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I15(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(70, 12), // (70,20): error CS0501: 'I15.I15()' must declare a body because it is not marked abstract, extern, or partial // static partial I15(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I15").WithArguments("I15.I15()").WithLocation(70, 20), // (70,20): error CS0542: 'I15': member names cannot be the same as their enclosing type // static partial I15(); Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I15").WithArguments("I15").WithLocation(70, 20), // (74,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I16() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(74, 5), // (74,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I16() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(74, 5), // (78,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I17() => throw null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(78, 12), // (78,20): error CS0542: 'I17': member names cannot be the same as their enclosing type // static partial I17() => throw null; Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I17").WithArguments("I17").WithLocation(78, 20), // (82,19): error CS0179: 'I18.I18()' cannot be extern and declare a body // extern static I18() {} Diagnostic(ErrorCode.ERR_ExternHasBody, "I18").WithArguments("I18.I18()").WithLocation(82, 19), // (86,19): error CS0179: 'I19.I19()' cannot be extern and declare a body // static extern I19() => throw null; Diagnostic(ErrorCode.ERR_ExternHasBody, "I19").WithArguments("I19.I19()").WithLocation(86, 19) ); } [Fact] public void Constructors_04() { var source1 = @" interface I1 { static I1() { System.Console.WriteLine(""I1""); } static void Main() { System.Console.WriteLine(""Main""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); ValidateConstructor(compilation1.SourceModule); Assert.Empty(compilation1.GetTypeByMetadataName("I1").GetMembers("I1")); CompileAndVerify(compilation1, symbolValidator: ValidateConstructor, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1 Main "); } private static void ValidateConstructor(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(cctor.IsAbstract); Assert.False(cctor.IsVirtual); Assert.False(cctor.IsMetadataVirtual()); Assert.False(cctor.IsSealed); Assert.True(cctor.IsStatic); Assert.False(cctor.IsExtern); Assert.False(cctor.IsAsync); Assert.False(cctor.IsOverride); Assert.Equal(Accessibility.Private, cctor.DeclaredAccessibility); Assert.Equal(MethodKind.StaticConstructor, cctor.MethodKind); } [Fact] public void Constructors_05() { var source1 = @" interface I1 { static string F = ""F""; static void Main() { System.Console.WriteLine(F); System.Console.WriteLine(""Main""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); ValidateConstructor(compilation1.SourceModule); CompileAndVerify(compilation1, symbolValidator: ValidateConstructor, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"F Main "); } [Fact] public void Constructors_06() { var source1 = @" interface I1 { static string F = ""F""; static I1() { System.Console.WriteLine(F); System.Console.WriteLine(""I1""); } static void Main() { System.Console.WriteLine(""Main""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); ValidateConstructor(compilation1.SourceModule); CompileAndVerify(compilation1, symbolValidator: ValidateConstructor, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"F I1 Main "); } [Fact] public void Constructors_07() { var source1 = @" interface I1 { extern static I1(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,19): warning CS0824: Constructor 'I1.I1()' is marked external // extern static I1(); Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "I1").WithArguments("I1.I1()").WithLocation(4, 19) ); var i1 = compilation1.SourceModule.GlobalNamespace.GetTypeMember("I1"); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(cctor.IsAbstract); Assert.False(cctor.IsVirtual); Assert.False(cctor.IsMetadataVirtual()); Assert.False(cctor.IsSealed); Assert.True(cctor.IsStatic); Assert.True(cctor.IsExtern); Assert.False(cctor.IsAsync); Assert.False(cctor.IsOverride); Assert.Equal(Accessibility.Private, cctor.DeclaredAccessibility); Assert.Equal(MethodKind.StaticConstructor, cctor.MethodKind); CompileAndVerify(compilation1, symbolValidator: ValidateConstructor, verify: Verification.Skipped); } [Fact] public void Constructors_08() { var source1 = @" interface I1 { void I1(); } class Test : I1 { void I1.I1() { System.Console.WriteLine(""Test.I1""); } static void Main() { I1 x = new Test(); x.I1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: "Test.I1"); } [Fact] public void Constructors_09() { var source1 = @" interface I1 { void I1(); static I1() { System.Console.WriteLine(""I1..cctor""); } static void M1() { System.Console.WriteLine(""I1.M1""); } } class Test : I1 { void I1.I1() { System.Console.WriteLine(""Test.I1""); } static void Main() { I1.M1(); I1 x = new Test(); x.I1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1..cctor I1.M1 Test.I1 "); } [Fact] public void Constructors_10() { var source1 = @" interface I1 { void I1() { System.Console.WriteLine(""I1.I1""); } static I1() { System.Console.WriteLine(""I1..cctor""); } static void M1() { System.Console.WriteLine(""I1.M1""); } } class Test : I1 { static void Main() { I1.M1(); I1 x = new Test(); x.I1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1..cctor I1.M1 I1.I1 ", verify: VerifyOnMonoOrCoreClr); } [Fact] public void Constructors_11() { var source1 = @" interface I1 { void I1() { System.Console.WriteLine(""I1.I1""); } } class Test : I1 { static void Main() { I1 x = new Test(); x.I1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "I1.I1", verify: VerifyOnMonoOrCoreClr); } /// <summary> /// Make sure runtime handles cycles in static constructors. /// </summary> [Fact] public void Constructors_12() { var source0 = @" interface I1 { public static int F1; static I1() { F1 = I2.F2; } } interface I2 { public static int F2; static I2() { F2 = I1.F1 + 1; } } "; var source1 = @" class Test { static void Main() { System.Console.WriteLine(I1.F1 + I2.F2); } } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "2"); var source2 = @" class Test { static void Main() { System.Console.WriteLine(I2.F2 + I1.F1); } } "; var compilation2 = CreateCompilation(source0 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1"); } [Fact] public void AutoProperty_01() { var source1 = @" public interface I1 { private int F1 {get; set;} private int F5 {get;} = 5; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics( // (4,21): error CS0501: 'I1.F1.get' must declare a body because it is not marked abstract, extern, or partial // private int F1 {get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.F1.get").WithLocation(4, 21), // (4,26): error CS0501: 'I1.F1.set' must declare a body because it is not marked abstract, extern, or partial // private int F1 {get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.F1.set").WithLocation(4, 26), // (5,17): error CS8053: Instance properties in interfaces cannot have initializers. // private int F5 {get;} = 5; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "F5").WithArguments("I1.F5").WithLocation(5, 17), // (5,21): error CS0501: 'I1.F5.get' must declare a body because it is not marked abstract, extern, or partial // private int F5 {get;} = 5; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.F5.get").WithLocation(5, 21) ); } [Fact] public void AutoProperty_02() { var source1 = @" public interface I1 { static int F1 {get; set;} public static int F2 {get; set;} internal static int F3 {get; set;} private static int F4 {get; set;} public class TestHelper { public static int F4Proxy { get => I1.F4; set => I1.F4 = value; } } } class Test1 : I1 { static void Main() { I1.F1 = 1; I1.F2 = 2; I1.F3 = 3; I1.TestHelper.F4Proxy = 4; System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.F3}{I1.TestHelper.F4Proxy}""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<PropertySymbol>("F1"); var f2 = i1.GetMember<PropertySymbol>("F2"); var f3 = i1.GetMember<PropertySymbol>("F3"); var f4 = i1.GetMember<PropertySymbol>("F4"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f4.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Null(cctor); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { I1.F1 = 11; I1.F2 = 22; I1.TestHelper.F4Proxy = 44; System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.TestHelper.F4Proxy}""); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "112244"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "112244"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,16): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static int F1 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F1").WithArguments("static", "7.3", "8.0").WithLocation(4, 16), // (5,23): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static int F2 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("static", "7.3", "8.0").WithLocation(5, 23), // (5,23): error CS8703: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static int F2 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("public", "7.3", "8.0").WithLocation(5, 23), // (6,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static int F3 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("static", "7.3", "8.0").WithLocation(6, 25), // (6,25): error CS8703: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static int F3 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("internal", "7.3", "8.0").WithLocation(6, 25), // (7,24): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static int F4 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("static", "7.3", "8.0").WithLocation(7, 24), // (7,24): error CS8703: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static int F4 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("private", "7.3", "8.0").WithLocation(7, 24), // (9,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(9, 18) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,20): error CS8701: Target runtime doesn't support default interface implementation. // static int F1 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(4, 20), // (4,25): error CS8701: Target runtime doesn't support default interface implementation. // static int F1 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(4, 25), // (5,27): error CS8701: Target runtime doesn't support default interface implementation. // public static int F2 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(5, 27), // (5,32): error CS8701: Target runtime doesn't support default interface implementation. // public static int F2 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(5, 32), // (6,29): error CS8701: Target runtime doesn't support default interface implementation. // internal static int F3 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(6, 29), // (6,34): error CS8701: Target runtime doesn't support default interface implementation. // internal static int F3 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(6, 34), // (7,28): error CS8701: Target runtime doesn't support default interface implementation. // private static int F4 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(7, 28), // (7,33): error CS8701: Target runtime doesn't support default interface implementation. // private static int F4 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(7, 33) ); Validate1(compilation5.SourceModule); } [Fact] public void AutoProperty_03() { var source1 = @" public interface I1 { static int F1 {get;} = 1; public static int F2 {get;} = 2; internal static int F3 {get;} = 3; private static int F4 {get;} = 4; public class TestHelper { public static int F4Proxy { get => I1.F4; } } } class Test1 : I1 { static void Main() { System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.F3}{I1.TestHelper.F4Proxy}""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<PropertySymbol>("F1"); var f2 = i1.GetMember<PropertySymbol>("F2"); var f3 = i1.GetMember<PropertySymbol>("F3"); var f4 = i1.GetMember<PropertySymbol>("F4"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.True(f1.IsReadOnly); Assert.True(f2.IsReadOnly); Assert.True(f3.IsReadOnly); Assert.True(f4.IsReadOnly); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f4.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Equal(MethodKind.StaticConstructor, cctor.MethodKind); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.TestHelper.F4Proxy}""); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "124"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "124"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,16): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static int F1 {get;} = 1; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F1").WithArguments("static", "7.3", "8.0").WithLocation(4, 16), // (5,23): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static int F2 {get;} = 2; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("static", "7.3", "8.0").WithLocation(5, 23), // (5,23): error CS8703: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static int F2 {get;} = 2; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("public", "7.3", "8.0").WithLocation(5, 23), // (6,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static int F3 {get;} = 3; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("static", "7.3", "8.0").WithLocation(6, 25), // (6,25): error CS8703: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static int F3 {get;} = 3; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("internal", "7.3", "8.0").WithLocation(6, 25), // (7,24): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static int F4 {get;} = 4; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("static", "7.3", "8.0").WithLocation(7, 24), // (7,24): error CS8703: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static int F4 {get;} = 4; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("private", "7.3", "8.0").WithLocation(7, 24), // (9,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(9, 18) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,20): error CS8701: Target runtime doesn't support default interface implementation. // static int F1 {get;} = 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(4, 20), // (5,27): error CS8701: Target runtime doesn't support default interface implementation. // public static int F2 {get;} = 2; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(5, 27), // (6,29): error CS8701: Target runtime doesn't support default interface implementation. // internal static int F3 {get;} = 3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(6, 29), // (7,28): error CS8701: Target runtime doesn't support default interface implementation. // private static int F4 {get;} = 4; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(7, 28) ); Validate1(compilation5.SourceModule); } [Fact] public void AutoProperty_04() { var source1 = @" public interface I1 { static int F1 {get; private set;} public static int F2 {get; private set;} internal static int F3 {get; private set;} public class TestHelper { public static void F4Proxy(int f1, int f2, int f3) { F1 = f1; F2 = f2; F3 = f3; } } } class Test1 : I1 { static void Main() { I1.TestHelper.F4Proxy(1,2,3); System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.F3}""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<PropertySymbol>("F1"); var f2 = i1.GetMember<PropertySymbol>("F2"); var f3 = i1.GetMember<PropertySymbol>("F3"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f1.SetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f2.SetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f3.SetMethod.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Null(cctor); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "123", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { I1.TestHelper.F4Proxy(11,22,3); System.Console.WriteLine($""{I1.F1}{I1.F2}""); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1122"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1122"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,16): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static int F1 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F1").WithArguments("static", "7.3", "8.0").WithLocation(4, 16), // (4,33): error CS8703: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static int F1 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("private", "7.3", "8.0").WithLocation(4, 33), // (5,23): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static int F2 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("static", "7.3", "8.0").WithLocation(5, 23), // (5,23): error CS8703: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static int F2 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("public", "7.3", "8.0").WithLocation(5, 23), // (5,40): error CS8703: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static int F2 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("private", "7.3", "8.0").WithLocation(5, 40), // (6,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static int F3 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("static", "7.3", "8.0").WithLocation(6, 25), // (6,25): error CS8703: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static int F3 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("internal", "7.3", "8.0").WithLocation(6, 25), // (6,42): error CS8703: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static int F3 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("private", "7.3", "8.0").WithLocation(6, 42), // (8,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(8, 18) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,20): error CS8701: Target runtime doesn't support default interface implementation. // static int F1 {get; private set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(4, 20), // (4,33): error CS8701: Target runtime doesn't support default interface implementation. // static int F1 {get; private set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(4, 33), // (5,27): error CS8701: Target runtime doesn't support default interface implementation. // public static int F2 {get; private set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(5, 27), // (5,40): error CS8701: Target runtime doesn't support default interface implementation. // public static int F2 {get; private set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(5, 40), // (6,29): error CS8701: Target runtime doesn't support default interface implementation. // internal static int F3 {get; private set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(6, 29), // (6,42): error CS8701: Target runtime doesn't support default interface implementation. // internal static int F3 {get; private set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(6, 42) ); Validate1(compilation5.SourceModule); } [Fact] public void FieldLikeEvent_01() { var source1 = @" public interface I1 { private event System.Action F1; private event System.Action F5 = null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyEmitDiagnostics( // (4,33): error CS0065: 'I1.F1': event property must have both add and remove accessors // private event System.Action F1; Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "F1").WithArguments("I1.F1").WithLocation(4, 33), // (5,33): error CS0068: 'I1.F5': instance event in interface cannot have initializer // private event System.Action F5 = null; Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "F5").WithArguments("I1.F5").WithLocation(5, 33), // (5,33): error CS0065: 'I1.F5': event property must have both add and remove accessors // private event System.Action F5 = null; Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "F5").WithArguments("I1.F5").WithLocation(5, 33), // (5,33): warning CS0067: The event 'I1.F5' is never used // private event System.Action F5 = null; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "F5").WithArguments("I1.F5").WithLocation(5, 33), // (4,33): warning CS0067: The event 'I1.F1' is never used // private event System.Action F1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "F1").WithArguments("I1.F1").WithLocation(4, 33) ); } [Fact] public void FieldLikeEvent_02() { var source1 = @" public interface I1 { static event System.Action F1; public static event System.Action F2; internal static event System.Action F3; private static event System.Action F4; public class TestHelper { public static System.Action F4Proxy { set => I1.F4 += value; } public static void Raise() { F1(); F2(); F3?.Invoke(); F4(); } } } class Test1 : I1 { static void Main() { I1.F1 += () => System.Console.Write(1); I1.F2 += () => System.Console.Write(2); I1.F3 += () => System.Console.Write(3); I1.TestHelper.F4Proxy = () => System.Console.Write(4); I1.TestHelper.Raise(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<EventSymbol>("F1"); var f2 = i1.GetMember<EventSymbol>("F2"); var f3 = i1.GetMember<EventSymbol>("F3"); var f4 = i1.GetMember<EventSymbol>("F4"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f4.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Null(cctor); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { I1.F1 += () => System.Console.Write(11); I1.F2 += () => System.Console.Write(22); I1.TestHelper.F4Proxy = () => System.Console.Write(44); I1.TestHelper.Raise(); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "112244"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "112244"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (9,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(9, 18), // (4,32): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static event System.Action F1; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F1").WithArguments("static", "7.3", "8.0").WithLocation(4, 32), // (5,39): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static event System.Action F2; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("static", "7.3", "8.0").WithLocation(5, 39), // (5,39): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static event System.Action F2; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("public", "7.3", "8.0").WithLocation(5, 39), // (6,41): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static event System.Action F3; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("static", "7.3", "8.0").WithLocation(6, 41), // (6,41): error CS8503: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static event System.Action F3; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("internal", "7.3", "8.0").WithLocation(6, 41), // (7,40): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static event System.Action F4; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("static", "7.3", "8.0").WithLocation(7, 40), // (7,40): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static event System.Action F4; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("private", "7.3", "8.0").WithLocation(7, 40) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,32): error CS8701: Target runtime doesn't support default interface implementation. // static event System.Action F1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F1").WithLocation(4, 32), // (5,39): error CS8701: Target runtime doesn't support default interface implementation. // public static event System.Action F2; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F2").WithLocation(5, 39), // (6,41): error CS8701: Target runtime doesn't support default interface implementation. // internal static event System.Action F3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F3").WithLocation(6, 41), // (7,40): error CS8701: Target runtime doesn't support default interface implementation. // private static event System.Action F4; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F4").WithLocation(7, 40) ); Validate1(compilation5.SourceModule); } [Fact] public void FieldLikeEvent_03() { var source1 = @" public interface I1 { static event System.Action F1 = () => System.Console.Write(1); public static event System.Action F2 = () => System.Console.Write(2); internal static event System.Action F3 = () => System.Console.Write(3); private static event System.Action F4 = () => System.Console.Write(4); public class TestHelper { public static void Raise() { F1(); F2(); F3(); F4(); } } } class Test1 : I1 { static void Main() { I1.TestHelper.Raise(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<EventSymbol>("F1"); var f2 = i1.GetMember<EventSymbol>("F2"); var f3 = i1.GetMember<EventSymbol>("F3"); var f4 = i1.GetMember<EventSymbol>("F4"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f4.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Equal(MethodKind.StaticConstructor, cctor.MethodKind); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { I1.TestHelper.Raise(); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (9,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(9, 18), // (4,32): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static event System.Action F1 = () => System.Console.Write(1); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F1").WithArguments("static", "7.3", "8.0").WithLocation(4, 32), // (5,39): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static event System.Action F2 = () => System.Console.Write(2); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("static", "7.3", "8.0").WithLocation(5, 39), // (5,39): error CS8703: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static event System.Action F2 = () => System.Console.Write(2); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("public", "7.3", "8.0").WithLocation(5, 39), // (6,41): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static event System.Action F3 = () => System.Console.Write(3); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("static", "7.3", "8.0").WithLocation(6, 41), // (6,41): error CS8703: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static event System.Action F3 = () => System.Console.Write(3); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("internal", "7.3", "8.0").WithLocation(6, 41), // (7,40): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static event System.Action F4 = () => System.Console.Write(4); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("static", "7.3", "8.0").WithLocation(7, 40), // (7,40): error CS8703: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static event System.Action F4 = () => System.Console.Write(4); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("private", "7.3", "8.0").WithLocation(7, 40) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,32): error CS8701: Target runtime doesn't support default interface implementation. // static event System.Action F1 = () => System.Console.Write(1); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F1").WithLocation(4, 32), // (5,39): error CS8701: Target runtime doesn't support default interface implementation. // public static event System.Action F2 = () => System.Console.Write(2); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F2").WithLocation(5, 39), // (6,41): error CS8701: Target runtime doesn't support default interface implementation. // internal static event System.Action F3 = () => System.Console.Write(3); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F3").WithLocation(6, 41), // (7,40): error CS8701: Target runtime doesn't support default interface implementation. // private static event System.Action F4 = () => System.Console.Write(4); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F4").WithLocation(7, 40) ); Validate1(compilation5.SourceModule); } [Fact] public void UnsupportedMemberAccess_01() { var source0 = @" public delegate void D0(); public interface I0 { static readonly int F1 = 1; static int P2 {get {System.Console.WriteLine(""P2""); return 2;} set {System.Console.WriteLine(""set_P2"");}} static void M3() {System.Console.WriteLine(""M3"");} static event D0 E4 { add {System.Console.WriteLine(""add E4"");value();} remove {System.Console.WriteLine(""remove E4"");value();} } class C6 { public static void M() {System.Console.WriteLine(""C6.M"");} } } "; var source1 = @" public delegate void D1(); public interface I1 { int P20 {get {System.Console.WriteLine(""P20""); return 20;}} int this[int P50] {set {System.Console.WriteLine(""P50"");}} void M30() {System.Console.WriteLine(""M30"");} event D1 E40 { add {System.Console.WriteLine(""add E40"");value();} remove {System.Console.WriteLine(""remove E40"");value();} } sealed int P200 {get {System.Console.WriteLine(""P200""); return 200;}} sealed int this[string P500] {set {System.Console.WriteLine(""P500"");}} sealed void M300() {System.Console.WriteLine(""M300"");} sealed event D1 E400 { add {System.Console.WriteLine(""add E400"");value();} remove {System.Console.WriteLine(""remove E400"");value();} } } public class Test1 : I1 { } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" class Test2 { static void Main() { System.Console.WriteLine(I0.F1); System.Console.WriteLine(I0.P2); I0.M3(); I0.E4 += I0.M3; I0.E4 -= new D0(I0.M3); I0.P2 = 3; I0.C6.M(); } } "; var source3 = @" class Test3 { static void Main() { I1 i1 = new Test1(); System.Console.WriteLine(i1.P20); i1.M30(); i1.E40 += i1.M30; i1.E40 -= new D1(i1.M30); i1[50] = default; } } "; var source4 = @" class Test4 : Test1 { static void Main() { I1 i1 = new Test1(); System.Console.WriteLine(i1.P200); i1.M300(); i1.E400 += i1.M300; i1.E400 -= new D1(i1.M300); i1[""500""] = default; } } "; foreach (var refs in new[] { (comp0:compilation0.ToMetadataReference(), comp1:compilation1.ToMetadataReference()), (comp0:compilation0.EmitToImageReference(), comp1:compilation1.EmitToImageReference()) }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.StandardLatest); compilation2 = compilation2.AddReferences(refs.comp0); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"1 P2 2 M3 add E4 M3 remove E4 M3 set_P2 C6.M "); var compilation3 = CreateCompilation(source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.StandardLatest); compilation3 = compilation3.AddReferences(refs.comp1); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"P20 20 M30 add E40 M30 remove E40 M30 P50 "); var compilation4 = CreateCompilation(source4, options: TestOptions.DebugExe, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); compilation4 = compilation4.AddReferences(refs.comp1); Assert.False(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics( // (7,34): error CS8501: Target runtime doesn't support default interface implementation. // System.Console.WriteLine(i1.P200); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.P200").WithLocation(7, 34), // (8,9): error CS8501: Target runtime doesn't support default interface implementation. // i1.M300(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.M300").WithLocation(8, 9), // (9,9): error CS8501: Target runtime doesn't support default interface implementation. // i1.E400 += i1.M300; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.E400 += i1.M300").WithLocation(9, 9), // (9,20): error CS8501: Target runtime doesn't support default interface implementation. // i1.E400 += i1.M300; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.M300").WithLocation(9, 20), // (10,9): error CS8501: Target runtime doesn't support default interface implementation. // i1.E400 -= new D1(i1.M300); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.E400 -= new D1(i1.M300)").WithLocation(10, 9), // (10,27): error CS8501: Target runtime doesn't support default interface implementation. // i1.E400 -= new D1(i1.M300); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.M300").WithLocation(10, 27), // (11,9): error CS8701: Target runtime doesn't support default interface implementation. // i1["500"] = default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, @"i1[""500""]").WithLocation(11, 9) ); } } [Fact] public void UnsupportedMemberAccess_02() { var source0 = @" public delegate void D0(); public interface I0 { static protected readonly int F1 = 1; static protected internal int P2 {get {System.Console.WriteLine(""P2""); return 2;} set {System.Console.WriteLine(""set_P2"");}} static protected void M3() {System.Console.WriteLine(""M3"");} static protected internal event D0 E4 { add {System.Console.WriteLine(""add E4"");value();} remove {System.Console.WriteLine(""remove E4"");value();} } protected internal class C6 { public static void M() {System.Console.WriteLine(""C6.M"");} } protected class C7<T> { } static int P8 {protected internal get {System.Console.WriteLine(""P8""); return 8;} set {System.Console.WriteLine(""set_P8"");}} static int P9 {get {System.Console.WriteLine(""P9""); return 9;} protected set {System.Console.WriteLine(""set_P9"");}} } public class Test1 : I0 { } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var source2 = @" using static I0; class Test2 : Test1 { static void Main() { System.Console.WriteLine(I0.F1); System.Console.WriteLine(I0.P2); I0.M3(); I0.E4 += I0.M3; I0.E4 -= new D0(I0.M3); I0.P2 = 3; I0.C6.M(); _ = new C7<int>(); _ = I0.P8; _ = I0.P9; I0.P8 = 12; I0.P9 = 13; } } "; foreach (var reference in new[] { compilation0.ToMetadataReference(), compilation0.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { reference }, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics( // (9,34): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // System.Console.WriteLine(I0.F1); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.F1").WithLocation(9, 34), // (10,34): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // System.Console.WriteLine(I0.P2); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.P2").WithLocation(10, 34), // (11,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.M3(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.M3").WithLocation(11, 9), // (12,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.E4 += I0.M3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.E4 += I0.M3").WithLocation(12, 9), // (12,18): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.E4 += I0.M3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.M3").WithLocation(12, 18), // (13,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.E4 -= new D0(I0.M3); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.E4 -= new D0(I0.M3)").WithLocation(13, 9), // (13,25): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.E4 -= new D0(I0.M3); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.M3").WithLocation(13, 25), // (14,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.P2 = 3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.P2").WithLocation(14, 9), // (15,12): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.C6.M(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "C6").WithLocation(15, 12), // (16,17): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // _ = new C7<int>(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "C7<int>").WithLocation(16, 17), // (17,13): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // _ = I0.P8; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.P8").WithLocation(17, 13), // (20,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.P9 = 13; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.P9").WithLocation(20, 9) ); } } [Fact] public void UnsupportedMemberAccess_03() { var source1 = @" public delegate void D1(); public interface I1 { protected int P20 {get {System.Console.WriteLine(""P20""); return 20;}} protected internal int this[int P50] {set {System.Console.WriteLine(""P50"");}} protected void M30() {System.Console.WriteLine(""M30"");} protected internal event D1 E40 { add {System.Console.WriteLine(""add E40"");value();} remove {System.Console.WriteLine(""remove E40"");value();} } int P50 {protected get {System.Console.WriteLine(""P50""); return 50;} set {}} int P60 {get {System.Console.WriteLine(""P60""); return 60;} protected internal set {}} protected internal sealed int P200 {get {System.Console.WriteLine(""P200""); return 200;}} protected sealed int this[string P500] {set {System.Console.WriteLine(""P500"");}} protected internal sealed void M300() {System.Console.WriteLine(""M300"");} protected sealed event D1 E400 { add {System.Console.WriteLine(""add E400"");value();} remove {System.Console.WriteLine(""remove E400"");value();} } sealed int P500 {protected get {System.Console.WriteLine(""P500""); return 500;} set {}} sealed int P600 {get {System.Console.WriteLine(""P600""); return 600;} protected internal set {}} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source3 = @" interface Test3 : I1 { static void Main() { Test3 i1 = null; System.Console.WriteLine(i1.P20); i1.M30(); i1.E40 += i1.M30; i1.E40 -= new D1(i1.M30); i1[50] = default; _ = i1.P50; _ = i1.P60; i1.P50 = 12; i1.P60 = 13; } } "; var source4 = @" interface Test4 : I1 { static void Main() { Test4 i1 = null; System.Console.WriteLine(i1.P200); i1.M300(); i1.E400 += i1.M300; i1.E400 -= new D1(i1.M300); i1[""500""] = default; _ = i1.P500; _ = i1.P600; i1.P500 = 12; i1.P600 = 13; } } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation3 = CreateCompilation(source3, options: TestOptions.DebugExe, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { reference }, parseOptions: TestOptions.Regular); compilation3.VerifyDiagnostics( // (4,17): error CS8701: Target runtime doesn't support default interface implementation. // static void Main() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "Main").WithLocation(4, 17), // (7,34): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // System.Console.WriteLine(i1.P20); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.P20").WithLocation(7, 34), // (8,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // i1.M30(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.M30").WithLocation(8, 9), // (9,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // i1.E40 += i1.M30; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.E40 += i1.M30").WithLocation(9, 9), // (9,19): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // i1.E40 += i1.M30; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.M30").WithLocation(9, 19), // (10,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // i1.E40 -= new D1(i1.M30); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.E40 -= new D1(i1.M30)").WithLocation(10, 9), // (10,26): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // i1.E40 -= new D1(i1.M30); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.M30").WithLocation(10, 26), // (11,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // i1[50] = default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1[50]").WithLocation(11, 9), // (12,13): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // _ = i1.P50; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.P50").WithLocation(12, 13), // (15,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // i1.P60 = 13; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.P60").WithLocation(15, 9) ); var compilation4 = CreateCompilation(source4, options: TestOptions.DebugExe, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { reference }, parseOptions: TestOptions.Regular); Assert.False(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics( // (4,17): error CS8701: Target runtime doesn't support default interface implementation. // static void Main() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "Main").WithLocation(4, 17), // (7,34): error CS8701: Target runtime doesn't support default interface implementation. // System.Console.WriteLine(i1.P200); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.P200").WithLocation(7, 34), // (8,9): error CS8701: Target runtime doesn't support default interface implementation. // i1.M300(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.M300").WithLocation(8, 9), // (9,9): error CS8701: Target runtime doesn't support default interface implementation. // i1.E400 += i1.M300; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.E400 += i1.M300").WithLocation(9, 9), // (9,20): error CS8701: Target runtime doesn't support default interface implementation. // i1.E400 += i1.M300; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.M300").WithLocation(9, 20), // (10,9): error CS8701: Target runtime doesn't support default interface implementation. // i1.E400 -= new D1(i1.M300); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.E400 -= new D1(i1.M300)").WithLocation(10, 9), // (10,27): error CS8701: Target runtime doesn't support default interface implementation. // i1.E400 -= new D1(i1.M300); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.M300").WithLocation(10, 27), // (11,9): error CS8701: Target runtime doesn't support default interface implementation. // i1["500"] = default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, @"i1[""500""]").WithLocation(11, 9), // (12,13): error CS8701: Target runtime doesn't support default interface implementation. // _ = i1.P500; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.P500").WithLocation(12, 13), // (13,13): error CS8701: Target runtime doesn't support default interface implementation. // _ = i1.P600; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.P600").WithLocation(13, 13), // (14,9): error CS8701: Target runtime doesn't support default interface implementation. // i1.P500 = 12; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.P500").WithLocation(14, 9), // (15,9): error CS8701: Target runtime doesn't support default interface implementation. // i1.P600 = 13; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.P600").WithLocation(15, 9) ); } } [Fact] public void UnsupportedMemberAccess_04() { var source1 = @" public interface I1 { protected interface I2 {} protected internal interface I3 {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source3 = @" interface Test3 : I1 { class C { static void M1(I1.I2 x) { System.Console.WriteLine(""M1""); } static void M2(I1.I3 x) { System.Console.WriteLine(""M2""); } static void Main() { M1(null); M2(null); } } } "; var source4 = @" class Test4 : I1 { interface Test5 : I1.I2 { } interface Test6 : I1.I3 { } } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation3 = CreateCompilation(source3, options: TestOptions.DebugExe, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { reference }, parseOptions: TestOptions.Regular); compilation3.VerifyDiagnostics( // (6,27): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // static void M1(I1.I2 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I2").WithLocation(6, 27), // (11,27): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // static void M2(I1.I3 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I3").WithLocation(11, 27) ); var compilation4 = CreateCompilation(source4, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { reference }, parseOptions: TestOptions.Regular); compilation4.VerifyDiagnostics( // (4,26): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // interface Test5 : I1.I2 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I2").WithLocation(4, 26), // (8,26): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // interface Test6 : I1.I3 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I3").WithLocation(8, 26) ); } } [Fact] public void EntryPoint_01() { var source1 = @" public interface I1 { static void Main() { System.Console.WriteLine(""I1.Main""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "I1.Main"); } [Fact] public void EntryPoint_02() { var source1 = @" public interface I1 { static void Main() { System.Console.WriteLine(""I1.Main""); } } public interface I2 { static void Main() { System.Console.WriteLine(""I2.Main""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMainTypeName("I2"), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "I2.Main"); } [Fact] public void Operators_01() { var source1 = @" public interface I1 { public static I1 operator +(I1 x) { System.Console.WriteLine(""+""); return x; } public static I1 operator -(I1 x) { System.Console.WriteLine(""-""); return x; } public static I1 operator !(I1 x) { System.Console.WriteLine(""!""); return x; } public static I1 operator ~(I1 x) { System.Console.WriteLine(""~""); return x; } public static I1 operator ++(I1 x) { System.Console.WriteLine(""++""); return x; } public static I1 operator --(I1 x) { System.Console.WriteLine(""--""); return x; } public static bool operator true(I1 x) { System.Console.WriteLine(""true""); return true; } public static bool operator false(I1 x) { System.Console.WriteLine(""false""); return false; } public static I1 operator +(I1 x, I1 y) { System.Console.WriteLine(""+2""); return x; } public static I1 operator -(I1 x, I1 y) { System.Console.WriteLine(""-2""); return x; } public static I1 operator *(I1 x, I1 y) { System.Console.WriteLine(""*""); return x; } public static I1 operator /(I1 x, I1 y) { System.Console.WriteLine(""/""); return x; } public static I1 operator %(I1 x, I1 y) { System.Console.WriteLine(""%""); return x; } public static I1 operator &(I1 x, I1 y) { System.Console.WriteLine(""&""); return x; } public static I1 operator |(I1 x, I1 y) { System.Console.WriteLine(""|""); return x; } public static I1 operator ^(I1 x, I1 y) { System.Console.WriteLine(""^""); return x; } public static I1 operator <<(I1 x, int y) { System.Console.WriteLine(""<<""); return x; } public static I1 operator >>(I1 x, int y) { System.Console.WriteLine("">>""); return x; } public static I1 operator >(I1 x, I1 y) { System.Console.WriteLine("">""); return x; } public static I1 operator <(I1 x, I1 y) { System.Console.WriteLine(""<""); return x; } public static I1 operator >=(I1 x, I1 y) { System.Console.WriteLine("">=""); return x; } public static I1 operator <=(I1 x, I1 y) { System.Console.WriteLine(""<=""); return x; } } "; var source2 = @" class Test2 : I1 { static void Main() { I1 x = new Test2(); I1 y = new Test2(); x = +x; x = -x; x = !x; x = ~x; x = ++x; x = x--; x = x + y; x = x - y; x = x * y; x = x / y; x = x % y; if (x && y) { } x = x | y; x = x ^ y; x = x << 1; x = x >> 2; x = x > y; x = x < y; x = x >= y; x = x <= y; } } "; var expectedOutput = @" + - ! ~ ++ -- +2 -2 * / % false & true | ^ << >> > < >= <= "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr); var compilation6 = CreateCompilation(source1 + source2, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular7_3); compilation6.VerifyDiagnostics( // (4,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator +(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "+").WithArguments("default interface implementation", "8.0").WithLocation(4, 31), // (10,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator -(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(10, 31), // (16,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator !(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "!").WithArguments("default interface implementation", "8.0").WithLocation(16, 31), // (22,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator ~(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "~").WithArguments("default interface implementation", "8.0").WithLocation(22, 31), // (28,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator ++(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "++").WithArguments("default interface implementation", "8.0").WithLocation(28, 31), // (34,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator --(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "--").WithArguments("default interface implementation", "8.0").WithLocation(34, 31), // (40,33): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static bool operator true(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "true").WithArguments("default interface implementation", "8.0").WithLocation(40, 33), // (46,33): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static bool operator false(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "false").WithArguments("default interface implementation", "8.0").WithLocation(46, 33), // (52,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator +(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "+").WithArguments("default interface implementation", "8.0").WithLocation(52, 31), // (58,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator -(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(58, 31), // (64,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator *(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "*").WithArguments("default interface implementation", "8.0").WithLocation(64, 31), // (70,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator /(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "/").WithArguments("default interface implementation", "8.0").WithLocation(70, 31), // (76,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator %(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "%").WithArguments("default interface implementation", "8.0").WithLocation(76, 31), // (82,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator &(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "&").WithArguments("default interface implementation", "8.0").WithLocation(82, 31), // (88,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator |(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "|").WithArguments("default interface implementation", "8.0").WithLocation(88, 31), // (94,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator ^(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "^").WithArguments("default interface implementation", "8.0").WithLocation(94, 31), // (100,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator <<(I1 x, int y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "<<").WithArguments("default interface implementation", "8.0").WithLocation(100, 31), // (106,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator >>(I1 x, int y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, ">>").WithArguments("default interface implementation", "8.0").WithLocation(106, 31), // (112,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator >(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, ">").WithArguments("default interface implementation", "8.0").WithLocation(112, 31), // (118,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator <(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "<").WithArguments("default interface implementation", "8.0").WithLocation(118, 31), // (124,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator >=(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, ">=").WithArguments("default interface implementation", "8.0").WithLocation(124, 31), // (130,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator <=(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "<=").WithArguments("default interface implementation", "8.0").WithLocation(130, 31) ); var compilation61 = CreateCompilation(source1 + source2, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); compilation61.VerifyDiagnostics( // (4,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator +(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "+").WithLocation(4, 31), // (10,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator -(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "-").WithLocation(10, 31), // (16,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator !(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "!").WithLocation(16, 31), // (22,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator ~(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "~").WithLocation(22, 31), // (28,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator ++(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "++").WithLocation(28, 31), // (34,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator --(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "--").WithLocation(34, 31), // (40,33): error CS8701: Target runtime doesn't support default interface implementation. // public static bool operator true(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "true").WithLocation(40, 33), // (46,33): error CS8701: Target runtime doesn't support default interface implementation. // public static bool operator false(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "false").WithLocation(46, 33), // (52,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator +(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "+").WithLocation(52, 31), // (58,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator -(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "-").WithLocation(58, 31), // (64,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator *(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "*").WithLocation(64, 31), // (70,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator /(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "/").WithLocation(70, 31), // (76,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator %(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "%").WithLocation(76, 31), // (82,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator &(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "&").WithLocation(82, 31), // (88,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator |(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "|").WithLocation(88, 31), // (94,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator ^(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "^").WithLocation(94, 31), // (100,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator <<(I1 x, int y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "<<").WithLocation(100, 31), // (106,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator >>(I1 x, int y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, ">>").WithLocation(106, 31), // (112,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator >(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, ">").WithLocation(112, 31), // (118,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator <(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "<").WithLocation(118, 31), // (124,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator >=(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, ">=").WithLocation(124, 31), // (130,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator <=(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "<=").WithLocation(130, 31) ); var compilation7 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular7_3); var expected7 = new DiagnosticDescription[] { // (9,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = +x; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "+x").WithArguments("default interface implementation", "8.0").WithLocation(9, 13), // (10,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = -x; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-x").WithArguments("default interface implementation", "8.0").WithLocation(10, 13), // (11,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = !x; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "!x").WithArguments("default interface implementation", "8.0").WithLocation(11, 13), // (12,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = ~x; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "~x").WithArguments("default interface implementation", "8.0").WithLocation(12, 13), // (13,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = ++x; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "++x").WithArguments("default interface implementation", "8.0").WithLocation(13, 13), // (14,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x--; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x--").WithArguments("default interface implementation", "8.0").WithLocation(14, 13), // (16,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x + y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x + y").WithArguments("default interface implementation", "8.0").WithLocation(16, 13), // (17,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x - y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x - y").WithArguments("default interface implementation", "8.0").WithLocation(17, 13), // (18,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x * y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x * y").WithArguments("default interface implementation", "8.0").WithLocation(18, 13), // (19,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x / y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x / y").WithArguments("default interface implementation", "8.0").WithLocation(19, 13), // (20,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x % y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x % y").WithArguments("default interface implementation", "8.0").WithLocation(20, 13), // (21,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // if (x && y) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x && y").WithArguments("default interface implementation", "8.0").WithLocation(21, 13), // (21,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // if (x && y) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x && y").WithArguments("default interface implementation", "8.0").WithLocation(21, 13), // (22,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x | y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x | y").WithArguments("default interface implementation", "8.0").WithLocation(22, 13), // (23,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x ^ y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x ^ y").WithArguments("default interface implementation", "8.0").WithLocation(23, 13), // (24,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x << 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x << 1").WithArguments("default interface implementation", "8.0").WithLocation(24, 13), // (25,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x >> 2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x >> 2").WithArguments("default interface implementation", "8.0").WithLocation(25, 13), // (26,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x > y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x > y").WithArguments("default interface implementation", "8.0").WithLocation(26, 13), // (27,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x < y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x < y").WithArguments("default interface implementation", "8.0").WithLocation(27, 13), // (28,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x >= y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x >= y").WithArguments("default interface implementation", "8.0").WithLocation(28, 13), // (29,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x <= y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x <= y").WithArguments("default interface implementation", "8.0").WithLocation(29, 13) }; compilation7.VerifyDiagnostics(expected7); var compilation8 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular7_3); compilation8.VerifyDiagnostics(expected7); var source3 = @" class Test3 : I1 { static void Main() { I1 x = new Test3(); I1 y = new Test3(); if (x) { } x = x & y; } } "; var compilation9 = CreateCompilation(source3, new[] { compilationReference }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular7_3); var expected9 = new DiagnosticDescription[] { // (8,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // if (x) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x").WithArguments("default interface implementation", "8.0").WithLocation(8, 13), // (9,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x & y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x & y").WithArguments("default interface implementation", "8.0").WithLocation(9, 13) }; compilation9.VerifyDiagnostics(expected9); var compilation10 = CreateCompilation(source3, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation10.VerifyDiagnostics(expected9); } [Fact] public void Operators_02() { var source1 = @" public class C1 { public static int operator +(C1 x, I1 y) { System.Console.WriteLine(""C1.+""); return 0; } public static int operator -(I1 x, C1 y) { System.Console.WriteLine(""C1.-""); return 0; } } public class C2 : C1 {} class Test : I1 { static void Main() { I1 x = new Test(); C2 y = new C2(); var r = y + x; r = x - y; } } "; var source2 = @" public interface I1 { } "; var source3 = @" public interface I1 { public static int operator +(C2 x, I1 y) { System.Console.WriteLine(""I1.+""); return 0; } public static int operator -(I1 x, C2 y) { System.Console.WriteLine(""I1.-""); return 0; } } "; var expectedOutput = @" C1.+ C1.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr); var compilation2 = CreateCompilation(source1 + source3, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr); } [Fact] public void Operators_03() { var source1 = @" public interface I1 { public static I1 operator ==(I1 x, I1 y) { System.Console.WriteLine(""==""); return x; } public static I1 operator !=(I1 x, I1 y) { System.Console.WriteLine(""!=""); return x; } } "; var source2 = @" class Test2 : I1 { static void Main() { I1 x = new Test2(); I1 y = new Test2(); x = x == y; x = x != y; } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular9); compilation1.VerifyDiagnostics( // (4,31): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // public static I1 operator ==(I1 x, I1 y) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(4, 31), // (10,31): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // public static I1 operator !=(I1 x, I1 y) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(10, 31), // (24,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x = x == y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x == y").WithArguments("static abstract members in interfaces").WithLocation(24, 13), // (25,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x = x != y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x != y").WithArguments("static abstract members in interfaces").WithLocation(25, 13) ); CreateCompilation(source1 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (4,31): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // public static I1 operator ==(I1 x, I1 y) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(4, 31), // (10,31): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // public static I1 operator !=(I1 x, I1 y) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(10, 31) ); CompilationReference compilationReference = compilation1.ToMetadataReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (9,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x = x == y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x == y").WithArguments("static abstract members in interfaces").WithLocation(9, 13), // (10,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x = x != y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x != y").WithArguments("static abstract members in interfaces").WithLocation(10, 13) ); var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig specialname static class I1 op_Equality(class I1 x, class I1 y) cil managed { // Code size 18 (0x12) .maxstack 1 .locals init (class I1 V_0) IL_0000: nop IL_0001: ldstr ""=="" IL_0006: call void [mscorlib]System.Console::WriteLine(string) IL_000b: nop IL_000c: ldarg.0 IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } // end of method I1::op_Equality .method public hidebysig specialname static class I1 op_Inequality(class I1 x, class I1 y) cil managed { // Code size 18 (0x12) .maxstack 1 .locals init (class I1 V_0) IL_0000: nop IL_0001: ldstr ""!="" IL_0006: call void [mscorlib]System.Console::WriteLine(string) IL_000b: nop IL_000c: ldarg.0 IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } // end of method I1::op_Inequality } // end of class I1 "; var compilation3 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" == != ").VerifyDiagnostics(); CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (9,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x = x == y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x == y").WithArguments("static abstract members in interfaces").WithLocation(9, 13), // (10,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x = x != y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x != y").WithArguments("static abstract members in interfaces").WithLocation(10, 13) ); var source3 = @" class Test2 : I1 { static void Main() { I1 x = new Test2(); I1 y = new Test2(); System.Console.WriteLine(x == y); System.Console.WriteLine(x != y); } } "; var compilation4 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); compilation4.VerifyDiagnostics(); CompileAndVerify(compilation4, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" == Test2 != Test2 "); CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (9,34): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // System.Console.WriteLine(x == y); Diagnostic(ErrorCode.ERR_FeatureInPreview, "x == y").WithArguments("static abstract members in interfaces").WithLocation(9, 34), // (10,34): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // System.Console.WriteLine(x != y); Diagnostic(ErrorCode.ERR_FeatureInPreview, "x != y").WithArguments("static abstract members in interfaces").WithLocation(10, 34) ); } [Fact] public void Operators_04() { var source1 = @" public interface I1 { public static implicit operator int(I1 x) { return 0; } public static explicit operator byte(I1 x) { return 0; } public static void Test(I1 x) { int y = x; y = (int)x; var z = (byte)x; z = x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (4,37): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // public static implicit operator int(I1 x) Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 37), // (4,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // public static implicit operator int(I1 x) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(4, 37), // (8,37): error CS0552: 'I1.explicit operator byte(I1)': user-defined conversions to or from an interface are not allowed // public static explicit operator byte(I1 x) Diagnostic(ErrorCode.ERR_ConversionWithInterface, "byte").WithArguments("I1.explicit operator byte(I1)").WithLocation(8, 37), // (8,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // public static explicit operator byte(I1 x) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "byte").WithLocation(8, 37), // (15,17): error CS0029: Cannot implicitly convert type 'I1' to 'int' // int y = x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("I1", "int").WithLocation(15, 17), // (16,13): error CS0030: Cannot convert type 'I1' to 'int' // y = (int)x; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int)x").WithArguments("I1", "int").WithLocation(16, 13), // (17,17): error CS0030: Cannot convert type 'I1' to 'byte' // var z = (byte)x; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(byte)x").WithArguments("I1", "byte").WithLocation(17, 17), // (18,13): error CS0029: Cannot implicitly convert type 'I1' to 'byte' // z = x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("I1", "byte").WithLocation(18, 13) ); } [Fact] public void Operators_05() { var source1 = @" public interface I1 { public static I1 operator -(I1 x) { System.Console.WriteLine(""-""); return x; } } public interface I2 : I1 {} "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); I1 y = -x; } } "; var expectedOutput = @" - "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var source3 = @" class Test2 : I2 { static void Main() { Test2 x = new Test2(); I1 y = -x; } } "; var compilation9 = CreateCompilation(source3, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); var expected9 = new DiagnosticDescription[] { // (8,16): error CS0023: Operator '-' cannot be applied to operand of type 'Test2' // I1 y = -x; Diagnostic(ErrorCode.ERR_BadUnaryOp, "-x").WithArguments("-", "Test2").WithLocation(8, 16) }; compilation9.VerifyDiagnostics(expected9); var compilation10 = CreateCompilation(source3, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation10.VerifyDiagnostics(expected9); } [Fact] public void Operators_06() { var source1 = @" public interface I1 { public static I1 operator -(I1 x) { System.Console.WriteLine(""I1.-""); return x; } } public interface I2 : I1 { public static I2 operator -(I2 x) { System.Console.WriteLine(""I2.-""); return x; } } "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); var y = -x; } } "; var expectedOutput = @" I2.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_07() { var source1 = @" public interface I1 { public static I1 operator -(I1 x) { System.Console.WriteLine(""I1.-""); return x; } } public interface I3 { public static I3 operator -(I3 x) { System.Console.WriteLine(""I3.-""); return x; } } public interface I4 : I1, I3 { public static I4 operator -(I4 x) { System.Console.WriteLine(""I4.-""); return x; } } public interface I2 : I4 { } "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); var y = -x; } } "; var expectedOutput = @" I4.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_08() { var source1 = @" public interface I1 { public static I1 operator -(I1 x) { System.Console.WriteLine(""I1.-""); return x; } } public interface I3 { public static I3 operator -(I3 x) { System.Console.WriteLine(""I3.-""); return x; } } public interface I4 : I1, I3 { } public interface I2 : I4 { } "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); var y = -x; } } "; var expected = new DiagnosticDescription[] { // (7,17): error CS0035: Operator '-' is ambiguous on an operand of type 'I2' // var y = -x; Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "-x").WithArguments("-", "I2").WithLocation(7, 17) }; var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(expected); CompilationReference compilationReference = compilation1.ToMetadataReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); } [Fact] public void Operators_09() { var source1 = @" public interface I1 { public static I1 operator -(I1 x) { System.Console.WriteLine(""I1.-""); return x; } } "; var source2 = @" class Test1 : Test2, I1 {} class Test2 { static void Main() { Test(new Test1()); } static void Test<T>(T x) where T : Test2, I1 { var y = -x; } public static Test2 operator -(Test2 x) { System.Console.WriteLine(""Test2.-""); return x; } } "; var expectedOutput = @" Test2.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_10() { var source1 = @" public interface I1 { public static I1 operator -(I1 x) { System.Console.WriteLine(""I1.-""); return x; } } public interface I3 { public static I3 operator -(I3 x) { System.Console.WriteLine(""I3.-""); return x; } } public interface I4 : I1, I3 { public static I4 operator -(I4 x) { System.Console.WriteLine(""I4.-""); return x; } } public interface I2 : I4 { }"; var source2 = @" class Test1 : Test2, I2 {} class Test2 { static void Main() { Test(new Test1()); } static void Test<T>(T x) where T : Test2, I2 { var y = -x; } } "; var expectedOutput = @" I4.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_11() { var source0 = @" public interface I1 { } public interface I2 { } "; var source1 = @" public class C1 { public static C1 operator +(C1 x, I2 y) { System.Console.WriteLine(""C1.+1""); return x; } public static C1 operator +(C1 x, I1 y) { System.Console.WriteLine(""C1.+2""); return x; } } "; var source2 = @" public interface I3 : I1, I2 { } "; var source3 = @" class Test2 : I3 { static void Main() { I3 x = new Test2(); var y = new C1() + x; } } "; var expected = new DiagnosticDescription[] { // (7,17): error CS0034: Operator '+' is ambiguous on operands of type 'C1' and 'I3' // var y = new C1() + x; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "new C1() + x").WithArguments("+", "C1", "I3").WithLocation(7, 17) }; var compilation0 = CreateCompilation(source0 + source1 + source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); CompilationReference compilationReference0 = compilation0.ToMetadataReference(); MetadataReference metadataReference0 = compilation0.EmitToImageReference(); var compilation1 = CreateCompilation(source3, new[] { compilationReference0 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source3, new[] { metadataReference0 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); var source4 = @" public interface I1 { public static C1 operator +(C1 x, I1 y) { System.Console.WriteLine(""I1.+""); return x; } } public interface I2 { } "; var compilation3 = CreateCompilation(source4 + source1 + source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompilationReference compilationReference3 = compilation3.ToMetadataReference(); MetadataReference metadataReference3 = compilation3.EmitToImageReference(); var compilation4 = CreateCompilation(source3, new[] { compilationReference3 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics(expected); var compilation5 = CreateCompilation(source3, new[] { metadataReference3 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics(expected); var source5 = @" public interface I3 : I1, I2 { public static C1 operator +(C1 x, I3 y) { System.Console.WriteLine(""I3.+""); return x; } } "; var compilation6 = CreateCompilation(source4 + source1 + source5, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics(); CompilationReference compilationReference6 = compilation6.ToMetadataReference(); MetadataReference metadataReference6 = compilation6.EmitToImageReference(); var compilation7 = CreateCompilation(source3, new[] { compilationReference6 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics(expected); var compilation8 = CreateCompilation(source3, new[] { metadataReference6 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation8.VerifyDiagnostics(expected); } [Fact] public void Operators_12() { var source0 = @" public interface I1 { } public interface I2 { } "; var source1 = @" public class C1 { public static C1 operator +(I2 x, C1 y) { System.Console.WriteLine(""C1.+1""); return y; } public static C1 operator +(I1 x, C1 y) { System.Console.WriteLine(""C1.+2""); return y; } } "; var source2 = @" public interface I3 : I1, I2 { } "; var source3 = @" class Test2 : I3 { static void Main() { I3 x = new Test2(); var y = x + new C1(); } } "; var expected = new DiagnosticDescription[] { // (7,17): error CS0034: Operator '+' is ambiguous on operands of type 'I3' and 'C1' // var y = x + new C1(); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x + new C1()").WithArguments("+", "I3", "C1").WithLocation(7, 17) }; var compilation0 = CreateCompilation(source0 + source1 + source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); CompilationReference compilationReference0 = compilation0.ToMetadataReference(); MetadataReference metadataReference0 = compilation0.EmitToImageReference(); var compilation1 = CreateCompilation(source3, new[] { compilationReference0 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source3, new[] { metadataReference0 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); var source4 = @" public interface I1 { public static C1 operator +(I1 x, C1 y) { System.Console.WriteLine(""I1.+""); return y; } } public interface I2 { } "; var compilation3 = CreateCompilation(source4 + source1 + source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompilationReference compilationReference3 = compilation3.ToMetadataReference(); MetadataReference metadataReference3 = compilation3.EmitToImageReference(); var compilation4 = CreateCompilation(source3, new[] { compilationReference3 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics(expected); var compilation5 = CreateCompilation(source3, new[] { metadataReference3 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics(expected); var source5 = @" public interface I3 : I1, I2 { public static C1 operator +(I3 x, C1 y) { System.Console.WriteLine(""I3.+""); return y; } } "; var compilation6 = CreateCompilation(source4 + source1 + source5, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics(); CompilationReference compilationReference6 = compilation6.ToMetadataReference(); MetadataReference metadataReference6 = compilation6.EmitToImageReference(); var compilation7 = CreateCompilation(source3, new[] { compilationReference6 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics(expected); var compilation8 = CreateCompilation(source3, new[] { metadataReference6 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation8.VerifyDiagnostics(expected); } [Fact] public void Operators_13() { var source1 = @" public interface I1 { public static int operator +(I1 x, I2 y) { System.Console.WriteLine(""I1.+""); return 1; } } public interface I2 { public static int operator +(I1 x, I2 y) { System.Console.WriteLine(""I2.+""); return 2; } } "; var source2 = @" class Test2: I1, I2 { static void Main() { I1 x = new Test2(); I2 y = new Test2(); var z = x + y; z = y + x; } } "; var expected = new DiagnosticDescription[] { // (8,17): error CS0034: Operator '+' is ambiguous on operands of type 'I1' and 'I2' // var z = x + y; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x + y").WithArguments("+", "I1", "I2").WithLocation(8, 17), // (9,13): error CS0019: Operator '+' cannot be applied to operands of type 'I2' and 'I1' // z = y + x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "y + x").WithArguments("+", "I2", "I1").WithLocation(9, 13) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(expected); } [Fact] public void Operators_14() { var source1 = @" public interface I1 { public static int operator +(I2 x, I1 y) { System.Console.WriteLine(""I1.+""); return 1; } } public interface I2 : I1 { public static int operator +(I2 x, I1 y) { System.Console.WriteLine(""I2.+""); return 2; } } "; var source2 = @" class Test2 : I2 { static void Main() { I1 x = new Test2(); I2 y = new Test2(); var z = y + x; z = x + y; } } "; var expected = new DiagnosticDescription[] { // (8,17): error CS0034: Operator '+' is ambiguous on operands of type 'I2' and 'I1' // var z = y + x; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "y + x").WithArguments("+", "I2", "I1").WithLocation(8, 17), // (9,13): error CS0019: Operator '+' cannot be applied to operands of type 'I1' and 'I2' // z = x + y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x + y").WithArguments("+", "I1", "I2").WithLocation(9, 13) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(expected); } [Fact] public void Operators_15() { var source1 = @" public class I1 { public static int operator +(I1 x, C2 y) { System.Console.WriteLine(""I1.+1""); return 1; } public static int operator +(C2 x, I1 y) { System.Console.WriteLine(""I1.+2""); return 1; } } public class I2 : I1 { public static int operator +(I2 x, C1 y) { System.Console.WriteLine(""I2.+1""); return 1; } public static int operator +(C1 x, I2 y) { System.Console.WriteLine(""I2.+2""); return 1; } } public class C1 { } public class C2 : C1 { } "; var source2 = @" class Test2: I2 { static void Main() { I2 x = new Test2(); C2 y = new C2(); var z = x + y; z = y + x; } } "; var expectedOutput = @" I2.+1 I2.+2 "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_16() { var source1 = @" public interface I1<T> { public static int operator +(I1<T> x, I1<T> y) { System.Console.WriteLine(""I1.+""); return 1; } } "; var source2 = @" class Test2: I1<object> { static void Main() { I1<object> x = new Test2(); I1<dynamic> y = new Test2(); var z = x + y; z = y + x; } } "; var expectedOutput = @" I1.+ I1.+ "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_17() { var source1 = @" public interface I1 { public static I1 operator +(I1 x, C1 y) { System.Console.WriteLine(""I1.+1""); return x; } public static I1 operator +(C1 x, I1 y) { System.Console.WriteLine(""I1.+2""); return y; } } public interface I2 : I1 {} public class C1{} "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); C1 y = new C1(); var z = x + y; z = y + x; } } "; var expectedOutput = @" I1.+1 I1.+2 "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var source3 = @" class Test2 : I2 { static void Main() { Test2 x = new Test2(); C1 y = new C1(); var z = x + y; z = y + x; } } "; var compilation9 = CreateCompilation(source3, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); var expected9 = new DiagnosticDescription[] { // (8,17): error CS0019: Operator '+' cannot be applied to operands of type 'Test2' and 'C1' // var z = x + y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x + y").WithArguments("+", "Test2", "C1").WithLocation(8, 17), // (9,13): error CS0019: Operator '+' cannot be applied to operands of type 'C1' and 'Test2' // z = y + x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "y + x").WithArguments("+", "C1", "Test2").WithLocation(9, 13) }; compilation9.VerifyDiagnostics(expected9); var compilation10 = CreateCompilation(source3, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation10.VerifyDiagnostics(expected9); } [Fact] public void Operators_18() { var source1 = @" public interface I1 { public static int operator +(I1 x, I1 y) { System.Console.WriteLine(""I1.+""); return 1; } } public interface I2 : I1 {} "; var source2 = @" class Test2: I2 { static void Main() { I2 x = new Test2(); I1 y = new Test2(); var z = x + y; z = y + x; z = x + x; z = y + y; } } "; var expectedOutput = @" I1.+ I1.+ I1.+ I1.+ "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_19() { var source1 = @" public interface I1<T> { public static int operator +(I1<T> x, I1<T> y) { System.Console.WriteLine(""I1.+""); return 1; } } public interface I2<T> : I1<T> {} "; var source2 = @" class Test2: I2<object> { static void Main() { I2<object> x = new Test2(); I2<dynamic> y = new Test2(); var z = x + y; z = y + x; I1<object> u = x; I1<dynamic> v = y; z = y + u; z = u + y; z = x + v; z = v + x; } } "; var expectedOutput = @" I1.+ I1.+ I1.+ I1.+ I1.+ I1.+ "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_20() { var source1 = @" public interface I1 { public static I1 operator -(I1 x, I2 y) { System.Console.WriteLine(""I1.-""); return x; } } public interface I2 : I1 { public static I2 operator -(I1 x, I2 y) { System.Console.WriteLine(""I2.-""); return y; } } "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); I2 y = new Test2(); var z = x - y; } } "; var expectedOutput = @" I2.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_21() { var source1 = @" public interface I1 { public static I1 operator -(I1 x, I2 y) { System.Console.WriteLine(""I1.-""); return x; } } public interface I2 : I1 { public static I2 operator -(I1 x, I2 y) { System.Console.WriteLine(""I2.-""); return y; } } public interface I3 : I2 {} public interface I4 : I2, I1 {} public interface I5 : I1, I2 {} "; var source2 = @" class Test2 : I3, I4, I5 { static void Main() { I3 x3 = new Test2(); I3 y3 = new Test2(); var z = x3 - y3; I4 x4 = new Test2(); I4 y4 = new Test2(); z = x4 - y4; I5 x5 = new Test2(); I5 y5 = new Test2(); z = x5 - y5; } } "; var expectedOutput = @" I2.- I2.- I2.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_22() { var source1 = @" public interface I1 { public static I1 operator -(I1 x, I2 y) { System.Console.WriteLine(""I1.-""); return x; } } public interface I2 : I1 { public static I2 operator -(I1 x, I2 y) { System.Console.WriteLine(""I2.-""); return y; } } public interface I3 : I2 {} public interface I4 : I3 {} "; var source2 = @" class Test2 : I3, I4 { static void Main() { I3 x = new Test2(); I4 y = new Test2(); var z = x - y; z = y - x; } } "; var expectedOutput = @" I2.- I2.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_23() { var source1 = @" public interface I1 { public static int operator +(I1 x, I2 y) { System.Console.WriteLine(""I1.+""); return 1; } } public interface I2 : I1 { public static int operator +(I1 x, I2 y) { System.Console.WriteLine(""I2.+""); return 2; } } public interface I3 : I2 {} "; var source2 = @" class Test2 : I3 { static void Main() { I1 x = new Test2(); I3 y = new Test2(); var z = x + y; z = y + x; } } "; var expected = new DiagnosticDescription[] { // (8,17): error CS0034: Operator '+' is ambiguous on operands of type 'I1' and 'I3' // var z = x + y; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x + y").WithArguments("+", "I1", "I3").WithLocation(8, 17), // (9,13): error CS0019: Operator '+' cannot be applied to operands of type 'I3' and 'I1' // z = y + x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "y + x").WithArguments("+", "I3", "I1").WithLocation(9, 13) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(expected); } [Fact] public void Operators_24() { var source1 = @" public interface I1 { public static int operator +(I2 x, I1 y) { System.Console.WriteLine(""I1.+""); return 1; } } public interface I2 : I1 { public static int operator +(I2 x, I1 y) { System.Console.WriteLine(""I2.+""); return 2; } } public interface I3 : I2 {} "; var source2 = @" class Test2 : I3 { static void Main() { I1 x = new Test2(); I3 y = new Test2(); var z = y + x; z = x + y; } } "; var expected = new DiagnosticDescription[] { // (8,17): error CS0034: Operator '+' is ambiguous on operands of type 'I3' and 'I1' // var z = y + x; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "y + x").WithArguments("+", "I3", "I1").WithLocation(8, 17), // (9,13): error CS0019: Operator '+' cannot be applied to operands of type 'I1' and 'I3' // z = x + y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x + y").WithArguments("+", "I1", "I3").WithLocation(9, 13) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(expected); } [Fact] public void Operators_25() { var source1 = @" public interface I1 { public static I1 operator -(I1 x, I1 y) { System.Console.WriteLine(""I1.-""); return x; } } public interface I3 { public static I3 operator -(I3 x, I3 y) { System.Console.WriteLine(""I3.-""); return x; } } public interface I4 : I1, I3 { } public interface I2 : I4 { } "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); var y = x - x; } } "; var expected = new DiagnosticDescription[] { // (7,17): error CS0034: Operator '-' is ambiguous on operands of type 'I2' and 'I2' // var y = x - x; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x - x").WithArguments("-", "I2", "I2").WithLocation(7, 17) }; var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(expected); CompilationReference compilationReference = compilation1.ToMetadataReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); } [Fact] public void Operators_26() { var source1 = @" public interface I1 { public static I1 operator -(I1 x, C1 y) { System.Console.WriteLine(""I1.-1""); return x; } public static I1 operator -(C1 x, I1 y) { System.Console.WriteLine(""I1.-2""); return y; } } public interface I3 { public static I3 operator -(I3 x, C2 y) { System.Console.WriteLine(""I3.-1""); return x; } public static I3 operator -(C2 x, I3 y) { System.Console.WriteLine(""I3.-2""); return y; } } public interface I4 { public static I4 operator -(I4 x, C1 y) { System.Console.WriteLine(""I4.-1""); return x; } public static I4 operator -(C1 x, I4 y) { System.Console.WriteLine(""I4.-2""); return y; } } public interface I5 : I1, I3, I4 { } public interface I2 : I5 { } public class C1{} public class C2 : C1{} "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); var c = new C2(); var y = x - c; y = c - x; } } "; var expectedOutput = @" I3.-1 I3.-2 "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_27() { var source1 = @" public interface I1 { public static I1 operator -(I1 x, I1 y) { System.Console.WriteLine(""I1.-""); return x; } } "; var source2 = @" class Test1 : Test2, I1 {} class Test2 { static void Main() { Test(new Test1()); } static void Test<T>(T x) where T : Test2, I1 { var y = x - x; } public static Test2 operator -(Test2 x, Test2 y) { System.Console.WriteLine(""Test2.-""); return x; } } "; var expectedOutput = @" Test2.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_28() { var source1 = @" public interface I1 { public static I1 operator -(I1 x, C1 y) { System.Console.WriteLine(""I1.-1""); return x; } public static I1 operator -(C1 x, I1 y) { System.Console.WriteLine(""I1.-2""); return y; } } public interface I3 { public static I3 operator -(I3 x, C2 y) { System.Console.WriteLine(""I3.-1""); return x; } public static I3 operator -(C2 x, I3 y) { System.Console.WriteLine(""I3.-2""); return y; } } public interface I4 { public static I4 operator -(I4 x, C1 y) { System.Console.WriteLine(""I4.-1""); return x; } public static I4 operator -(C1 x, I4 y) { System.Console.WriteLine(""I4.-2""); return y; } } public interface I5 : I1, I3, I4 { } public interface I2 : I5 { } public class C1{} public class C2 : C1{} "; var source2 = @" class Test1 : Test2, I2 {} class Test2 { static void Main() { Test(new Test1()); } static void Test<T>(T x) where T : Test2, I2 { var c = new C2(); var y = c - x; y = x - c; } } "; var expectedOutput = @" I3.-2 I3.-1 "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_29() { var source1 = @" public interface I1 { public static I1 operator +(int x) => throw null; public static I1 operator -(int x) => throw null; public static I1 operator !(int x) => throw null; public static I1 operator ~(int x) => throw null; public static I1 operator ++(int x) => throw null; public static I1 operator --(int x) => throw null; public static bool operator true(int x) => throw null; public static bool operator false(int x) => throw null; public static I1 operator +(int x, int y) => throw null; public static I1 operator -(int x, int y) => throw null; public static I1 operator *(int x, int y) => throw null; public static I1 operator /(int x, int y) => throw null; public static I1 operator %(int x, int y) => throw null; public static I1 operator &(int x, int y) => throw null; public static I1 operator |(int x, int y) => throw null; public static I1 operator ^(int x, int y) => throw null; public static I1 operator <<(int x, int y) => throw null; public static I1 operator >>(int x, int y) => throw null; public static I1 operator >(int x, int y) => throw null; public static I1 operator <(int x, int y) => throw null; public static I1 operator >=(int x, int y) => throw null; public static I1 operator <=(int x, int y) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,31): error CS0562: The parameter of a unary operator must be the containing type // public static I1 operator +(int x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "+").WithLocation(4, 31), // (5,31): error CS0562: The parameter of a unary operator must be the containing type // public static I1 operator -(int x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "-").WithLocation(5, 31), // (6,31): error CS0562: The parameter of a unary operator must be the containing type // public static I1 operator !(int x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "!").WithLocation(6, 31), // (7,31): error CS0562: The parameter of a unary operator must be the containing type // public static I1 operator ~(int x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "~").WithLocation(7, 31), // (8,31): error CS0559: The parameter type for ++ or -- operator must be the containing type // public static I1 operator ++(int x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, "++").WithLocation(8, 31), // (9,31): error CS0559: The parameter type for ++ or -- operator must be the containing type // public static I1 operator --(int x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, "--").WithLocation(9, 31), // (10,33): error CS0562: The parameter of a unary operator must be the containing type // public static bool operator true(int x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "true").WithLocation(10, 33), // (11,33): error CS0562: The parameter of a unary operator must be the containing type // public static bool operator false(int x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "false").WithLocation(11, 33), // (12,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator +(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "+").WithLocation(12, 31), // (13,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator -(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "-").WithLocation(13, 31), // (14,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator *(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "*").WithLocation(14, 31), // (15,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator /(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "/").WithLocation(15, 31), // (16,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator %(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "%").WithLocation(16, 31), // (17,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator &(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "&").WithLocation(17, 31), // (18,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator |(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "|").WithLocation(18, 31), // (19,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator ^(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "^").WithLocation(19, 31), // (20,31): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static I1 operator <<(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, "<<").WithLocation(20, 31), // (21,31): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static I1 operator >>(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, ">>").WithLocation(21, 31), // (22,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator >(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, ">").WithLocation(22, 31), // (23,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator <(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "<").WithLocation(23, 31), // (24,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator >=(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, ">=").WithLocation(24, 31), // (25,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator <=(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "<=").WithLocation(25, 31) ); } [Fact] public void Operators_30() { var source1 = @" public interface I1 { public static I1 operator <<(I1 x, I1 y) => throw null; public static I1 operator >>(I1 x, I1 y) => throw null; } public interface I2 { public static bool operator true(I2 x) => throw null; } public interface I3 { public static bool operator false(I3 x) => throw null; } public interface I4 { public static int operator true(I4 x) => throw null; public static int operator false(I4 x) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,31): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static I1 operator <<(I1 x, I1 y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, "<<").WithLocation(4, 31), // (5,31): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static I1 operator >>(I1 x, I1 y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, ">>").WithLocation(5, 31), // (10,33): error CS0216: The operator 'I2.operator true(I2)' requires a matching operator 'false' to also be defined // public static bool operator true(I2 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "true").WithArguments("I2.operator true(I2)", "false").WithLocation(10, 33), // (15,33): error CS0216: The operator 'I3.operator false(I3)' requires a matching operator 'true' to also be defined // public static bool operator false(I3 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "false").WithArguments("I3.operator false(I3)", "true").WithLocation(15, 33), // (20,32): error CS0215: The return type of operator True or False must be bool // public static int operator true(I4 x) => throw null; Diagnostic(ErrorCode.ERR_OpTFRetType, "true").WithLocation(20, 32), // (21,32): error CS0215: The return type of operator True or False must be bool // public static int operator false(I4 x) => throw null; Diagnostic(ErrorCode.ERR_OpTFRetType, "false").WithLocation(21, 32) ); } [Fact] public void Operators_31() { var source1 = @" public interface I1 { public static I1 operator -(I1 x) { System.Console.WriteLine(""I1.-""); return x; } } public interface I2 : I1 { public static I2 operator -(I2 x) { System.Console.WriteLine(""I2.-""); return x; } } public interface I3 : I2 {} public interface I4 : I2, I1 {} public interface I5 : I1, I2 {} "; var source2 = @" class Test2 : I3, I4, I5 { static void Main() { I3 x3 = new Test2(); var y = -x3; I4 x4 = new Test2(); y = -x4; I5 x5 = new Test2(); y = -x5; } } "; var expectedOutput = @" I2.- I2.- I2.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] [WorkItem(52202, "https://github.com/dotnet/roslyn/issues/52202")] public void Operators_32() { var source1 = @" public interface I1 { static I1 operator +(I1 x) { System.Console.WriteLine(""+""); return x; } static I1 operator -(I1 x) { System.Console.WriteLine(""-""); return x; } static I1 operator !(I1 x) { System.Console.WriteLine(""!""); return x; } static I1 operator ~(I1 x) { System.Console.WriteLine(""~""); return x; } static I1 operator ++(I1 x) { System.Console.WriteLine(""++""); return x; } static I1 operator --(I1 x) { System.Console.WriteLine(""--""); return x; } static bool operator true(I1 x) { System.Console.WriteLine(""true""); return true; } static bool operator false(I1 x) { System.Console.WriteLine(""false""); return false; } static I1 operator +(I1 x, I1 y) { System.Console.WriteLine(""+2""); return x; } static I1 operator -(I1 x, I1 y) { System.Console.WriteLine(""-2""); return x; } static I1 operator *(I1 x, I1 y) { System.Console.WriteLine(""*""); return x; } static I1 operator /(I1 x, I1 y) { System.Console.WriteLine(""/""); return x; } static I1 operator %(I1 x, I1 y) { System.Console.WriteLine(""%""); return x; } static I1 operator &(I1 x, I1 y) { System.Console.WriteLine(""&""); return x; } static I1 operator |(I1 x, I1 y) { System.Console.WriteLine(""|""); return x; } static I1 operator ^(I1 x, I1 y) { System.Console.WriteLine(""^""); return x; } static I1 operator <<(I1 x, int y) { System.Console.WriteLine(""<<""); return x; } static I1 operator >>(I1 x, int y) { System.Console.WriteLine("">>""); return x; } static I1 operator >(I1 x, I1 y) { System.Console.WriteLine("">""); return x; } static I1 operator <(I1 x, I1 y) { System.Console.WriteLine(""<""); return x; } static I1 operator >=(I1 x, I1 y) { System.Console.WriteLine("">=""); return x; } static I1 operator <=(I1 x, I1 y) { System.Console.WriteLine(""<=""); return x; } } "; var source2 = @" class Test2 : I1 { static void Main() { I1 x = new Test2(); I1 y = new Test2(); x = +x; x = -x; x = !x; x = ~x; x = ++x; x = x--; x = x + y; x = x - y; x = x * y; x = x / y; x = x % y; if (x && y) { } x = x | y; x = x ^ y; x = x << 1; x = x >> 2; x = x > y; x = x < y; x = x >= y; x = x <= y; } } "; var expectedOutput = @" + - ! ~ ++ -- +2 -2 * / % false & true | ^ << >> > < >= <= "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); var i1 = compilation1.GlobalNamespace.GetTypeMember("I1"); foreach (var member in i1.GetMembers()) { Assert.Equal(Accessibility.Public, member.DeclaredAccessibility); } CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(52202, "https://github.com/dotnet/roslyn/issues/52202")] public void Operators_33() { var source1 = @" public interface I1 { static implicit operator int(I1 x) { return 0; } static explicit operator byte(I1 x) { return 0; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); var i1 = compilation1.GlobalNamespace.GetTypeMember("I1"); foreach (var member in i1.GetMembers()) { Assert.Equal(Accessibility.Public, member.DeclaredAccessibility); } compilation1.VerifyDiagnostics( // (4,30): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // static implicit operator int(I1 x) Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 30), // (4,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static implicit operator int(I1 x) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(4, 30), // (9,30): error CS0552: 'I1.explicit operator byte(I1)': user-defined conversions to or from an interface are not allowed // static explicit operator byte(I1 x) Diagnostic(ErrorCode.ERR_ConversionWithInterface, "byte").WithArguments("I1.explicit operator byte(I1)").WithLocation(9, 30), // (9,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static explicit operator byte(I1 x) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "byte").WithLocation(9, 30) ); } [Fact] public void RuntimeFeature_01() { var compilation1 = CreateCompilation("", options: TestOptions.DebugDll, references: new[] { TestMetadata.Net461.mscorlib }, targetFramework: TargetFramework.Empty); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.False(compilation1.Assembly.CorLibrary.RuntimeSupportsDefaultInterfaceImplementation); } [Fact] public void RuntimeFeature_02() { var compilation1 = CreateCompilation("", options: TestOptions.DebugDll, references: new[] { NetCoreApp.SystemRuntime }, targetFramework: TargetFramework.Empty); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.True(compilation1.Assembly.CorLibrary.RuntimeSupportsDefaultInterfaceImplementation); } [Fact] public void RuntimeFeature_03() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { public static class RuntimeFeature { public const string DefaultImplementationsOfInterfaces = ""DefaultImplementationsOfInterfaces""; } } } "; AssertRuntimeFeatureTrue(source); } private static void AssertRuntimeFeatureTrue(string source) { var compilation1 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.Empty); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.Same(compilation1.Assembly, compilation1.Assembly.CorLibrary); foreach (var reference in new[] { compilation1.EmitToImageReference(), compilation1.ToMetadataReference() }) { var compilation2 = CreateCompilation("", options: TestOptions.DebugDll, references: new[] { reference }, targetFramework: TargetFramework.Empty); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.True(compilation2.Assembly.CorLibrary.RuntimeSupportsDefaultInterfaceImplementation); } } [Fact] public void RuntimeFeature_04() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { public static class RuntimeFeature { public const string DefaultImplementationsOfInterfaces = """"; } } } "; AssertRuntimeFeatureTrue(source); } [Fact] public void RuntimeFeature_05() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { public static class RuntimeFeature { public static string DefaultImplementationsOfInterfaces; } } } "; AssertRuntimeFeatureTrue(source); } [Fact] public void RuntimeFeature_06() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { public class RuntimeFeature { public const string DefaultImplementationsOfInterfaces = ""DefaultImplementationsOfInterfaces""; } } } "; AssertRuntimeFeatureFalse(source); } [Fact] public void RuntimeFeature_07() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { public static class RuntimeFeature { static string DefaultImplementationsOfInterfaces; } } } "; AssertRuntimeFeatureFalse(source); } private static void AssertRuntimeFeatureFalse(string source) { var compilation1 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.Empty); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.Same(compilation1.Assembly, compilation1.Assembly.CorLibrary); foreach (var reference in new[] { compilation1.EmitToImageReference(), compilation1.ToMetadataReference() }) { var compilation2 = CreateCompilation("", options: TestOptions.DebugDll, references: new[] { reference }, targetFramework: TargetFramework.Empty); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.False(compilation2.Assembly.CorLibrary.RuntimeSupportsDefaultInterfaceImplementation); } } [Fact] public void RuntimeFeature_08() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { public class RuntimeFeature { public string DefaultImplementationsOfInterfaces; } } } "; AssertRuntimeFeatureFalse(source); } [Fact] public void RuntimeFeature_09() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} public struct Int32 {} namespace Runtime.CompilerServices { public static class RuntimeFeature { public const int DefaultImplementationsOfInterfaces = 0; } } } "; AssertRuntimeFeatureFalse(source); } [Fact] public void RuntimeFeature_10() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { public static class RuntimeFeature { } } } "; AssertRuntimeFeatureFalse(source); } [Fact] public void RuntimeFeature_11() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { } } "; AssertRuntimeFeatureFalse(source); } [Fact] public void RuntimeFeature_12() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { static class RuntimeFeature { public const string DefaultImplementationsOfInterfaces = ""DefaultImplementationsOfInterfaces""; } } } "; AssertRuntimeFeatureFalse(source); } [Fact] public void RuntimeFeature_13() { var source = @" namespace System { namespace Runtime.CompilerServices { public static class RuntimeFeature { public const string DefaultImplementationsOfInterfaces = ""DefaultImplementationsOfInterfaces""; } } } "; var compilation1 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { TestMetadata.Net461.mscorlib }, targetFramework: TargetFramework.Empty); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.False(compilation1.Assembly.CorLibrary.RuntimeSupportsDefaultInterfaceImplementation); } [Fact] public void ProtectedAccessibility_01() { var source0 = @" interface I1 { sealed protected void M1() { System.Console.WriteLine(""M1""); } } "; var source1 = @" interface I2 : I1 { static void Test<T>(T x) where T : I2 { x.M1(); } } class A : I2 { static void Main() { I2.Test(new A()); } } "; var compilation0 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); var source2 = @" interface I2 : I1 { static void Test<T>(T x) where T : I1, I3 { x.M1(); } } interface I3 : I2 {} class A : I3 { static void Main() { I2.Test(new A()); } } "; var compilation1 = CreateCompilation(source0 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var verifier = CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); verifier.VerifyIL("I2.Test<T>", @" { // Code size 16 (0x10) .maxstack 1 IL_0000: nop IL_0001: ldarga.s V_0 IL_0003: constrained. ""T"" IL_0009: callvirt ""void I1.M1()"" IL_000e: nop IL_000f: ret } "); var source3 = @" interface I2 : I1 { static void Test<T>(T x) where T : I1 { x.M1(); } } "; var compilation2 = CreateCompilation(source0 + source3, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (14,11): error CS1540: Cannot access protected member 'I1.M1()' via a qualifier of type 'T'; the qualifier must be of type 'I2' (or derived from it) // x.M1(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M1").WithArguments("I1.M1()", "T", "I2").WithLocation(14, 11) ); } [Fact] public void ProtectedAccessibility_02() { var source0 = @" interface I1<T> { sealed protected void M1() { System.Console.WriteLine(""M1""); } static void Test(I1<int> x) { x.M1(); } } class A : I1<int> { static void Main() { I1<byte>.Test(new A()); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); } [Fact] public void ProtectedAccessibility_03() { var source0 = @" interface I1<T> { sealed protected void M1() { System.Console.WriteLine(""M1""); } } interface I3<T> : I1<T> {} "; var source1 = @" interface I2<T> : I3<T> { static void Test(I2<int> x) { x.M1(); } } class A : I2<int> { static void Main() { I2<byte>.Test(new A()); } } "; var compilation0 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); var source2 = @" interface I2<T> : I3<T> { static void Test(I4 x) { x.M1(); } } interface I4 : I2<int> {} class A : I4 { static void Main() { I2<byte>.Test(new A()); } } "; var compilation1 = CreateCompilation(source0 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); var source3 = @" interface I2<T> : I3<T> { static void Test(I3<int> x) { x.M1(); } static void Test(I1<int> y) { y.M1(); } } "; var compilation2 = CreateCompilation(source0 + source3, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (17,11): error CS1540: Cannot access protected member 'I1<int>.M1()' via a qualifier of type 'I3<int>'; the qualifier must be of type 'I2<T>' (or derived from it) // x.M1(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M1").WithArguments("I1<int>.M1()", "I3<int>", "I2<T>").WithLocation(17, 11), // (22,11): error CS1540: Cannot access protected member 'I1<int>.M1()' via a qualifier of type 'I1<int>'; the qualifier must be of type 'I2<T>' (or derived from it) // y.M1(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M1").WithArguments("I1<int>.M1()", "I1<int>", "I2<T>").WithLocation(22, 11) ); } [Fact] public void ProtectedAccessibility_04() { var source0 = @" interface I1 : I2 { sealed protected void M1() { } static void Test(I1 x) { x.M1(); } } interface I2 : I1 { static void Test(I2 y) { y.M1(); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(2, 11), // (13,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(13, 11), // (17,11): error CS1061: 'I2' does not contain a definition for 'M1' and no accessible extension method 'M1' accepting a first argument of type 'I2' could be found (are you missing a using directive or an assembly reference?) // y.M1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("I2", "M1").WithLocation(17, 11) ); } [Fact] public void ProtectedAccessibility_05() { var source0 = @" interface I1 : I2 { static protected void M2() { } static void Test() { I1.M2(); } } interface I2 : I1 { static void Test() { I1.M2(); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(2, 11), // (13,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(13, 11) ); } [Fact] public void ProtectedAccessibility_06() { var source0 = @" interface I1<T> { static protected void M1() { System.Console.WriteLine(""M1""); } } interface I3<T> : I1<T> {} "; var source1 = @" class I2<T> : I3<T> { public static void Test() { I1<int>.M1(); } } class A { static void Main() { I2<byte>.Test(); } } "; var compilation0 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); var source3 = @" class I2<T> { static void Test() { I3<T>.M1(); I1<T>.M1(); } } "; var compilation2 = CreateCompilation(source0 + source3, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (17,15): error CS0122: 'I1<T>.M1()' is inaccessible due to its protection level // I3<T>.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1<T>.M1()").WithLocation(17, 15), // (18,15): error CS0122: 'I1<T>.M1()' is inaccessible due to its protection level // I1<T>.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1<T>.M1()").WithLocation(18, 15) ); } [Fact] public void ProtectedAccessibility_07() { var source0 = @" interface I1<T> { static protected void M1() { System.Console.WriteLine(""M1""); } } class I3<T> : I1<T> {} "; var source1 = @" class I2<T> : I3<T> { public static void Test() { I1<int>.M1(); } } class A { static void Main() { I2<byte>.Test(); } } "; var compilation0 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); } private const string NoPiaAttributes = @" namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] public sealed class GuidAttribute : Attribute { public GuidAttribute(string guid){} } [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)] public sealed class PrimaryInteropAssemblyAttribute : Attribute { public PrimaryInteropAssemblyAttribute(int major, int minor){} } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false)] public sealed class ComImportAttribute : Attribute { public ComImportAttribute(){} } [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class TypeIdentifierAttribute : Attribute { public TypeIdentifierAttribute(){} public TypeIdentifierAttribute(string scope, string identifier){} } } "; [Fact] public void NoPia_01() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia7 : ITest33 { } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,17): error CS8711: Type 'ITest33' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. // class UsePia7 : ITest33 Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType, "ITest33").WithArguments("ITest33").WithLocation(2, 17) ); } } [Fact] public void NoPia_02() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main(ITest33 x) { x.M1(); } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (4,29): error CS8711: Type 'ITest33' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. // public static void Main(ITest33 x) Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType, "ITest33").WithArguments("ITest33").WithLocation(4, 29) ); } } [Fact] public void NoPia_03() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(){} void M2(); } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main(ITest33 x) { x.M2(); } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (4,29): error CS8711: Type 'ITest33' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. // public static void Main(ITest33 x) Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType, "ITest33").WithArguments("ITest33").WithLocation(4, 29) ); } } [Fact] public void NoPia_04() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { sealed void M1(){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main(ITest33 x) { x.M1(); } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (4,29): error CS8711: Type 'ITest33' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. // public static void Main(ITest33 x) Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType, "ITest33").WithArguments("ITest33").WithLocation(4, 29) ); } } [Fact] public void NoPia_05() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { static void M1(){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main() { ITest33.M1(); } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (6,9): error CS8711: Type 'ITest33' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. // ITest33.M1(); Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType, "ITest33").WithArguments("ITest33").WithLocation(6, 9) ); } } [Fact] public void NoPia_06() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface I1 { } } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main(ITest33.I1 x) { } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (4,37): error CS1754: Type 'ITest33.I1' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // public static void Main(ITest33.I1 x) Diagnostic(ErrorCode.ERR_NoPIANestedType, "I1").WithArguments("ITest33.I1").WithLocation(4, 37) ); } } [Fact] public void NoPia_07() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { public static int F1; } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main() { _ = ITest33.F1; } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (6,13): error CS8711: Type 'ITest33' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. // _ = ITest33.F1; Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType, "ITest33").WithArguments("ITest33").WithLocation(6, 13) ); } } [Fact] public void NoPia_08() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest44 : ITest33 { void ITest33.M1(){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main(ITest44 x) { x.M1(); } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (4,29): error CS8711: Type 'ITest44' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. // public static void Main(ITest44 x) Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType, "ITest44").WithArguments("ITest44").WithLocation(4, 29) ); } } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPia_09() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(); public interface ITest55 { void M2(); } } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest44 : ITest33 { void ITest33.M1(){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer1 = @" public class UsePia { public static void Test(ITest33 x) { x.M1(); } } "; string consumer2 = @" class Test : ITest33 { public static void Main() { UsePia.Test(new Test()); } void ITest33.M1() { System.Console.WriteLine(""Test.M1""); } } "; string pia2 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(); } " + NoPiaAttributes; var pia2Compilation = CreateCompilation(pia2, options: TestOptions.ReleaseDll); var pia2Reference = pia2Compilation.EmitToImageReference(); foreach (var reference1 in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer1, options: TestOptions.ReleaseDll, references: new[] { reference1, attributesRef }, targetFramework: TargetFramework.StandardLatest); foreach (var reference2 in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(consumer2, options: TestOptions.ReleaseExe, references: new[] { reference2, pia2Reference }, targetFramework: TargetFramework.StandardLatest); CompileAndVerify(compilation2, expectedOutput: "Test.M1"); } } } [Fact] [WorkItem(35911, "https://github.com/dotnet/roslyn/issues/35911")] public void NoPia_10() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest44 : ITest33 { abstract void ITest33.M1(); } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main(ITest44 x) { x.M1(); } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (4,29): error CS8750: Type 'ITest44' cannot be embedded because it has a re-abstraction of a member from base interface. Consider setting the 'Embed Interop Types' property to false. // public static void Main(ITest44 x) Diagnostic(ErrorCode.ERR_ReAbstractionInNoPIAType, "ITest44").WithArguments("ITest44").WithLocation(4, 29) ); } } [Fact] public void LambdaCaching_01() { var source0 = @" interface I1 { static void M1() { M2(() => System.Console.WriteLine(""M1"")); } static void M2(System.Action d) { d(); } } class A { static void Main() { I1.M1(); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var verifier = CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); verifier.VerifyIL("I1.M1", @" { // Code size 39 (0x27) .maxstack 2 IL_0000: nop IL_0001: ldsfld ""System.Action I1.<>c.<>9__0_0"" IL_0006: dup IL_0007: brtrue.s IL_0020 IL_0009: pop IL_000a: ldsfld ""I1.<>c I1.<>c.<>9"" IL_000f: ldftn ""void I1.<>c.<M1>b__0_0()"" IL_0015: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_001a: dup IL_001b: stsfld ""System.Action I1.<>c.<>9__0_0"" IL_0020: call ""void I1.M2(System.Action)"" IL_0025: nop IL_0026: ret } "); } [Fact] public void LambdaCaching_02() { var source0 = @" interface I1 { void M1() { M2(() => System.Console.WriteLine(""M1"")); } static void M2(System.Action d) { d(); } } class A : I1 { static void Main() { ((I1)new A()).M1(); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var verifier = CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); verifier.VerifyIL("I1.M1", @" { // Code size 39 (0x27) .maxstack 2 IL_0000: nop IL_0001: ldsfld ""System.Action I1.<>c.<>9__0_0"" IL_0006: dup IL_0007: brtrue.s IL_0020 IL_0009: pop IL_000a: ldsfld ""I1.<>c I1.<>c.<>9"" IL_000f: ldftn ""void I1.<>c.<M1>b__0_0()"" IL_0015: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_001a: dup IL_001b: stsfld ""System.Action I1.<>c.<>9__0_0"" IL_0020: call ""void I1.M2(System.Action)"" IL_0025: nop IL_0026: ret } "); } [Fact] public void LambdaCaching_03() { var source0 = @" interface I1 { void M1() { M2(() => System.Console.WriteLine(this.ToString())); } static void M2(System.Action d) { d(); } } class A : I1 { static void Main() { ((I1)new A()).M1(); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var verifier = CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"A", verify: VerifyOnMonoOrCoreClr); verifier.VerifyIL("I1.M1", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldftn ""void I1.<M1>b__0_0()"" IL_0008: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_000d: call ""void I1.M2(System.Action)"" IL_0012: nop IL_0013: ret } "); } [Fact] public void MemberwiseClone_01() { var source0 = @" interface I1 { object M1(I2 x, I3 y) { x.MemberwiseClone(); y.MemberwiseClone(); this.MemberwiseClone(); return ((I1)this).MemberwiseClone(); } } interface I2 { } interface I3 : I1 { } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics( // (6,11): error CS0122: 'object.MemberwiseClone()' is inaccessible due to its protection level // x.MemberwiseClone(); Diagnostic(ErrorCode.ERR_BadAccess, "MemberwiseClone").WithArguments("object.MemberwiseClone()").WithLocation(6, 11), // (7,11): error CS0122: 'object.MemberwiseClone()' is inaccessible due to its protection level // y.MemberwiseClone(); Diagnostic(ErrorCode.ERR_BadAccess, "MemberwiseClone").WithArguments("object.MemberwiseClone()").WithLocation(7, 11), // (8,14): error CS0122: 'object.MemberwiseClone()' is inaccessible due to its protection level // this.MemberwiseClone(); Diagnostic(ErrorCode.ERR_BadAccess, "MemberwiseClone").WithArguments("object.MemberwiseClone()").WithLocation(8, 14), // (9,27): error CS0122: 'object.MemberwiseClone()' is inaccessible due to its protection level // return ((I1)this).MemberwiseClone(); Diagnostic(ErrorCode.ERR_BadAccess, "MemberwiseClone").WithArguments("object.MemberwiseClone()").WithLocation(9, 27) ); } [Fact] public void MethodReAbstraction_01() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { abstract void I1.M1(); } "; var source2 = @" class Test1 : I2 { } "; ValidateMethodReAbstraction_01(source1, source2); } private static void ValidateMethodReAbstraction_01(string source1, string source2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); var expected = new DiagnosticDescription[] { // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1()").WithLocation(2, 15) }; compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); ValidateReabstraction(i2m1); var i1m1 = i2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } private static void ValidateReabstraction(MethodSymbol m) { Assert.True(m.IsMetadataVirtual()); Assert.True(m.IsMetadataFinal); Assert.False(m.IsMetadataNewSlot()); Assert.True(m.IsAbstract); Assert.False(m.IsVirtual); Assert.True(m.IsSealed); Assert.False(m.IsStatic); Assert.False(m.IsExtern); Assert.False(m.IsAsync); Assert.False(m.IsOverride); Assert.Equal(Accessibility.Private, m.DeclaredAccessibility); } [Fact] public void MethodReAbstraction_02() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } "; var source2 = @" class Test1 : I2 { } "; ValidateMethodReAbstraction_01(source1, source2); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void MethodReAbstraction_03() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { abstract void I1.M1(); } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1.M1(); } void I1.M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodReAbstraction_03(source1, source2); } private void ValidateMethodReAbstraction_03(string source1, string source2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test1.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test1.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); var i1m1 = i2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Equal("void Test1.I1.M1()", test1.FindImplementationForInterfaceMember(i1m1).ToTestDisplayString()); } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void MethodReAbstraction_04() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1.M1(); } void I1.M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodReAbstraction_03(source1, source2); } [Fact] public void MethodReAbstraction_05() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidateMethodReAbstraction_05(source1, source2); } private static void ValidateMethodReAbstraction_05(string source1, string source2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); var expected = new DiagnosticDescription[] { // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.M1()").WithLocation(2, 15) }; compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i3 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I3", i3.Name); var i1m1 = i3.ContainingNamespace.GetTypeMember("I1").GetMember<MethodSymbol>("M1"); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i3.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_06() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidateMethodReAbstraction_05(source1, source2); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void MethodReAbstraction_07() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I2 { void I1.M1() { System.Console.WriteLine(""I3.M1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1.M1(); } } "; ValidateMethodReAbstraction_07(source1, source2); } private void ValidateMethodReAbstraction_07(string source1, string source2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "I3.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "I3.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i3 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I3", i3.Name); var i1m1 = i3.ContainingNamespace.GetTypeMember("I1").GetMember<MethodSymbol>("M1"); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Equal("void I3.I1.M1()", i3.FindImplementationForInterfaceMember(i1m1).ToTestDisplayString()); Assert.Equal("void I3.I1.M1()", test1.FindImplementationForInterfaceMember(i1m1).ToTestDisplayString()); } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void MethodReAbstraction_08() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I2 { void I1.M1() { System.Console.WriteLine(""I3.M1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1.M1(); } } "; ValidateMethodReAbstraction_07(source1, source2); } [Fact] public void MethodReAbstraction_09() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I1 { abstract void I1.M1(); } "; var source2 = @" class Test1 : I2, I3 { } "; ValidateMethodReAbstraction_09(source1, source2); } private void ValidateMethodReAbstraction_09(string source1, string source2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); var expected = new DiagnosticDescription[] { // (2,15): error CS8705: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I2.I1.M1()', nor 'I3.I1.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1()", "I2.I1.M1()", "I3.I1.M1()").WithLocation(2, 15) }; compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1m1 = test1.InterfacesNoUseSiteDiagnostics().First().ContainingNamespace.GetTypeMember("I1").GetMember<MethodSymbol>("M1"); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_10() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { void I1.M1() {} } public interface I3 : I1 { abstract void I1.M1(); } "; var source2 = @" class Test1 : I2, I3 { } "; ValidateMethodReAbstraction_09(source1, source2); } [Fact] public void MethodReAbstraction_11() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I1 { void I1.M1() {} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidateMethodReAbstraction_09(source1, source2); } [Fact] public void MethodReAbstraction_12() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I1 { abstract void I1.M1(); } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); var expected = new DiagnosticDescription[] { // (2,15): error CS8705: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I2.I1.M1()', nor 'I3.I1.M1()' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.M1()", "I2.I1.M1()", "I3.I1.M1()").WithLocation(2, 15) }; compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i4 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I4", i4.Name); var i1m1 = i4.ContainingNamespace.GetTypeMember("I1").GetMember<MethodSymbol>("M1"); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i4.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void MethodReAbstraction_13() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I1 { abstract void I1.M1(); } public interface I4 : I2, I3 { void I1.M1() { System.Console.WriteLine(""I4.M1""); } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); i1.M1(); } } "; var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "I4.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "I4.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i4 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I4", i4.Name); var i1m1 = i4.ContainingNamespace.GetTypeMember("I1").GetMember<MethodSymbol>("M1"); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Equal("void I4.I1.M1()", i4.FindImplementationForInterfaceMember(i1m1).ToTestDisplayString()); Assert.Equal("void I4.I1.M1()", test1.FindImplementationForInterfaceMember(i1m1).ToTestDisplayString()); } } [Fact] public void MethodReAbstraction_14() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { abstract void I1.M1() {} } class Test1 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics( // (9,22): error CS0500: 'I2.I1.M1()' cannot declare a body because it is marked abstract // abstract void I1.M1() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M1").WithArguments("I2.I1.M1()").WithLocation(9, 22), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1()").WithLocation(12, 15) ); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); ValidateReabstraction(i2m1); var i1m1 = i2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_15() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { abstract extern void I1.M1(); } class Test1 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics( // (9,29): error CS0180: 'I2.I1.M1()' cannot be both extern and abstract // abstract extern void I1.M1(); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M1").WithArguments("I2.I1.M1()").WithLocation(9, 29), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1()").WithLocation(12, 15) ); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); Assert.True(i2m1.IsMetadataVirtual()); Assert.True(i2m1.IsMetadataFinal); Assert.False(i2m1.IsMetadataNewSlot()); Assert.True(i2m1.IsAbstract); Assert.False(i2m1.IsVirtual); Assert.True(i2m1.IsSealed); Assert.False(i2m1.IsStatic); Assert.True(i2m1.IsExtern); Assert.False(i2m1.IsAsync); Assert.False(i2m1.IsOverride); Assert.Equal(Accessibility.Private, i2m1.DeclaredAccessibility); var i1m1 = i2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_16() { var source1 = @" public interface I1 { void M1(); } public partial interface I2 : I1 { abstract partial void I1.M1(); } class Test1 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularWithExtendedPartialMethods, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics( // (9,30): error CS0754: A partial method may not explicitly implement an interface method // abstract partial void I1.M1(); Diagnostic(ErrorCode.ERR_PartialMethodNotExplicit, "M1").WithLocation(9, 30), // (9,30): error CS0750: A partial method cannot have the 'abstract' modifier // abstract partial void I1.M1(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M1").WithLocation(9, 30), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1()").WithLocation(12, 15) ); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); ValidateReabstraction(i2m1); var i1m1 = i2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_17() { var source1 = @" public interface I1 { void M1(); } public partial interface I2 : I1 { abstract async void I1.M1(); } class Test1 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics( // (9,28): error CS1994: The 'async' modifier can only be used in methods that have a body. // abstract async void I1.M1(); Diagnostic(ErrorCode.ERR_BadAsyncLacksBody, "M1").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1()").WithLocation(12, 15) ); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); Assert.True(i2m1.IsMetadataVirtual()); Assert.True(i2m1.IsMetadataFinal); Assert.False(i2m1.IsMetadataNewSlot()); Assert.True(i2m1.IsAbstract); Assert.False(i2m1.IsVirtual); Assert.True(i2m1.IsSealed); Assert.False(i2m1.IsStatic); Assert.False(i2m1.IsExtern); Assert.True(i2m1.IsAsync); Assert.False(i2m1.IsOverride); Assert.Equal(Accessibility.Private, i2m1.DeclaredAccessibility); var i1m1 = i2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_18() { var source1 = @" public interface I1 { void M1(); } public partial interface I2 : I1 { abstract public void I1.M1(); } class Test1 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics( // (9,29): error CS0106: The modifier 'public' is not valid for this item // abstract public void I1.M1(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("public").WithLocation(9, 29), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1()").WithLocation(12, 15) ); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); ValidateReabstraction(i2m1); var i1m1 = i2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_19() { var source1 = @" public interface I1 { void M1(); } public class C2 : I1 { abstract void I1.M1(); } "; ValidateMethodReAbstraction_19(source1); } private static void ValidateMethodReAbstraction_19(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics( // (9,22): error CS0106: The modifier 'abstract' is not valid for this item // abstract void I1.M1(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("abstract").WithLocation(9, 22), // (9,22): error CS0501: 'C2.I1.M1()' must declare a body because it is not marked abstract, extern, or partial // abstract void I1.M1(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M1").WithArguments("C2.I1.M1()").WithLocation(9, 22) ); static void validate(ModuleSymbol m) { var c2 = m.GlobalNamespace.GetTypeMember("C2"); var c2m1 = c2.GetMember<MethodSymbol>("I1.M1"); Assert.False(c2m1.IsAbstract); Assert.False(c2m1.IsSealed); var i1m1 = c2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Same(c2m1, c2.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_20() { var source1 = @" public interface I1 { void M1(); } public struct C2 : I1 { abstract void I1.M1(); } "; ValidateMethodReAbstraction_19(source1); } [Fact] public void MethodReAbstraction_21() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract void I1.M1(); } class Test1 : I2 { } "; ValidateMethodReAbstraction_21(source1, // (8,22): error CS0539: 'I2.M1()' in explicit interface declaration is not found among members of the interface that can be implemented // abstract void I1.M1(); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M1").WithArguments("I2.M1()").WithLocation(8, 22) ); } private static void ValidateMethodReAbstraction_21(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); ValidateReabstraction(i2m1); Assert.Empty(i2m1.ExplicitInterfaceImplementations); } } [Fact] public void MethodReAbstraction_22() { var source1 = @" public interface I2 : I1 { abstract void I1.M1(); } class Test1 : I2 { } "; ValidateMethodReAbstraction_21(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,19): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract void I1.M1(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 19), // (4,19): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract void I1.M1(); Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 19) ); } [Fact] public void MethodReAbstraction_23() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { abstract void I1.M1(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,22): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract void I1.M1(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M1").WithArguments("default interface implementation", "8.0").WithLocation(9, 22) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,22): error CS8701: Target runtime doesn't support default interface implementation. // abstract void I1.M1(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(9, 22) ); } [Fact] public void PropertyReAbstraction_001() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 {get; set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } private static void ValidatePropertyReAbstraction_001(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<PropertySymbol>().Single(); ValidateReabstraction(i2p1); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Same(i1p1.GetMethod, i2p1.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } else if (i2p1.GetMethod is object) { Assert.Empty(i2p1.GetMethod.ExplicitInterfaceImplementations); } if (i1p1.SetMethod is object) { Assert.Same(i1p1.SetMethod, i2p1.SetMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } else if (i2p1.SetMethod is object) { Assert.Empty(i2p1.SetMethod.ExplicitInterfaceImplementations); } } } private static void ValidateReabstraction(PropertySymbol reabstracting) { Assert.True(reabstracting.IsAbstract); Assert.False(reabstracting.IsVirtual); Assert.True(reabstracting.IsSealed); Assert.False(reabstracting.IsStatic); Assert.False(reabstracting.IsExtern); Assert.False(reabstracting.IsOverride); Assert.Equal(Accessibility.Private, reabstracting.DeclaredAccessibility); if (reabstracting.GetMethod is object) { ValidateReabstraction(reabstracting.GetMethod); } if (reabstracting.SetMethod is object) { ValidateReabstraction(reabstracting.SetMethod); } } [Fact] public void PropertyReAbstraction_002() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_003() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 {get; set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; i1.P1 = 1; } int I1.P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set => System.Console.WriteLine(""Test1.set_P1""); } } "; ValidatePropertyReAbstraction_003(source1, source2, @" Test1.get_P1 Test1.set_P1 "); } private void ValidatePropertyReAbstraction_003(string source1, string source2, string expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test12p1 = test1.GetMembers().OfType<PropertySymbol>().Single(); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<PropertySymbol>().Single(); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Same(test12p1, test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Same(test12p1.GetMethod, test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } if (i1p1.SetMethod is object) { Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Same(test12p1.SetMethod, test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_004() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; i1.P1 = 1; } int I1.P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set => System.Console.WriteLine(""Test1.set_P1""); } } "; ValidatePropertyReAbstraction_003(source1, source2, @" Test1.get_P1 Test1.set_P1 "); } [Fact] public void PropertyReAbstraction_005() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } private static void ValidatePropertyReAbstraction_005(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i3 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I3", i3.Name); var i1p1 = i3.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(i3.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Null(i3.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } if (i1p1.SetMethod is object) { Assert.Null(i3.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } } } [Fact] public void PropertyReAbstraction_006() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_007() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I2 { int I1.P1 { get { System.Console.WriteLine(""I3.get_P1""); return 0; } set => System.Console.WriteLine(""I3.set_P1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; i1.P1 = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, @" I3.get_P1 I3.set_P1 "); } private void ValidatePropertyReAbstraction_007(string source1, string source2, string expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i3 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I3", i3.Name); var i3p1 = i3.GetMembers().OfType<PropertySymbol>().Single(); var i1p1 = i3.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(i3p1, i3.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i3p1, test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Same(i3p1.GetMethod, i3.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Same(i3p1.GetMethod, test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } if (i1p1.SetMethod is object) { Assert.Same(i3p1.SetMethod, i3.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Same(i3p1.SetMethod, test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_008() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I2 { int I1.P1 { get { System.Console.WriteLine(""I3.get_P1""); return 0; } set => System.Console.WriteLine(""I3.set_P1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; i1.P1 = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, @" I3.get_P1 I3.set_P1 "); } [Fact] public void PropertyReAbstraction_009() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I1 { abstract int I1.P1 {get; set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } private static void ValidatePropertyReAbstraction_009(string source1, string source2, params DiagnosticDescription[] expected) { ValidatePropertyReAbstraction_009(source1, source2, expected, expected); } private static void ValidatePropertyReAbstraction_009(string source1, string source2, DiagnosticDescription[] expected1, params DiagnosticDescription[] expected2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); var expected = expected1; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); expected = expected2; } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1p1 = test1.InterfacesNoUseSiteDiagnostics().First().ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } if (i1p1.SetMethod is object) { Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } } } [Fact] public void PropertyReAbstraction_010() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { int I1.P1 { get => throw null; set => throw null; } } public interface I3 : I1 { abstract int I1.P1 {get; set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_011() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I1 { int I1.P1 { get => throw null; set => throw null; } } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_012() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I1 { abstract int I1.P1 {get; set;} } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; ValidatePropertyReAbstraction_012(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } private static void ValidatePropertyReAbstraction_012(string source1, string source2, params DiagnosticDescription[] expected) { ValidatePropertyReAbstraction_012(source1, source2, expected, expected); } private static void ValidatePropertyReAbstraction_012(string source1, string source2, DiagnosticDescription[] expected1, params DiagnosticDescription[] expected2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); var expected = expected1; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); expected = expected2; } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i4 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I4", i4.Name); var i1p1 = i4.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(i4.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Null(i4.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } if (i1p1.SetMethod is object) { Assert.Null(i4.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_013() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I1 { abstract int I1.P1 {get; set;} } public interface I4 : I2, I3 { int I1.P1 { get { System.Console.WriteLine(""I4.get_P1""); return 0; } set => System.Console.WriteLine(""I4.set_P1""); } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; i1.P1 = 1; } } "; ValidatePropertyReAbstraction_013(source1, source2, @" I4.get_P1 I4.set_P1 "); } private void ValidatePropertyReAbstraction_013(string source1, string source2, string expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i4 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I4", i4.Name); var i4p1 = i4.GetMembers().OfType<PropertySymbol>().Single(); var i1p1 = i4.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(i4p1, i4.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i4p1, test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Same(i4p1.GetMethod, i4.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Same(i4p1.GetMethod, test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } if (i1p1.SetMethod is object) { Assert.Same(i4p1.SetMethod, i4.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Same(i4p1.SetMethod, test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } } } [Fact] public void PropertyReAbstraction_014() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 { get { throw null; } set { throw null; } } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.P1.get' cannot declare a body because it is marked abstract // get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.P1.get").WithLocation(11, 9), // (15,9): error CS0500: 'I2.I1.P1.set' cannot declare a body because it is marked abstract // set Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.P1.set").WithLocation(15, 9), // (22,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(22, 15) ); } private static void ValidatePropertyReAbstraction_014(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<PropertySymbol>().Single(); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); ValidateReabstraction(i2p1); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { if (i2p1.GetMethod is object) { Assert.Same(i1p1.GetMethod, i2p1.GetMethod.ExplicitInterfaceImplementations.Single()); } Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } else if (i2p1.GetMethod is object) { Assert.Empty(i2p1.GetMethod.ExplicitInterfaceImplementations); } if (i1p1.SetMethod is object) { if (i2p1.SetMethod is object) { Assert.Same(i1p1.SetMethod, i2p1.SetMethod.ExplicitInterfaceImplementations.Single()); } Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } else if (i2p1.SetMethod is object) { Assert.Empty(i2p1.SetMethod.ExplicitInterfaceImplementations); } } } [Fact] public void PropertyReAbstraction_015() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 { get => throw null; set => throw null; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.P1.get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.P1.get").WithLocation(11, 9), // (12,9): error CS0500: 'I2.I1.P1.set' cannot declare a body because it is marked abstract // set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.P1.set").WithLocation(12, 9), // (16,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(16, 15) ); } [Fact] public void PropertyReAbstraction_016() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { extern abstract int I1.P1 {get; set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_016(source1, // (9,28): error CS0180: 'I2.I1.P1' cannot be both extern and abstract // extern abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P1").WithArguments("I2.I1.P1").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } private static void ValidatePropertyReAbstraction_016(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<PropertySymbol>().Single(); Assert.True(i2p1.IsAbstract); Assert.False(i2p1.IsVirtual); Assert.True(i2p1.IsSealed); Assert.False(i2p1.IsStatic); Assert.True(i2p1.IsExtern); Assert.False(i2p1.IsOverride); Assert.Equal(Accessibility.Private, i2p1.DeclaredAccessibility); var i2p1Get = i2p1.GetMethod; if (i2p1Get is object) { Assert.True(i2p1Get.IsMetadataVirtual()); Assert.True(i2p1Get.IsMetadataFinal); Assert.False(i2p1Get.IsMetadataNewSlot()); Assert.True(i2p1Get.IsAbstract); Assert.False(i2p1Get.IsVirtual); Assert.True(i2p1Get.IsSealed); Assert.False(i2p1Get.IsStatic); Assert.True(i2p1Get.IsExtern); Assert.False(i2p1Get.IsAsync); Assert.False(i2p1Get.IsOverride); Assert.Equal(Accessibility.Private, i2p1Get.DeclaredAccessibility); } var i2p1Set = i2p1.SetMethod; if (i2p1Set is object) { Assert.True(i2p1Set.IsMetadataVirtual()); Assert.True(i2p1Set.IsMetadataFinal); Assert.False(i2p1Set.IsMetadataNewSlot()); Assert.True(i2p1Set.IsAbstract); Assert.False(i2p1Set.IsVirtual); Assert.True(i2p1Set.IsSealed); Assert.False(i2p1Set.IsStatic); Assert.True(i2p1Set.IsExtern); Assert.False(i2p1Set.IsAsync); Assert.False(i2p1Set.IsOverride); Assert.Equal(Accessibility.Private, i2p1Set.DeclaredAccessibility); } var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Same(i1p1.GetMethod, i2p1.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } else if (i2p1.GetMethod is object) { Assert.Empty(i2p1.GetMethod.ExplicitInterfaceImplementations); } if (i1p1.SetMethod is object) { Assert.Same(i1p1.SetMethod, i2p1.SetMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } else if (i2p1.SetMethod is object) { Assert.Empty(i2p1.SetMethod.ExplicitInterfaceImplementations); } } } [Fact] public void PropertyReAbstraction_017() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract public int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,28): error CS0106: The modifier 'public' is not valid for this item // abstract public int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("public").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_018() { var source1 = @" public interface I1 { int P1 {get; set;} } public class C2 : I1 { abstract int I1.P1 { get; set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 21) ); } private static void ValidatePropertyReAbstraction_018(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var c2 = m.GlobalNamespace.GetTypeMember("C2"); var c2p1 = c2.GetMembers().OfType<PropertySymbol>().Single(); Assert.False(c2p1.IsAbstract); Assert.False(c2p1.IsSealed); var c2p1Get = c2p1.GetMethod; if (c2p1Get is object) { Assert.False(c2p1Get.IsAbstract); Assert.False(c2p1Get.IsSealed); } var c2p1Set = c2p1.SetMethod; if (c2p1Set is object) { Assert.False(c2p1Set.IsAbstract); Assert.False(c2p1Set.IsSealed); } var i1p1 = c2p1.ExplicitInterfaceImplementations.Single(); Assert.Same(c2p1, c2.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Same(i1p1.GetMethod, c2p1.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(c2p1Get, c2.FindImplementationForInterfaceMember(i1p1.GetMethod)); } else if (c2p1.GetMethod is object) { Assert.Empty(c2p1.GetMethod.ExplicitInterfaceImplementations); } if (i1p1.SetMethod is object) { Assert.Same(i1p1.SetMethod, c2p1.SetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(c2p1Set, c2.FindImplementationForInterfaceMember(i1p1.SetMethod)); } else if (c2p1.SetMethod is object) { Assert.Empty(c2p1.SetMethod.ExplicitInterfaceImplementations); } } } [Fact] public void PropertyReAbstraction_019() { var source1 = @" public interface I1 { int P1 {get; set;} } public struct C2 : I1 { abstract int I1.P1 { get; set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 21) ); } [Fact] public void PropertyReAbstraction_020() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 { get; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.P1' is missing accessor 'I1.P1.set' // abstract int I1.P1 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P1").WithArguments("I2.I1.P1", "I1.P1.set").WithLocation(9, 21), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_021() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 { set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.P1' is missing accessor 'I1.P1.get' // abstract int I1.P1 { set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P1").WithArguments("I2.I1.P1", "I1.P1.get").WithLocation(9, 21), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_022() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,31): error CS0550: 'I2.I1.P1.set' adds an accessor not found in interface member 'I1.P1' // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.I1.P1.set", "I1.P1").WithLocation(9, 31), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_023() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,26): error CS0550: 'I2.I1.P1.get' adds an accessor not found in interface member 'I1.P1' // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.I1.P1.get", "I1.P1").WithLocation(9, 26), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_024() { var source1 = @" public interface I1 { int P1 {get => throw null; private set => throw null;} } public interface I2 : I1 { abstract int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,31): error CS0550: 'I2.I1.P1.set' adds an accessor not found in interface member 'I1.P1' // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.I1.P1.set", "I1.P1").WithLocation(9, 31), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_025() { var source1 = @" public interface I1 { int P1 {private get => throw null; set => throw null;} } public interface I2 : I1 { abstract int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,26): error CS0550: 'I2.I1.P1.get' adds an accessor not found in interface member 'I1.P1' // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.I1.P1.get", "I1.P1").WithLocation(9, 26), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_026() { var source1 = @" public interface I1 { internal int P1 {get => throw null; set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.P1' is inaccessible due to its protection level // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); } private static void ValidatePropertyReAbstraction_026(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, references: new[] { reference }, targetFramework: TargetFramework.NetCoreApp); validate(compilation2.SourceModule); compilation2.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<PropertySymbol>().Single(); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); ValidateReabstraction(i2p1); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Same(i1p1.GetMethod, i2p1.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } else if (i2p1.GetMethod is object) { Assert.Empty(i2p1.GetMethod.ExplicitInterfaceImplementations); } if (i1p1.SetMethod is object) { Assert.Same(i1p1.SetMethod, i2p1.SetMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } else if (i2p1.SetMethod is object) { Assert.Empty(i2p1.SetMethod.ExplicitInterfaceImplementations); } } } [Fact] public void PropertyReAbstraction_027() { var source1 = @" public interface I1 { int P1 {internal get => throw null; set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.P1.get' is inaccessible due to its protection level // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1.get").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); } [Fact] public void PropertyReAbstraction_028() { var source1 = @" public interface I1 { int P1 {get => throw null; internal set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.P1.set' is inaccessible due to its protection level // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1.set").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_029() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 // Code size 3 (0x3) .maxstack 8 IL_0000: ldc.i4.s 65 IL_0002: ret } // end of method I2::I1.get_F1 .method private hidebysig specialname abstract virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 } // end of method I2::I1.set_F1 .property instance char I1.F1() { .get instance char I2::I1.get_F1() .set instance void I2::I1.set_F1(char) } // end of property I2::I1.F1 } // end of class I2 "; var source1 = @" class Test2 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.F1' // class Test2 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.SetMethod)); Assert.Equal("System.Char I2.I1.get_F1()", test2.FindImplementationForInterfaceMember(i1F1.GetMethod).ToTestDisplayString()); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_030() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname abstract virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 } // end of method I2::I1.get_F1 .method private hidebysig specialname virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 IL_0002: ret } // end of method I2::I1.set_F1 .property instance char I1.F1() { .get instance char I2::I1.get_F1() .set instance void I2::I1.set_F1(char) } // end of property I2::I1.F1 } // end of class I2 "; var source1 = @" class Test2 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.F1' // class Test2 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Equal("void I2.I1.set_F1(System.Char value)", test2.FindImplementationForInterfaceMember(i1F1.SetMethod).ToTestDisplayString()); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.GetMethod)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_031() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 // Code size 3 (0x3) .maxstack 8 IL_0000: ldc.i4.s 65 IL_0002: ret } // end of method I2::I1.get_F1 .method private hidebysig specialname abstract virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 } // end of method I2::I1.set_F1 .property instance char I1.F1() { .get instance char I2::I1.get_F1() .set instance void I2::I1.set_F1(char) } // end of property I2::I1.F1 } // end of class I2 .class interface public abstract auto ansi I3 implements I1 { .method private hidebysig specialname abstract virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 } // end of method I3::I1.get_F1 .method private hidebysig specialname virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 IL_0002: ret } // end of method I3::I1.set_F1 .property instance char I1.F1() { .get instance char I3::I1.get_F1() .set instance void I3::I1.set_F1(char) } // end of property I3::I1.F1 } // end of class I3 "; var source1 = @" class Test2 : I2, I3 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS8705: Interface member 'I1.F1' does not have a most specific implementation. Neither 'I2.I1.F1', nor 'I3.I1.F1' are most specific. // class Test2 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.F1", "I2.I1.F1", "I3.I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.GetMethod)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_032() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 // Code size 3 (0x3) .maxstack 8 IL_0000: ldc.i4.s 65 IL_0002: ret } // end of method I2::I1.get_F1 .method private hidebysig specialname abstract virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 } // end of method I2::I1.set_F1 } // end of class I2 "; var source1 = @" class Test2 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.F1' // class Test2 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.SetMethod)); Assert.Equal("System.Char I2.I1.get_F1()", test2.FindImplementationForInterfaceMember(i1F1.GetMethod).ToTestDisplayString()); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_033() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname abstract virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 } // end of method I2::I1.get_F1 .method private hidebysig specialname virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 IL_0002: ret } // end of method I2::I1.set_F1 } // end of class I2 "; var source1 = @" class Test2 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.F1' // class Test2 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Equal("void I2.I1.set_F1(System.Char value)", test2.FindImplementationForInterfaceMember(i1F1.SetMethod).ToTestDisplayString()); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.GetMethod)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_034() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 // Code size 3 (0x3) .maxstack 8 IL_0000: ldc.i4.s 65 IL_0002: ret } // end of method I2::I1.get_F1 .method private hidebysig specialname abstract virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 } // end of method I2::I1.set_F1 } // end of class I2 .class interface public abstract auto ansi I3 implements I1 { .method private hidebysig specialname abstract virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 } // end of method I3::I1.get_F1 .method private hidebysig specialname virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 IL_0002: ret } // end of method I3::I1.set_F1 .property instance char I1.F1() { .get instance char I3::I1.get_F1() .set instance void I3::I1.set_F1(char) } // end of property I3::I1.F1 } // end of class I3 "; var source1 = @" class Test2 : I2, I3 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.F1' // class Test2 : I2, I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.GetMethod)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_035() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 // Code size 3 (0x3) .maxstack 8 IL_0000: ldc.i4.s 65 IL_0002: ret } // end of method I2::I1.get_F1 .method private hidebysig specialname abstract virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 } // end of method I2::I1.set_F1 .property instance char I1.F1() { .get instance char I2::I1.get_F1() .set instance void I2::I1.set_F1(char) } // end of property I2::I1.F1 } // end of class I2 .class interface public abstract auto ansi I3 implements I1 { .method private hidebysig specialname abstract virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 } // end of method I3::I1.get_F1 .method private hidebysig specialname virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 IL_0002: ret } // end of method I3::I1.set_F1 } // end of class I3 "; var source1 = @" class Test2 : I2, I3 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.F1' // class Test2 : I2, I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.GetMethod)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_036() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 // Code size 3 (0x3) .maxstack 8 IL_0000: ldc.i4.s 65 IL_0002: ret } // end of method I2::I1.get_F1 .method private hidebysig specialname abstract virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 } // end of method I2::I1.set_F1 } // end of class I2 .class interface public abstract auto ansi I3 implements I1 { .method private hidebysig specialname abstract virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 } // end of method I3::I1.get_F1 .method private hidebysig specialname virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 IL_0002: ret } // end of method I3::I1.set_F1 } // end of class I3 "; var source1 = @" class Test2 : I2, I3 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.F1' // class Test2 : I2, I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.GetMethod)); } [Fact] public void PropertyReAbstraction_037() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 {get;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_038() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_039() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 {get;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; } int I1.P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.get_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_040() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; } int I1.P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.get_P1"); } [Fact] public void PropertyReAbstraction_041() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_042() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_043() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I2 { int I1.P1 { get { System.Console.WriteLine(""I3.get_P1""); return 0; } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.get_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_044() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I2 { int I1.P1 { get { System.Console.WriteLine(""I3.get_P1""); return 0; } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.get_P1"); } [Fact] public void PropertyReAbstraction_045() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I1 { abstract int I1.P1 {get;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_046() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { int I1.P1 { get => throw null; } } public interface I3 : I1 { abstract int I1.P1 {get;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_047() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I1 { int I1.P1 { get => throw null; } } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_048() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I1 { abstract int I1.P1 {get;} } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; ValidatePropertyReAbstraction_012(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_049() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I1 { abstract int I1.P1 {get;} } public interface I4 : I2, I3 { int I1.P1 { get { System.Console.WriteLine(""I4.get_P1""); return 0; } } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "; ValidatePropertyReAbstraction_013(source1, source2, "I4.get_P1"); } [Fact] public void PropertyReAbstraction_050() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 { get { throw null; } } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.P1.get' cannot declare a body because it is marked abstract // get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.P1.get").WithLocation(11, 9), // (18,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(18, 15) ); } [Fact] public void PropertyReAbstraction_051() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 { get => throw null; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.P1.get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.P1.get").WithLocation(11, 9), // (15,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(15, 15) ); } [Fact] public void PropertyReAbstraction_052() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 => throw null; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,27): error CS0500: 'I2.I1.P1.get' cannot declare a body because it is marked abstract // abstract int I1.P1 => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "throw null").WithArguments("I2.I1.P1.get").WithLocation(9, 27), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_053() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { extern abstract int I1.P1 {get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_016(source1, // (9,28): error CS0180: 'I2.I1.P1' cannot be both extern and abstract // extern abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P1").WithArguments("I2.I1.P1").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_054() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract public int I1.P1 { get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,28): error CS0106: The modifier 'public' is not valid for this item // abstract public int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("public").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_055() { var source1 = @" public interface I1 { int P1 {get;} } public class C2 : I1 { abstract int I1.P1 { get; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 21) ); } [Fact] public void PropertyReAbstraction_056() { var source1 = @" public interface I1 { int P1 {get;} } public struct C2 : I1 { abstract int I1.P1 { get; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 21) ); } [Fact] public void PropertyReAbstraction_057() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 { get; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.P1' is missing accessor 'I1.P1.set' // abstract int I1.P1 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P1").WithArguments("I2.I1.P1", "I1.P1.set").WithLocation(9, 21), // (9,26): error CS0550: 'I2.I1.P1.get' adds an accessor not found in interface member 'I1.P1' // abstract int I1.P1 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.I1.P1.get", "I1.P1").WithLocation(9, 26), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_058() { var source1 = @" public interface I1 { internal int P1 {get => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.P1 { get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.P1' is inaccessible due to its protection level // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); } [Fact] public void PropertyReAbstraction_059() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 {set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_060() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_061() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 {set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } int I1.P1 { set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.set_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_062() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } int I1.P1 { set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.set_P1"); } [Fact] public void PropertyReAbstraction_063() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_064() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_065() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I2 { int I1.P1 { set { System.Console.WriteLine(""I3.set_P1""); } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.set_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_066() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I2 { int I1.P1 { set { System.Console.WriteLine(""I3.set_P1""); } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.set_P1"); } [Fact] public void PropertyReAbstraction_067() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I1 { abstract int I1.P1 {set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_068() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { int I1.P1 { set => throw null; } } public interface I3 : I1 { abstract int I1.P1 {set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_069() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I1 { int I1.P1 { set => throw null; } } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_070() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I1 { abstract int I1.P1 {set;} } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; ValidatePropertyReAbstraction_012(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_071() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I1 { abstract int I1.P1 {set;} } public interface I4 : I2, I3 { int I1.P1 { set { System.Console.WriteLine(""I4.set_P1""); } } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } } "; ValidatePropertyReAbstraction_013(source1, source2, "I4.set_P1"); } [Fact] public void PropertyReAbstraction_072() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 { set { throw null; } } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.P1.set' cannot declare a body because it is marked abstract // set Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.P1.set").WithLocation(11, 9), // (18,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(18, 15) ); } [Fact] public void PropertyReAbstraction_073() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 { set => throw null; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.P1.set' cannot declare a body because it is marked abstract // set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.P1.set").WithLocation(11, 9), // (15,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(15, 15) ); } [Fact] public void PropertyReAbstraction_074() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { extern abstract int I1.P1 {set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_016(source1, // (9,28): error CS0180: 'I2.I1.P1' cannot be both extern and abstract // extern abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P1").WithArguments("I2.I1.P1").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_075() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract public int I1.P1 { set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,28): error CS0106: The modifier 'public' is not valid for this item // abstract public int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("public").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_076() { var source1 = @" public interface I1 { int P1 {set;} } public class C2 : I1 { abstract int I1.P1 { set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.P1 { set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 21), // (9,26): error CS8051: Auto-implemented properties must have get accessors. // abstract int I1.P1 { set; } Diagnostic(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, "set").WithArguments("C2.I1.P1.set").WithLocation(9, 26) ); } [Fact] public void PropertyReAbstraction_077() { var source1 = @" public interface I1 { int P1 {set;} } public struct C2 : I1 { abstract int I1.P1 { set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.P1 { set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 21), // (9,26): error CS8051: Auto-implemented properties must have get accessors. // abstract int I1.P1 { set; } Diagnostic(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, "set").WithArguments("C2.I1.P1.set").WithLocation(9, 26) ); } [Fact] public void PropertyReAbstraction_078() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 { set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.P1' is missing accessor 'I1.P1.get' // abstract int I1.P1 { set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P1").WithArguments("I2.I1.P1", "I1.P1.get").WithLocation(9, 21), // (9,26): error CS0550: 'I2.I1.P1.set' adds an accessor not found in interface member 'I1.P1' // abstract int I1.P1 { set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.I1.P1.set", "I1.P1").WithLocation(9, 26), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_079() { var source1 = @" public interface I1 { internal int P1 {set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.P1 { set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.P1' is inaccessible due to its protection level // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); } [Fact] public void PropertyReAbstraction_080() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 { get; set; } = 0; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS8053: Instance properties in interfaces cannot have initializers. // abstract int I1.P1 { get; set; } = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P1").WithArguments("I2.I1.P1").WithLocation(9, 21), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_081() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 { get; } = 0; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS8053: Instance properties in interfaces cannot have initializers. // abstract int I1.P1 { get; } = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P1").WithArguments("I2.I1.P1").WithLocation(9, 21), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_082() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 { set; } = 0; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS8053: Instance properties in interfaces cannot have initializers. // abstract int I1.P1 { set; } = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P1").WithArguments("I2.I1.P1").WithLocation(9, 21), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_083() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract int I1.P1 {get; set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (8,21): error CS0539: 'I2.P1' in explicit interface declaration is not found among members of the interface that can be implemented // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("I2.P1").WithLocation(8, 21) ); } private static void ValidatePropertyReAbstraction_083(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<PropertySymbol>().Single(); ValidateReabstraction(i2p1); Assert.Empty(i2p1.ExplicitInterfaceImplementations); if (i2p1.GetMethod is object) { Assert.Empty(i2p1.GetMethod.ExplicitInterfaceImplementations); } if (i2p1.SetMethod is object) { Assert.Empty(i2p1.SetMethod.ExplicitInterfaceImplementations); } } } [Fact] public void PropertyReAbstraction_084() { var source1 = @" public interface I2 : I1 { abstract int I1.P1 {get; set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,18): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 18), // (4,18): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 18) ); } [Fact] public void PropertyReAbstraction_085() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract int I1.P1 {get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (8,21): error CS0539: 'I2.P1' in explicit interface declaration is not found among members of the interface that can be implemented // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("I2.P1").WithLocation(8, 21) ); } [Fact] public void PropertyReAbstraction_086() { var source1 = @" public interface I2 : I1 { abstract int I1.P1 {get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,18): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract int I1.P1 {get;} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 18), // (4,18): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract int I1.P1 {get;} Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 18) ); } [Fact] public void PropertyReAbstraction_087() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract int I1.P1 {set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (8,21): error CS0539: 'I2.P1' in explicit interface declaration is not found among members of the interface that can be implemented // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("I2.P1").WithLocation(8, 21) ); } [Fact] public void PropertyReAbstraction_088() { var source1 = @" public interface I2 : I1 { abstract int I1.P1 {set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,18): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract int I1.P1 {set;} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 18), // (4,18): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract int I1.P1 {set;} Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 18) ); } [Fact] public void PropertyReAbstraction_089() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 {get; set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,25): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(9, 25), // (9,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(9, 30) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,25): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(9, 25), // (9,30): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(9, 30) ); } [Fact] public void PropertyReAbstraction_090() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 {get;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,25): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.P1 {get;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(9, 25) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,25): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.P1 {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(9, 25) ); } [Fact] public void PropertyReAbstraction_091() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 {set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,25): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.P1 {set;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(9, 25) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,25): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.P1 {set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(9, 25) ); } [Fact] public void EventReAbstraction_001() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1; } "; var source2 = @" class Test1 : I2 { } "; ValidateEventReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } private static void ValidateEventReAbstraction_001(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<EventSymbol>().Single(); ValidateReabstraction(i2p1); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i1p1.AddMethod, i2p1.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Same(i1p1.RemoveMethod, i2p1.RemoveMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } private static void ValidateReabstraction(EventSymbol reabstracting) { Assert.True(reabstracting.IsAbstract); Assert.False(reabstracting.IsVirtual); Assert.True(reabstracting.IsSealed); Assert.False(reabstracting.IsStatic); Assert.False(reabstracting.IsExtern); Assert.False(reabstracting.IsOverride); Assert.Equal(Accessibility.Private, reabstracting.DeclaredAccessibility); if (reabstracting.AddMethod is object) { ValidateReabstraction(reabstracting.AddMethod); } if (reabstracting.RemoveMethod is object) { ValidateReabstraction(reabstracting.RemoveMethod); } } [Fact] public void EventReAbstraction_002() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } "; var source2 = @" class Test1 : I2 { } "; ValidateEventReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void EventReAbstraction_003() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1; } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1.P1 += null; i1.P1 -= null; } event System.Action I1.P1 { add { System.Console.WriteLine(""Test1.add_P1""); } remove => System.Console.WriteLine(""Test1.remove_P1""); } } "; ValidateEventReAbstraction_003(source1, source2, @" Test1.add_P1 Test1.remove_P1 "); } private void ValidateEventReAbstraction_003(string source1, string source2, string expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test12p1 = test1.GetMembers().OfType<EventSymbol>().Single(); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<EventSymbol>().Single(); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Same(test12p1, test1.FindImplementationForInterfaceMember(i1p1)); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Same(test12p1.AddMethod, test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Same(test12p1.RemoveMethod, test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void EventReAbstraction_004() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1.P1 += null; i1.P1 -= null; } event System.Action I1.P1 { add { System.Console.WriteLine(""Test1.add_P1""); } remove => System.Console.WriteLine(""Test1.remove_P1""); } } "; ValidateEventReAbstraction_003(source1, source2, @" Test1.add_P1 Test1.remove_P1 "); } [Fact] public void EventReAbstraction_005() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidateEventReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } private static void ValidateEventReAbstraction_005(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i3 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I3", i3.Name); var i1p1 = i3.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.Null(i3.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); Assert.Null(i3.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(i3.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } [Fact] public void EventReAbstraction_006() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidateEventReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void EventReAbstraction_007() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I2 { event System.Action I1.P1 { add { System.Console.WriteLine(""I3.add_P1""); } remove => System.Console.WriteLine(""I3.remove_P1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1.P1 += null; i1.P1 -= null; } } "; ValidateEventReAbstraction_007(source1, source2, @" I3.add_P1 I3.remove_P1 "); } private void ValidateEventReAbstraction_007(string source1, string source2, string expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i3 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I3", i3.Name); var i3p1 = i3.GetMembers().OfType<EventSymbol>().Single(); var i1p1 = i3.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.Same(i3p1, i3.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i3p1, test1.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i3p1.AddMethod, i3.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Same(i3p1.AddMethod, test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Same(i3p1.RemoveMethod, i3.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Same(i3p1.RemoveMethod, test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void EventReAbstraction_008() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I2 { event System.Action I1.P1 { add { System.Console.WriteLine(""I3.add_P1""); } remove => System.Console.WriteLine(""I3.remove_P1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1.P1 += null; i1.P1 -= null; } } "; ValidateEventReAbstraction_007(source1, source2, @" I3.add_P1 I3.remove_P1 "); } [Fact] public void EventReAbstraction_009() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I1 { abstract event System.Action I1.P1; } "; var source2 = @" class Test1 : I2, I3 { } "; ValidateEventReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } private static void ValidateEventReAbstraction_009(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1p1 = test1.InterfacesNoUseSiteDiagnostics().First().ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } [Fact] public void EventReAbstraction_010() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { event System.Action I1.P1 { add => throw null; remove => throw null; } } public interface I3 : I1 { abstract event System.Action I1.P1; } "; var source2 = @" class Test1 : I2, I3 { } "; ValidateEventReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void EventReAbstraction_011() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I1 { event System.Action I1.P1 { add => throw null; remove => throw null; } } "; var source2 = @" class Test1 : I2, I3 { } "; ValidateEventReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void EventReAbstraction_012() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I1 { abstract event System.Action I1.P1; } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; ValidateEventReAbstraction_012(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } private static void ValidateEventReAbstraction_012(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i4 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I4", i4.Name); var i1p1 = i4.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.Null(i4.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); Assert.Null(i4.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(i4.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void EventReAbstraction_013() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I1 { abstract event System.Action I1.P1; } public interface I4 : I2, I3 { event System.Action I1.P1 { add { System.Console.WriteLine(""I4.add_P1""); } remove => System.Console.WriteLine(""I4.remove_P1""); } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); i1.P1 += null; i1.P1 -= null; } } "; ValidateEventReAbstraction_013(source1, source2, @" I4.add_P1 I4.remove_P1 "); } private void ValidateEventReAbstraction_013(string source1, string source2, string expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i4 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I4", i4.Name); var i4p1 = i4.GetMembers().OfType<EventSymbol>().Single(); var i1p1 = i4.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.Same(i4p1, i4.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i4p1, test1.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i4p1.AddMethod, i4.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Same(i4p1.AddMethod, test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Same(i4p1.RemoveMethod, i4.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Same(i4p1.RemoveMethod, test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } [Fact] public void EventReAbstraction_014() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { add { throw null; } remove { throw null; } } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (10,5): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // { Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(10, 5), // (22,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(22, 15) ); } private static void ValidateEventReAbstraction_014(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<EventSymbol>().Single(); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); ValidateReabstraction(i2p1); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.AddMethod is object) { if (i2p1.AddMethod is object) { Assert.Same(i1p1.AddMethod, i2p1.AddMethod.ExplicitInterfaceImplementations.Single()); } Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); } else if (i2p1.AddMethod is object) { Assert.Empty(i2p1.AddMethod.ExplicitInterfaceImplementations); } if (i1p1.RemoveMethod is object) { if (i2p1.RemoveMethod is object) { Assert.Same(i1p1.RemoveMethod, i2p1.RemoveMethod.ExplicitInterfaceImplementations.Single()); } Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } else if (i2p1.RemoveMethod is object) { Assert.Empty(i2p1.RemoveMethod.ExplicitInterfaceImplementations); } } } [Fact] public void EventReAbstraction_015() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { add => throw null; remove => throw null; } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (10,5): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // { Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(10, 5), // (16,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(16, 15) ); } [Fact] public void EventReAbstraction_016() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { extern abstract event System.Action I1.P1; } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,44): error CS0106: The modifier 'extern' is not valid for this item // extern abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("extern").WithLocation(9, 44), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_017() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract public event System.Action I1.P1; } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,44): error CS0106: The modifier 'public' is not valid for this item // abstract public event System.Action I1.P1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("public").WithLocation(9, 44), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_018() { var source1 = @" public interface I1 { event System.Action P1; } public class C2 : I1 { abstract event System.Action I1.P1; } "; ValidateEventReAbstraction_018(source1, // (7,19): error CS0535: 'C2' does not implement interface member 'I1.P1.remove' // public class C2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1.remove").WithLocation(7, 19), // (7,19): error CS0535: 'C2' does not implement interface member 'I1.P1.add' // public class C2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1.add").WithLocation(7, 19), // (9,37): error CS0071: An explicit interface implementation of an event must use event accessor syntax // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "P1").WithLocation(9, 37), // (9,37): error CS0106: The modifier 'abstract' is not valid for this item // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 37) ); } private static void ValidateEventReAbstraction_018(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var c2 = m.GlobalNamespace.GetTypeMember("C2"); var c2p1 = c2.GetMembers().OfType<EventSymbol>().Single(); Assert.False(c2p1.IsAbstract); Assert.False(c2p1.IsSealed); var i1p1 = c2p1.ExplicitInterfaceImplementations.Single(); Assert.Same(c2p1, c2.FindImplementationForInterfaceMember(i1p1)); var c2p1Add = c2p1.AddMethod; if (c2p1Add is object) { Assert.False(c2p1Add.IsAbstract); Assert.False(c2p1Add.IsSealed); Assert.Same(i1p1.AddMethod, c2p1Add.ExplicitInterfaceImplementations.Single()); Assert.Same(c2p1Add, c2.FindImplementationForInterfaceMember(i1p1.AddMethod)); } else { Assert.Null(c2.FindImplementationForInterfaceMember(i1p1.AddMethod)); } var c2p1Remove = c2p1.RemoveMethod; if (c2p1Remove is object) { Assert.False(c2p1Remove.IsAbstract); Assert.False(c2p1Remove.IsSealed); Assert.Same(i1p1.RemoveMethod, c2p1Remove.ExplicitInterfaceImplementations.Single()); Assert.Same(c2p1Remove, c2.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } else { Assert.Null(c2.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } } [Fact] public void EventReAbstraction_019() { var source1 = @" public interface I1 { event System.Action P1; } public class C2 : I1 { abstract event System.Action I1.P1 { add => throw null; remove => throw null; } } "; ValidateEventReAbstraction_018(source1, // (9,37): error CS0106: The modifier 'abstract' is not valid for this item // abstract event System.Action I1.P1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 37) ); } [Fact] public void EventReAbstraction_020() { var source1 = @" public interface I1 { event System.Action P1; } public struct C2 : I1 { abstract event System.Action I1.P1; } "; ValidateEventReAbstraction_018(source1, // (7,20): error CS0535: 'C2' does not implement interface member 'I1.P1.remove' // public struct C2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1.remove").WithLocation(7, 20), // (7,20): error CS0535: 'C2' does not implement interface member 'I1.P1.add' // public struct C2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1.add").WithLocation(7, 20), // (9,37): error CS0071: An explicit interface implementation of an event must use event accessor syntax // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "P1").WithLocation(9, 37), // (9,37): error CS0106: The modifier 'abstract' is not valid for this item // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 37) ); } [Fact] public void EventReAbstraction_021() { var source1 = @" public interface I1 { event System.Action P1; } public struct C2 : I1 { abstract event System.Action I1.P1 { add => throw null; remove => throw null; } } "; ValidateEventReAbstraction_018(source1, // (9,37): error CS0106: The modifier 'abstract' is not valid for this item // abstract event System.Action I1.P1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 37) ); } [Fact] public void EventReAbstraction_022() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { add => throw null; } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,40): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action I1.P1 { add => throw null; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_023() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { add; } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,40): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action I1.P1 { add; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_024() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { remove => throw null; } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,40): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action I1.P1 { remove => throw null; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_025() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { remove; } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,40): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action I1.P1 { remove; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_026() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { add; remove; } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,40): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action I1.P1 { add; remove; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_027() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 {} } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,40): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action I1.P1 {} Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_028() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { add => throw null; remove => throw null; } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,40): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action I1.P1 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_029() { var source1 = @" public interface I1 { event System.Action P1 {add => throw null;} } public interface I2 : I1 { abstract event System.Action I1.P1; } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (4,25): error CS0065: 'I1.P1': event property must have both add and remove accessors // event System.Action P1 {add => throw null;} Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P1").WithArguments("I1.P1").WithLocation(4, 25), // (9,37): error CS0550: 'I2.I1.P1.remove' adds an accessor not found in interface member 'I1.P1' // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "P1").WithArguments("I2.I1.P1.remove", "I1.P1").WithLocation(9, 37), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_030() { var source1 = @" public interface I1 { event System.Action P1 {add => throw null;} } public interface I2 : I1 { abstract event System.Action I1.P1 { add {} remove {} } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (4,25): error CS0065: 'I1.P1': event property must have both add and remove accessors // event System.Action P1 {add => throw null;} Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P1").WithArguments("I1.P1").WithLocation(4, 25), // (10,5): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // { Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(10, 5), // (12,9): error CS0550: 'I2.I1.P1.remove' adds an accessor not found in interface member 'I1.P1' // remove {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "remove").WithArguments("I2.I1.P1.remove", "I1.P1").WithLocation(12, 9), // (16,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(16, 15) ); } [Fact] public void EventReAbstraction_031() { var source1 = @" public interface I1 { event System.Action P1 {remove => throw null;} } public interface I2 : I1 { abstract event System.Action I1.P1; } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (4,25): error CS0065: 'I1.P1': event property must have both add and remove accessors // event System.Action P1 {remove => throw null;} Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P1").WithArguments("I1.P1").WithLocation(4, 25), // (9,37): error CS0550: 'I2.I1.P1.add' adds an accessor not found in interface member 'I1.P1' // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "P1").WithArguments("I2.I1.P1.add", "I1.P1").WithLocation(9, 37), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_032() { var source1 = @" public interface I1 { event System.Action P1 {remove => throw null;} } public interface I2 : I1 { abstract event System.Action I1.P1 { add {} remove {} } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (4,25): error CS0065: 'I1.P1': event property must have both add and remove accessors // event System.Action P1 {remove => throw null;} Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P1").WithArguments("I1.P1").WithLocation(4, 25), // (10,5): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // { Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(10, 5), // (11,9): error CS0550: 'I2.I1.P1.add' adds an accessor not found in interface member 'I1.P1' // add {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "add").WithArguments("I2.I1.P1.add", "I1.P1").WithLocation(11, 9), // (16,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(16, 15) ); } [Fact] public void EventReAbstraction_033() { var source1 = @" public interface I1 { internal event System.Action P1 {add => throw null; remove => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract event System.Action I1.P1; } class Test1 : I2 { } "; ValidateEventReAbstraction_033(source1, source2, // (4,37): error CS0122: 'I1.P1' is inaccessible due to its protection level // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(4, 37), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); } private static void ValidateEventReAbstraction_033(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, references: new[] { reference }, targetFramework: TargetFramework.NetCoreApp); validate(compilation2.SourceModule); compilation2.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<EventSymbol>().Single(); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); ValidateReabstraction(i2p1); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i1p1.AddMethod, i2p1.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Same(i1p1.RemoveMethod, i2p1.RemoveMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } [Fact] public void EventReAbstraction_034() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract event System.Action I1.P1; } class Test1 : I2 { } "; ValidateEventReAbstraction_034(source1, // (8,37): error CS0539: 'I2.P1' in explicit interface declaration is not found among members of the interface that can be implemented // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("I2.P1").WithLocation(8, 37) ); } private static void ValidateEventReAbstraction_034(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<EventSymbol>().Single(); ValidateReabstraction(i2p1); Assert.Empty(i2p1.ExplicitInterfaceImplementations); Assert.Empty(i2p1.AddMethod.ExplicitInterfaceImplementations); Assert.Empty(i2p1.RemoveMethod.ExplicitInterfaceImplementations); } } [Fact] public void EventReAbstraction_035() { var source1 = @" public interface I2 : I1 { abstract event System.Action I1.P1; } class Test1 : I2 { } "; ValidateEventReAbstraction_034(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,34): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 34), // (4,34): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 34) ); } [Fact] public void EventReAbstraction_036() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,36): error CS0071: An explicit interface implementation of an event must use event accessor syntax // abstract event System.Action I1.P1 Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, ".").WithLocation(9, 36), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_037() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,37): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "P1").WithArguments("default interface implementation", "8.0").WithLocation(9, 37) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,37): error CS8701: Target runtime doesn't support default interface implementation. // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P1").WithLocation(9, 37) ); } [Fact] public void IndexerReAbstraction_001() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_002() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_003() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; i1[0] = 1; } int I1.this[int i] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set => System.Console.WriteLine(""Test1.set_P1""); } } "; ValidatePropertyReAbstraction_003(source1, source2, @" Test1.get_P1 Test1.set_P1 "); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_004() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; i1[0] = 1; } int I1.this[int i] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set => System.Console.WriteLine(""Test1.set_P1""); } } "; ValidatePropertyReAbstraction_003(source1, source2, @" Test1.get_P1 Test1.set_P1 "); } [Fact] public void IndexerReAbstraction_005() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_006() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_007() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I2 { int I1.this[int i] { get { System.Console.WriteLine(""I3.get_P1""); return 0; } set => System.Console.WriteLine(""I3.set_P1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; i1[0] = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, @" I3.get_P1 I3.set_P1 "); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_008() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I2 { int I1.this[int i] { get { System.Console.WriteLine(""I3.get_P1""); return 0; } set => System.Console.WriteLine(""I3.set_P1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; i1[0] = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, @" I3.get_P1 I3.set_P1 "); } [Fact] public void IndexerReAbstraction_009() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I1 { abstract int I1.this[int i] {get; set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_010() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { int I1.this[int i] { get => throw null; set => throw null; } } public interface I3 : I1 { abstract int I1.this[int i] {get; set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_011() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I1 { int I1.this[int i] { get => throw null; set => throw null; } } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_012() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I1 { abstract int I1.this[int i] {get; set;} } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; ValidatePropertyReAbstraction_012(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_013() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I1 { abstract int I1.this[int i] {get; set;} } public interface I4 : I2, I3 { int I1.this[int i] { get { System.Console.WriteLine(""I4.get_P1""); return 0; } set => System.Console.WriteLine(""I4.set_P1""); } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; i1[0] = 1; } } "; ValidatePropertyReAbstraction_013(source1, source2, @" I4.get_P1 I4.set_P1 "); } [Fact] public void IndexerReAbstraction_014() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] { get { throw null; } set { throw null; } } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.this[int].get' cannot declare a body because it is marked abstract // get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.this[int].get").WithLocation(11, 9), // (15,9): error CS0500: 'I2.I1.this[int].set' cannot declare a body because it is marked abstract // set Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.this[int].set").WithLocation(15, 9), // (22,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(22, 15) ); } [Fact] public void IndexerReAbstraction_015() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] { get => throw null; set => throw null; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.this[int].get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.this[int].get").WithLocation(11, 9), // (12,9): error CS0500: 'I2.I1.this[int].set' cannot declare a body because it is marked abstract // set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.this[int].set").WithLocation(12, 9), // (16,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(16, 15) ); } [Fact] public void IndexerReAbstraction_016() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { extern abstract int I1.this[int i] {get; set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_016(source1, // (9,28): error CS0180: 'I2.I1.this[int]' cannot be both extern and abstract // extern abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "this").WithArguments("I2.I1.this[int]").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_017() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract public int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,28): error CS0106: The modifier 'public' is not valid for this item // abstract public int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("public").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_018() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public class C2 : I1 { abstract int I1.this[int i] { get; set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(9, 21), // (9,35): error CS0501: 'C2.I1.this[int].get' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("C2.I1.this[int].get").WithLocation(9, 35), // (9,40): error CS0501: 'C2.I1.this[int].set' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("C2.I1.this[int].set").WithLocation(9, 40) ); } [Fact] public void IndexerReAbstraction_019() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public struct C2 : I1 { abstract int I1.this[int i] { get; set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(9, 21), // (9,35): error CS0501: 'C2.I1.this[int].get' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("C2.I1.this[int].get").WithLocation(9, 35), // (9,40): error CS0501: 'C2.I1.this[int].set' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("C2.I1.this[int].set").WithLocation(9, 40) ); } [Fact] public void IndexerReAbstraction_020() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] { get; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.this[int]' is missing accessor 'I1.this[int].set' // abstract int I1.this[int i] { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("I2.I1.this[int]", "I1.this[int].set").WithLocation(9, 21), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_021() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] { set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.this[int]' is missing accessor 'I1.this[int].get' // abstract int I1.this[int i] { set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("I2.I1.this[int]", "I1.this[int].get").WithLocation(9, 21), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_022() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,40): error CS0550: 'I2.I1.this[int].set' adds an accessor not found in interface member 'I1.this[int]' // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.I1.this[int].set", "I1.this[int]").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_023() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,35): error CS0550: 'I2.I1.this[int].get' adds an accessor not found in interface member 'I1.this[int]' // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.I1.this[int].get", "I1.this[int]").WithLocation(9, 35), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_024() { var source1 = @" public interface I1 { int this[int i] {get => throw null; private set => throw null;} } public interface I2 : I1 { abstract int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,40): error CS0550: 'I2.I1.this[int].set' adds an accessor not found in interface member 'I1.this[int]' // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.I1.this[int].set", "I1.this[int]").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_025() { var source1 = @" public interface I1 { int this[int i] {private get => throw null; set => throw null;} } public interface I2 : I1 { abstract int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,35): error CS0550: 'I2.I1.this[int].get' adds an accessor not found in interface member 'I1.this[int]' // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.I1.this[int].get", "I1.this[int]").WithLocation(9, 35), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_026() { var source1 = @" public interface I1 { internal int this[int i] {get => throw null; set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int]").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(7, 15) ); } [Fact] public void IndexerReAbstraction_027() { var source1 = @" public interface I1 { int this[int i] {internal get => throw null; set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.this[int].get' is inaccessible due to its protection level // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int].get").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(7, 15) ); } [Fact] public void IndexerReAbstraction_028() { var source1 = @" public interface I1 { int this[int i] {get => throw null; internal set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.this[int].set' is inaccessible due to its protection level // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int].set").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(7, 15) ); } [Fact] public void IndexerReAbstraction_037() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] {get;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_038() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_039() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] {get;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; } int I1.this[int i] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.get_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_040() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; } int I1.this[int i] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.get_P1"); } [Fact] public void IndexerReAbstraction_041() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_042() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_043() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I2 { int I1.this[int i] { get { System.Console.WriteLine(""I3.get_P1""); return 0; } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.get_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_044() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I2 { int I1.this[int i] { get { System.Console.WriteLine(""I3.get_P1""); return 0; } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.get_P1"); } [Fact] public void IndexerReAbstraction_045() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I1 { abstract int I1.this[int i] {get;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_046() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { int I1.this[int i] { get => throw null; } } public interface I3 : I1 { abstract int I1.this[int i] {get;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_047() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I1 { int I1.this[int i] { get => throw null; } } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_048() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I1 { abstract int I1.this[int i] {get;} } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; ValidatePropertyReAbstraction_012(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_049() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I1 { abstract int I1.this[int i] {get;} } public interface I4 : I2, I3 { int I1.this[int i] { get { System.Console.WriteLine(""I4.get_P1""); return 0; } } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "; ValidatePropertyReAbstraction_013(source1, source2, "I4.get_P1"); } [Fact] public void IndexerReAbstraction_050() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] { get { throw null; } } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.this[int].get' cannot declare a body because it is marked abstract // get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.this[int].get").WithLocation(11, 9), // (18,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(18, 15) ); } [Fact] public void IndexerReAbstraction_051() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] { get => throw null; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.this[int].get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.this[int].get").WithLocation(11, 9), // (15,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(15, 15) ); } [Fact] public void IndexerReAbstraction_052() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] => throw null; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,36): error CS0500: 'I2.I1.this[int].get' cannot declare a body because it is marked abstract // abstract int I1.this[int i] => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "throw null").WithArguments("I2.I1.this[int].get").WithLocation(9, 36), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_053() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { extern abstract int I1.this[int i] {get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_016(source1, // (9,28): error CS0180: 'I2.I1.this[int]' cannot be both extern and abstract // extern abstract int I1.this[int i] {get;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "this").WithArguments("I2.I1.this[int]").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_054() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract public int I1.this[int i] { get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,28): error CS0106: The modifier 'public' is not valid for this item // abstract public int I1.this[int i] { get;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("public").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_055() { var source1 = @" public interface I1 { int this[int i] {get;} } public class C2 : I1 { abstract int I1.this[int i] { get; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.this[int i] { get; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(9, 21), // (9,35): error CS0501: 'C2.I1.this[int].get' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { get; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("C2.I1.this[int].get").WithLocation(9, 35) ); } [Fact] public void IndexerReAbstraction_056() { var source1 = @" public interface I1 { int this[int i] {get;} } public struct C2 : I1 { abstract int I1.this[int i] { get; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.this[int i] { get; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(9, 21), // (9,35): error CS0501: 'C2.I1.this[int].get' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { get; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("C2.I1.this[int].get").WithLocation(9, 35) ); } [Fact] public void IndexerReAbstraction_057() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] { get; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.this[int]' is missing accessor 'I1.this[int].set' // abstract int I1.this[int i] { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("I2.I1.this[int]", "I1.this[int].set").WithLocation(9, 21), // (9,35): error CS0550: 'I2.I1.this[int].get' adds an accessor not found in interface member 'I1.this[int]' // abstract int I1.this[int i] { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.I1.this[int].get", "I1.this[int]").WithLocation(9, 35), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_058() { var source1 = @" public interface I1 { internal int this[int i] {get => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.this[int i] { get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // abstract int I1.this[int i] { get;} Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int]").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(7, 15) ); } [Fact] public void IndexerReAbstraction_059() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] {set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_060() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_061() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] {set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } int I1.this[int i] { set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.set_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_062() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } int I1.this[int i] { set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.set_P1"); } [Fact] public void IndexerReAbstraction_063() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_064() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_065() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I2 { int I1.this[int i] { set { System.Console.WriteLine(""I3.set_P1""); } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.set_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_066() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I2 { int I1.this[int i] { set { System.Console.WriteLine(""I3.set_P1""); } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.set_P1"); } [Fact] public void IndexerReAbstraction_067() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I1 { abstract int I1.this[int i] {set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_068() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { int I1.this[int i] { set => throw null; } } public interface I3 : I1 { abstract int I1.this[int i] {set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_069() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I1 { int I1.this[int i] { set => throw null; } } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_070() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I1 { abstract int I1.this[int i] {set;} } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; ValidatePropertyReAbstraction_012(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_071() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I1 { abstract int I1.this[int i] {set;} } public interface I4 : I2, I3 { int I1.this[int i] { set { System.Console.WriteLine(""I4.set_P1""); } } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } } "; ValidatePropertyReAbstraction_013(source1, source2, "I4.set_P1"); } [Fact] public void IndexerReAbstraction_072() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] { set { throw null; } } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.this[int].set' cannot declare a body because it is marked abstract // set Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.this[int].set").WithLocation(11, 9), // (18,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(18, 15) ); } [Fact] public void IndexerReAbstraction_073() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] { set => throw null; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.this[int].set' cannot declare a body because it is marked abstract // set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.this[int].set").WithLocation(11, 9), // (15,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(15, 15) ); } [Fact] public void IndexerReAbstraction_074() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { extern abstract int I1.this[int i] {set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_016(source1, // (9,28): error CS0180: 'I2.I1.this[int]' cannot be both extern and abstract // extern abstract int I1.this[int i] {set;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "this").WithArguments("I2.I1.this[int]").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_075() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract public int I1.this[int i] { set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,28): error CS0106: The modifier 'public' is not valid for this item // abstract public int I1.this[int i] { set;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("public").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_076() { var source1 = @" public interface I1 { int this[int i] {set;} } public class C2 : I1 { abstract int I1.this[int i] { set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.this[int i] { set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(9, 21), // (9,35): error CS0501: 'C2.I1.this[int].set' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { set; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("C2.I1.this[int].set").WithLocation(9, 35) ); } [Fact] public void IndexerReAbstraction_077() { var source1 = @" public interface I1 { int this[int i] {set;} } public struct C2 : I1 { abstract int I1.this[int i] { set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.this[int i] { set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(9, 21), // (9,35): error CS0501: 'C2.I1.this[int].set' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { set; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("C2.I1.this[int].set").WithLocation(9, 35) ); } [Fact] public void IndexerReAbstraction_078() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] { set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.this[int]' is missing accessor 'I1.this[int].get' // abstract int I1.this[int i] { set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("I2.I1.this[int]", "I1.this[int].get").WithLocation(9, 21), // (9,35): error CS0550: 'I2.I1.this[int].set' adds an accessor not found in interface member 'I1.this[int]' // abstract int I1.this[int i] { set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.I1.this[int].set", "I1.this[int]").WithLocation(9, 35), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_079() { var source1 = @" public interface I1 { internal int this[int i] {set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.this[int i] { set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // abstract int I1.this[int i] { set;} Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int]").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(7, 15) ); } [Fact] public void IndexerReAbstraction_080() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] { get; set; } = 0; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,47): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // abstract int I1.this[int i] { get; set; } = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(9, 47), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_081() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] { get; } = 0; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,42): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // abstract int I1.this[int i] { get; } = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(9, 42), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_082() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] { set; } = 0; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,42): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // abstract int I1.this[int i] { set; } = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(9, 42), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_083() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (8,21): error CS0539: 'I2.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("I2.this[int]").WithLocation(8, 21) ); } [Fact] public void IndexerReAbstraction_084() { var source1 = @" public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,18): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 18), // (4,18): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 18) ); } [Fact] public void IndexerReAbstraction_085() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract int I1.this[int i] {get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (8,21): error CS0539: 'I2.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // abstract int I1.this[int i] {get;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("I2.this[int]").WithLocation(8, 21) ); } [Fact] public void IndexerReAbstraction_086() { var source1 = @" public interface I2 : I1 { abstract int I1.this[int i] {get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,18): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract int I1.this[int i] {get;} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 18), // (4,18): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract int I1.this[int i] {get;} Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 18) ); } [Fact] public void IndexerReAbstraction_087() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract int I1.this[int i] {set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (8,21): error CS0539: 'I2.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // abstract int I1.this[int i] {set;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("I2.this[int]").WithLocation(8, 21) ); } [Fact] public void IndexerReAbstraction_088() { var source1 = @" public interface I2 : I1 { abstract int I1.this[int i] {set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,18): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract int I1.this[int i] {set;} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 18), // (4,18): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract int I1.this[int i] {set;} Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 18) ); } [Fact] public void IndexerReAbstraction_089() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,34): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(9, 34), // (9,39): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(9, 39) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,34): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(9, 34), // (9,39): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(9, 39) ); } [Fact] public void IndexerReAbstraction_090() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] {get;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,34): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.this[int i] {get;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(9, 34) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,34): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.this[int i] {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(9, 34) ); } [Fact] public void IndexerReAbstraction_091() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] {set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,34): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.this[int i] {set;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(9, 34) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,34): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.this[int i] {set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(9, 34) ); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void ImplicitImplementationOfNonPublicMethod_01() { var ilSource = @" .class interface public abstract auto ansi I1 { .method assembly hidebysig newslot strict virtual instance string M() cil managed { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""I1.M"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } // end of method I1::M .method public hidebysig instance string Test() cil managed { // Code size 12 (0xc) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: callvirt instance string I1::M() IL_0007: stloc.0 IL_0008: br.s IL_000a IL_000a: ldloc.0 IL_000b: ret } // end of method I1::Test } // end of class I1 .class public auto ansi beforefieldinit C0 extends System.Object implements I1 { .method public hidebysig newslot virtual instance string M() cil managed { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""C0.M"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } // end of method C0::M .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C0::.ctor } // end of class C0 "; var source1 = @" class Test { static void Main() { I1 x = new C0(); System.Console.WriteLine(x.Test()); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: "C0.M"); var c0 = compilation1.GetTypeByMetadataName("C0"); var i1M = compilation1.GetMember<MethodSymbol>("I1.M"); Assert.Equal("System.String C0.M()", c0.FindImplementationForInterfaceMember(i1M).ToTestDisplayString()); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void ImplicitImplementationOfNonPublicMethod_02() { var ilSource = @" .class interface public abstract auto ansi I1 { .method assembly hidebysig newslot strict virtual instance string M() cil managed { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""I1.M"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } // end of method I1::M .method public hidebysig instance string Test() cil managed { // Code size 12 (0xc) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: callvirt instance string I1::M() IL_0007: stloc.0 IL_0008: br.s IL_000a IL_000a: ldloc.0 IL_000b: ret } // end of method I1::Test } // end of class I1 .class public auto ansi beforefieldinit C0 extends System.Object implements I1 { .method public hidebysig newslot virtual instance string M() cil managed { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""C0.M"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } // end of method C0::M .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C0::.ctor } // end of class C0 "; var source1 = @" class Test : C0, I1 { static void Main() { I1 x = new Test(); System.Console.WriteLine(x.Test()); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: "C0.M"); var test = compilation1.GetTypeByMetadataName("Test"); var i1M = compilation1.GetMember<MethodSymbol>("I1.M"); Assert.Equal("System.String C0.M()", test.FindImplementationForInterfaceMember(i1M).ToTestDisplayString()); } [Fact] public void ImplicitImplementationOfNonPublicMethod_03() { var source1 = @" public interface I1 { internal string M() { return ""I1.M""; } public sealed string Test() { return M(); } } public class C0 : I1 { public virtual string M() { return ""C0.M""; } } class Test : C0, I1 { static void Main() { I1 x = new Test(); System.Console.WriteLine(x.Test()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); var i1M = compilation1.GetMember<MethodSymbol>("I1.M"); var c0 = compilation1.GetTypeByMetadataName("C0"); var test = compilation1.GetTypeByMetadataName("Test"); Assert.Equal("System.String C0.M()", c0.FindImplementationForInterfaceMember(i1M).ToTestDisplayString()); Assert.Equal("System.String C0.M()", test.FindImplementationForInterfaceMember(i1M).ToTestDisplayString()); compilation1.VerifyDiagnostics( // (15,19): error CS8704: 'C0' does not implement interface member 'I1.M()'. 'C0.M()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class C0 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("C0", "I1.M()", "C0.M()", "9.0", "10.0").WithLocation(15, 19) ); compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); i1M = compilation1.GetMember<MethodSymbol>("I1.M"); c0 = compilation1.GetTypeByMetadataName("C0"); test = compilation1.GetTypeByMetadataName("Test"); Assert.Equal("System.String C0.M()", c0.FindImplementationForInterfaceMember(i1M).ToTestDisplayString()); Assert.Equal("System.String C0.M()", test.FindImplementationForInterfaceMember(i1M).ToTestDisplayString()); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "C0.M", verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] public void ImplicitImplementationOfNonPublicMethod_04() { var source1 = @" public interface I1 { internal int get_P(); } public class C0 : I1 { public virtual int P { get; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,19): error CS8704: 'C0' does not implement interface member 'I1.get_P()'. 'C0.P.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class C0 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("C0", "I1.get_P()", "C0.P.get", "9.0", "10.0").WithLocation(7, 19), // (9,28): error CS0686: Accessor 'C0.P.get' cannot implement interface member 'I1.get_P()' for type 'C0'. Use an explicit interface implementation. // public virtual int P { get; } Diagnostic(ErrorCode.ERR_AccessorImplementingMethod, "get").WithArguments("C0.P.get", "I1.get_P()", "C0").WithLocation(9, 28) ); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,28): error CS0686: Accessor 'C0.P.get' cannot implement interface member 'I1.get_P()' for type 'C0'. Use an explicit interface implementation. // public virtual int P { get; } Diagnostic(ErrorCode.ERR_AccessorImplementingMethod, "get").WithArguments("C0.P.get", "I1.get_P()", "C0").WithLocation(9, 28) ); } private static string BuildAssemblyExternClause(PortableExecutableReference reference) { AssemblyIdentity assemblyIdentity = ((AssemblyMetadata)reference.GetMetadata()).GetAssembly().Identity; Version version = assemblyIdentity.Version; var publicKeyToken = assemblyIdentity.PublicKeyToken; if (publicKeyToken.Length > 0) { return @" .assembly extern " + assemblyIdentity.Name + @" { .publickeytoken = (" + publicKeyToken[0].ToString("X2") + publicKeyToken[1].ToString("X2") + publicKeyToken[2].ToString("X2") + publicKeyToken[3].ToString("X2") + publicKeyToken[4].ToString("X2") + publicKeyToken[5].ToString("X2") + publicKeyToken[6].ToString("X2") + publicKeyToken[7].ToString("X2") + @" ) .ver " + $"{version.Major}:{version.Minor}:{version.Build}:{version.Revision}" + @" } "; } else { return @" .assembly extern " + assemblyIdentity.Name + @" { .ver " + $"{version.Major}:{version.Minor}:{version.Build}:{version.Revision}" + @" } "; } } [Fact] [WorkItem(36532, "https://github.com/dotnet/roslyn/issues/36532")] public void WindowsRuntimeEvent_01() { var windowsRuntimeRef = CompilationExtensions.CreateWindowsRuntimeMetadataReference(); var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + BuildAssemblyExternClause(windowsRuntimeRef) + @" .class public auto ansi sealed Event extends [System.Runtime]System.MulticastDelegate { .method private hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public hidebysig newslot specialname virtual instance void Invoke() runtime managed { } } // end of class Event .class interface public abstract auto ansi Interface`1<T> { .method public hidebysig newslot specialname abstract virtual instance void add_Normal(class Event 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance void remove_Normal(class Event 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance valuetype [System.Runtime.InteropServices.WindowsRuntime]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken add_WinRT([in] class Event 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance void remove_WinRT([in] valuetype [System.Runtime.InteropServices.WindowsRuntime]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken 'value') cil managed { } .event Event Normal { .addon instance void Interface`1::add_Normal(class Event) .removeon instance void Interface`1::remove_Normal(class Event) } // end of event I`1::Normal .event Event WinRT { .addon instance valuetype [System.Runtime.InteropServices.WindowsRuntime]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken Interface`1::add_WinRT(class Event) .removeon instance void Interface`1::remove_WinRT(valuetype [System.Runtime.InteropServices.WindowsRuntime]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) } } // end of class Interface "; var source = @" interface I1 : Interface<int> { event Event Interface<int>.Normal { add { throw null; } remove { throw null; } } event Event Interface<int>.WinRT { add { return new System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken(); } remove { System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken x = value; x.ToString(); } } } class C1 : I1, Interface<int> {} "; foreach (var options in new[] { TestOptions.DebugDll, TestOptions.DebugWinMD }) { var comp = CreateCompilationWithIL(source, ilSource, options: options, targetFramework: TargetFramework.NetCoreApp, references: new[] { windowsRuntimeRef }); void Validate(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var c1 = m.GlobalNamespace.GetTypeMember("C1"); var baseInterface = i1.Interfaces().Single(); Assert.True(baseInterface.IsInterface); Assert.True(i1.IsInterface); var i1Normal = i1.GetMember<EventSymbol>("Interface<System.Int32>.Normal"); var i1WinRT = i1.GetMember<EventSymbol>("Interface<System.Int32>.WinRT"); var baseInterfaceNormal = baseInterface.GetMember<EventSymbol>("Normal"); var baseInterfaceWinRT = baseInterface.GetMember<EventSymbol>("WinRT"); Assert.False(baseInterfaceNormal.IsWindowsRuntimeEvent); Assert.False(i1Normal.IsWindowsRuntimeEvent); Assert.True(baseInterfaceWinRT.IsWindowsRuntimeEvent); Assert.True(i1WinRT.IsWindowsRuntimeEvent); Assert.Same(i1Normal, i1.FindImplementationForInterfaceMember(baseInterfaceNormal)); Assert.Same(i1Normal.AddMethod, i1.FindImplementationForInterfaceMember(baseInterfaceNormal.AddMethod)); Assert.Same(i1Normal.RemoveMethod, i1.FindImplementationForInterfaceMember(baseInterfaceNormal.RemoveMethod)); Assert.Same(i1WinRT, i1.FindImplementationForInterfaceMember(baseInterfaceWinRT)); Assert.Same(i1WinRT.AddMethod, i1.FindImplementationForInterfaceMember(baseInterfaceWinRT.AddMethod)); Assert.Same(i1WinRT.RemoveMethod, i1.FindImplementationForInterfaceMember(baseInterfaceWinRT.RemoveMethod)); Assert.Same(i1Normal, c1.FindImplementationForInterfaceMember(baseInterfaceNormal)); Assert.Same(i1Normal.AddMethod, c1.FindImplementationForInterfaceMember(baseInterfaceNormal.AddMethod)); Assert.Same(i1Normal.RemoveMethod, c1.FindImplementationForInterfaceMember(baseInterfaceNormal.RemoveMethod)); Assert.Same(i1WinRT, c1.FindImplementationForInterfaceMember(baseInterfaceWinRT)); Assert.Same(i1WinRT.AddMethod, c1.FindImplementationForInterfaceMember(baseInterfaceWinRT.AddMethod)); Assert.Same(i1WinRT.RemoveMethod, c1.FindImplementationForInterfaceMember(baseInterfaceWinRT.RemoveMethod)); Assert.Equal("void I1.Interface<System.Int32>.Normal.add", i1Normal.AddMethod.ToTestDisplayString()); Assert.Equal("void I1.Interface<System.Int32>.Normal.remove", i1Normal.RemoveMethod.ToTestDisplayString()); Assert.Equal("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken I1.Interface<System.Int32>.WinRT.add", i1WinRT.AddMethod.ToTestDisplayString()); Assert.Equal("void I1.Interface<System.Int32>.WinRT.remove", i1WinRT.RemoveMethod.ToTestDisplayString()); } Validate(comp.SourceModule); CompileAndVerify(comp, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); } } [Fact] [WorkItem(36532, "https://github.com/dotnet/roslyn/issues/36532")] public void WindowsRuntimeEvent_02() { var source = @" interface I1 { event System.Action WinRT { add { return new System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken(); } remove { System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken x = value; x.ToString(); } } } class C1 : I1 { } "; var comp = CreateCompilation(source, options: TestOptions.DebugWinMD, targetFramework: TargetFramework.NetCoreApp, references: new[] { CompilationExtensions.CreateWindowsRuntimeMetadataReference() }); void Validate(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var c1 = m.GlobalNamespace.GetTypeMember("C1"); var i1WinRT = i1.GetMember<EventSymbol>("WinRT"); Assert.True(i1WinRT.IsWindowsRuntimeEvent); Assert.Same(i1WinRT, c1.FindImplementationForInterfaceMember(i1WinRT)); Assert.Same(i1WinRT.AddMethod, c1.FindImplementationForInterfaceMember(i1WinRT.AddMethod)); Assert.Same(i1WinRT.RemoveMethod, c1.FindImplementationForInterfaceMember(i1WinRT.RemoveMethod)); Assert.Equal("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken I1.WinRT.add", i1WinRT.AddMethod.ToTestDisplayString()); Assert.Equal("void I1.WinRT.remove", i1WinRT.RemoveMethod.ToTestDisplayString()); } Validate(comp.SourceModule); CompileAndVerify(comp, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); } [Fact] [WorkItem(36532, "https://github.com/dotnet/roslyn/issues/36532")] public void WindowsRuntimeEvent_03() { var source = @" interface Interface { event System.Action WinRT; } interface I1 : Interface { event System.Action Interface.WinRT { add { return new System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken(); } remove { System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken x = value; x.ToString(); } } } class C1 : I1, Interface {} "; var comp = CreateCompilation(source, options: TestOptions.DebugWinMD, targetFramework: TargetFramework.NetCoreApp, references: new[] { CompilationExtensions.CreateWindowsRuntimeMetadataReference() }); void Validate(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var c1 = m.GlobalNamespace.GetTypeMember("C1"); var baseInterface = i1.Interfaces().Single(); Assert.True(baseInterface.IsInterface); Assert.True(i1.IsInterface); var i1WinRT = i1.GetMember<EventSymbol>("Interface.WinRT"); var baseInterfaceWinRT = baseInterface.GetMember<EventSymbol>("WinRT"); Assert.True(baseInterfaceWinRT.IsWindowsRuntimeEvent); Assert.True(i1WinRT.IsWindowsRuntimeEvent); Assert.Same(i1WinRT, i1.FindImplementationForInterfaceMember(baseInterfaceWinRT)); Assert.Same(i1WinRT.AddMethod, i1.FindImplementationForInterfaceMember(baseInterfaceWinRT.AddMethod)); Assert.Same(i1WinRT.RemoveMethod, i1.FindImplementationForInterfaceMember(baseInterfaceWinRT.RemoveMethod)); Assert.Same(i1WinRT, c1.FindImplementationForInterfaceMember(baseInterfaceWinRT)); Assert.Same(i1WinRT.AddMethod, c1.FindImplementationForInterfaceMember(baseInterfaceWinRT.AddMethod)); Assert.Same(i1WinRT.RemoveMethod, c1.FindImplementationForInterfaceMember(baseInterfaceWinRT.RemoveMethod)); Assert.Equal("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken I1.Interface.WinRT.add", i1WinRT.AddMethod.ToTestDisplayString()); Assert.Equal("void I1.Interface.WinRT.remove", i1WinRT.RemoveMethod.ToTestDisplayString()); } Validate(comp.SourceModule); CompileAndVerify(comp, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_01() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P1() cil managed { } // end of method I1::get_P1 .method public hidebysig newslot specialname abstract virtual instance int32 get_P2() cil managed { } // end of method I1::get_P2 .method public hidebysig newslot specialname abstract virtual instance void set_P2(int32 'value') cil managed { } // end of method I1::set_P2 .method public hidebysig newslot specialname abstract virtual instance void set_P3(int32 'value') cil managed { } // end of method I1::set_P3 .method public hidebysig newslot specialname abstract virtual instance void add_E1(class [System.Runtime]System.Action 'value') cil managed { } // end of method I1::add_E1 .method public hidebysig newslot specialname abstract virtual instance void remove_E1(class [System.Runtime]System.Action 'value') cil managed { } // end of method I1::remove_E1 .event [System.Runtime]System.Action E1 { .addon instance void I1::add_E1(class [System.Runtime]System.Action) .removeon instance void I1::remove_E1(class [System.Runtime]System.Action) } // end of event I1::E1 .property instance int32 P1() { .get instance int32 I1::get_P1() } // end of property I1::P1 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 .property instance int32 P3() { .set instance void I1::set_P3(int32) } // end of property I1::P3 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object implements I1 { .method private hidebysig newslot specialname virtual final instance int32 I1.get_P1() cil managed { .override I1::get_P1 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.get_P1 .method private hidebysig newslot specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.get_P2 .method private hidebysig newslot specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.set_P2 .method private hidebysig newslot specialname virtual final instance void I1.set_P3(int32 'value') cil managed { .override I1::set_P3 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.set_P3 .method private hidebysig newslot specialname virtual final instance void I1.add_E1(class [System.Runtime]System.Action 'value') cil managed { .override I1::add_E1 // Code size 3 (0x3) .maxstack 8 IL_0000: nop IL_0001: ldnull IL_0002: throw } // end of method C1::I1.add_E1 .method private hidebysig newslot specialname virtual final instance void I1.remove_E1(class [System.Runtime]System.Action 'value') cil managed { .override I1::remove_E1 // Code size 3 (0x3) .maxstack 8 IL_0000: nop IL_0001: ldnull IL_0002: throw } // end of method C1::I1.remove_E1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor } // end of class C1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P1() cil managed { .override I1::get_P1 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P1 .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .method private hidebysig specialname virtual final instance void I1.set_P3(int32 'value') cil managed { .override I1::set_P3 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P3 .method private hidebysig specialname virtual final instance void I1.add_E1(class [System.Runtime]System.Action 'value') cil managed { .override I1::add_E1 // Code size 3 (0x3) .maxstack 8 IL_0000: nop IL_0001: ldnull IL_0002: throw } // end of method I2::I1.add_E1 .method private hidebysig specialname virtual final instance void I1.remove_E1(class [System.Runtime]System.Action 'value') cil managed { .override I1::remove_E1 // Code size 3 (0x3) .maxstack 8 IL_0000: nop IL_0001: ldnull IL_0002: throw } // end of method I2::I1.remove_E1 } // end of class I2 "; var source1 = @" class Test1 : C1, I1 { } class Test2 : I2, I1 { } class Test3 : I2 { public long P1 {get => throw null;} public long P2 {get => throw null; set => throw null;} public long P3 {set => throw null;} } class Test4 : C1, I1 { public long P1 {get => throw null;} public long P2 {get => throw null; set => throw null;} public long P3 {set => throw null;} } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,19): error CS0535: 'Test2' does not implement interface member 'I1.E1' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.E1").WithLocation(6, 19), // (6,19): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(6, 19), // (6,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(6, 19), // (6,19): error CS0535: 'Test2' does not implement interface member 'I1.P3' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P3").WithLocation(6, 19), // (10,15): error CS0535: 'Test3' does not implement interface member 'I1.E1' // class Test3 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test3", "I1.E1").WithLocation(10, 15), // (10,15): error CS0738: 'Test3' does not implement interface member 'I1.P1'. 'Test3.P1' cannot implement 'I1.P1' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P1", "Test3.P1", "int").WithLocation(10, 15), // (10,15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(10, 15), // (10,15): error CS0738: 'Test3' does not implement interface member 'I1.P3'. 'Test3.P3' cannot implement 'I1.P3' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P3", "Test3.P3", "int").WithLocation(10, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var c1 = compilation1.GetTypeByMetadataName("C1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var test4 = compilation1.GetTypeByMetadataName("Test4"); var i1P1 = i1.GetMember<PropertySymbol>("P1"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i1P3 = i1.GetMember<PropertySymbol>("P3"); var i1E1 = i1.GetMember<EventSymbol>("E1"); var i2i1P1get = i2.GetMember<MethodSymbol>("I1.get_P1"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); var i2i1P3set = i2.GetMember<MethodSymbol>("I1.set_P3"); var i2i1E1add = i2.GetMember<MethodSymbol>("I1.add_E1"); var i2i1E1remove = i2.GetMember<MethodSymbol>("I1.remove_E1"); var c1i1P1get = c1.GetMember<MethodSymbol>("I1.get_P1"); var c1i1P2get = c1.GetMember<MethodSymbol>("I1.get_P2"); var c1i1P2set = c1.GetMember<MethodSymbol>("I1.set_P2"); var c1i1P3set = c1.GetMember<MethodSymbol>("I1.set_P3"); var c1i1E1add = c1.GetMember<MethodSymbol>("I1.add_E1"); var c1i1E1remove = c1.GetMember<MethodSymbol>("I1.remove_E1"); Assert.Null(i2.FindImplementationForInterfaceMember(i1P1)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P3)); Assert.Null(i2.FindImplementationForInterfaceMember(i1E1)); Assert.Same(i2i1P1get, test2.FindImplementationForInterfaceMember(i1P1.GetMethod)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(i2i1P3set, test2.FindImplementationForInterfaceMember(i1P3.SetMethod)); Assert.Same(i2i1E1add, test2.FindImplementationForInterfaceMember(i1E1.AddMethod)); Assert.Same(i2i1E1remove, test2.FindImplementationForInterfaceMember(i1E1.RemoveMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P3)); Assert.Null(test2.FindImplementationForInterfaceMember(i1E1)); Assert.Same(c1i1P1get, test1.FindImplementationForInterfaceMember(i1P1.GetMethod)); Assert.Same(c1i1P2get, test1.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test1.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(c1i1P3set, test1.FindImplementationForInterfaceMember(i1P3.SetMethod)); Assert.Same(c1i1E1add, test1.FindImplementationForInterfaceMember(i1E1.AddMethod)); Assert.Same(c1i1E1remove, test1.FindImplementationForInterfaceMember(i1E1.RemoveMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1P1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1P2)); Assert.Null(test1.FindImplementationForInterfaceMember(i1P3)); Assert.Null(test1.FindImplementationForInterfaceMember(i1E1)); Assert.Same(c1i1P1get, test4.FindImplementationForInterfaceMember(i1P1.GetMethod)); Assert.Same(c1i1P2get, test4.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test4.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(c1i1P3set, test4.FindImplementationForInterfaceMember(i1P3.SetMethod)); Assert.Same(c1i1E1add, test4.FindImplementationForInterfaceMember(i1E1.AddMethod)); Assert.Same(c1i1E1remove, test4.FindImplementationForInterfaceMember(i1E1.RemoveMethod)); Assert.Null(test4.FindImplementationForInterfaceMember(i1P1)); Assert.Null(test4.FindImplementationForInterfaceMember(i1P2)); Assert.Null(test4.FindImplementationForInterfaceMember(i1P3)); Assert.Null(test4.FindImplementationForInterfaceMember(i1E1)); Assert.Same(i2i1P1get, test3.FindImplementationForInterfaceMember(i1P1.GetMethod)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(i2i1P3set, test3.FindImplementationForInterfaceMember(i1P3.SetMethod)); Assert.Same(i2i1E1add, test3.FindImplementationForInterfaceMember(i1E1.AddMethod)); Assert.Same(i2i1E1remove, test3.FindImplementationForInterfaceMember(i1E1.RemoveMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P1)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P3)); Assert.Null(test3.FindImplementationForInterfaceMember(i1E1)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_02() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P2() cil managed { } // end of method I1::get_P2 .method public hidebysig newslot specialname abstract virtual instance void set_P2(int32 'value') cil managed { } // end of method I1::set_P2 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object implements I1 { .method private hidebysig newslot specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.get_P2 .method private hidebysig newslot specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.set_P2 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor .property instance int32 I1.P2() { .get instance int32 C1::I1.get_P2() } // end of property C1::I1.P2 } // end of class C1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .property instance int32 I1.P2() { .get instance int32 I2::I1.get_P2() } // end of property I2::I1.P2 } // end of class I2 "; var source1 = @" class Test1 : C1, I1 { } class Test2 : I2, I1 { } class Test3 : I2 { public long P2 {get => throw null; set => throw null;} } class Test4 : C1, I1 { public long P2 {get => throw null; set => throw null;} } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(6, 19), // (10, 15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(10, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var c1 = compilation1.GetTypeByMetadataName("C1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var test4 = compilation1.GetTypeByMetadataName("Test4"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i2i1P2 = i2.GetMember<PropertySymbol>("I1.P2"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); var c1i1P2 = c1.GetMember<PropertySymbol>("I1.P2"); var c1i1P2get = c1.GetMember<MethodSymbol>("I1.get_P2"); var c1i1P2set = c1.GetMember<MethodSymbol>("I1.set_P2"); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(c1i1P2get, test1.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test1.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(c1i1P2, test1.FindImplementationForInterfaceMember(i1P2)); Assert.Same(c1i1P2get, test4.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test4.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(c1i1P2, test4.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_03() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P2() cil managed { } // end of method I1::get_P2 .method public hidebysig newslot specialname abstract virtual instance void set_P2(int32 'value') cil managed { } // end of method I1::set_P2 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object implements I1 { .method private hidebysig newslot specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.get_P2 .method private hidebysig newslot specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.set_P2 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor .property instance int32 I1.P2() { .set instance void C1::I1.set_P2(int32) } // end of property C1::I1.P2 } // end of class C1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .property instance int32 I1.P2() { .set instance void I2::I1.set_P2(int32) } // end of property I2::I1.P2 } // end of class I2 "; var source1 = @" class Test1 : C1, I1 { } class Test2 : I2, I1 { } class Test3 : I2 { public long P2 {get => throw null; set => throw null;} } class Test4 : C1, I1 { public long P2 {get => throw null; set => throw null;} } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(6, 19), // (10,15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(10, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var c1 = compilation1.GetTypeByMetadataName("C1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var test4 = compilation1.GetTypeByMetadataName("Test4"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i2i1P2 = i2.GetMember<PropertySymbol>("I1.P2"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); var c1i1P2 = c1.GetMember<PropertySymbol>("I1.P2"); var c1i1P2get = c1.GetMember<MethodSymbol>("I1.get_P2"); var c1i1P2set = c1.GetMember<MethodSymbol>("I1.set_P2"); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(c1i1P2get, test1.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test1.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(c1i1P2, test1.FindImplementationForInterfaceMember(i1P2)); Assert.Same(c1i1P2get, test4.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test4.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(c1i1P2, test4.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_04() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P2() cil managed { } // end of method I1::get_P2 .method public hidebysig newslot specialname abstract virtual instance void set_P2(int32 'value') cil managed { } // end of method I1::set_P2 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object implements I1 { .method private hidebysig newslot specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.get_P2 .method private hidebysig newslot specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.set_P2 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor .property instance int32 I1.P21() { .get instance int32 C1::I1.get_P2() } // end of property C1::I1.P2 .property instance int32 I1.P22() { .set instance void C1::I1.set_P2(int32) } // end of property C1::I1.P2 } // end of class C1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .property instance int32 I1.P21() { .get instance int32 I2::I1.get_P2() } // end of property I2::I1.P2 .property instance int32 I1.P22() { .set instance void I2::I1.set_P2(int32) } // end of property I2::I1.P2 } // end of class I2 "; var source1 = @" class Test1 : C1, I1 { } class Test2 : I2, I1 { } class Test3 : I2 { public long P2 {get => throw null; set => throw null;} } class Test4 : C1, I1 { public long P2 {get => throw null; set => throw null;} } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(6, 19), // (10,15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(10, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var c1 = compilation1.GetTypeByMetadataName("C1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var test4 = compilation1.GetTypeByMetadataName("Test4"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); var c1i1P2get = c1.GetMember<MethodSymbol>("I1.get_P2"); var c1i1P2set = c1.GetMember<MethodSymbol>("I1.set_P2"); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(c1i1P2get, test1.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test1.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1P2)); Assert.Same(c1i1P2get, test4.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test4.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test4.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); } [Fact] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_05() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P2() cil managed { } // end of method I1::get_P2 .method public hidebysig newslot specialname abstract virtual instance void set_P2(int32 'value') cil managed { } // end of method I1::set_P2 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [mscorlib]System.Object { .method public hidebysig newslot specialname instance int32 get_P2() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method C1::get_P2 .method public hidebysig newslot specialname instance void set_P2(int32 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::set_P2 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor .property instance int32 P2() { .get instance int32 C1::get_P2() .set instance void C1::set_P2(int32) } // end of property C1::P2 } // end of class C1 .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method private hidebysig newslot specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.2 IL_0001: ret } // end of method C2::I1.get_P2 .method private hidebysig newslot specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C2::I1.set_P2 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: nop IL_0007: ret } // end of method C2::.ctor .property instance int32 I1.P21() { .get instance int32 C2::I1.get_P2() } // end of property C2::I1.P2 .property instance int32 I1.P22() { .set instance void C2::I1.set_P2(int32) } // end of property C2::I1.P2 } // end of class C2 "; var source1 = @" class C3 : C2, I1 { static void Main() { I1 x = new C3(); System.Console.WriteLine(x.P2); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugExe); var i1 = compilation1.GetTypeByMetadataName("I1"); var c3 = compilation1.GetTypeByMetadataName("C3"); Assert.Null(c3.FindImplementationForInterfaceMember(i1.GetMember<PropertySymbol>("P2"))); CompileAndVerify(compilation1, expectedOutput: "2"); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_06() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname virtual instance int32 get_P1() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::get_P1 .method public hidebysig newslot specialname virtual instance int32 get_P2() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::get_P2 .method public hidebysig newslot specialname virtual instance void set_P2(int32 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::set_P2 .method public hidebysig newslot specialname virtual instance void set_P3(int32 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::set_P3 .method public hidebysig newslot specialname virtual instance void add_E1(class [System.Runtime]System.Action 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::add_E1 .method public hidebysig newslot specialname virtual instance void remove_E1(class [System.Runtime]System.Action 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::remove_E1 .event [System.Runtime]System.Action E1 { .addon instance void I1::add_E1(class [System.Runtime]System.Action) .removeon instance void I1::remove_E1(class [System.Runtime]System.Action) } // end of event I1::E1 .property instance int32 P1() { .get instance int32 I1::get_P1() } // end of property I1::P1 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 .property instance int32 P3() { .set instance void I1::set_P3(int32) } // end of property I1::P3 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P1() cil managed { .override I1::get_P1 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P1 .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .method private hidebysig specialname virtual final instance void I1.set_P3(int32 'value') cil managed { .override I1::set_P3 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P3 .method private hidebysig specialname virtual final instance void I1.add_E1(class [System.Runtime]System.Action 'value') cil managed { .override I1::add_E1 // Code size 3 (0x3) .maxstack 8 IL_0000: nop IL_0001: ldnull IL_0002: throw } // end of method I2::I1.add_E1 .method private hidebysig specialname virtual final instance void I1.remove_E1(class [System.Runtime]System.Action 'value') cil managed { .override I1::remove_E1 // Code size 3 (0x3) .maxstack 8 IL_0000: nop IL_0001: ldnull IL_0002: throw } // end of method I2::I1.remove_E1 } // end of class I2 "; var source1 = @" class Test2 : I2, I1 { } class Test3 : I2 { public long P1 {get => throw null;} public long P2 {get => throw null; set => throw null;} public long P3 {set => throw null;} } interface I3 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'Test2' does not implement interface member 'I1.E1' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.E1").WithLocation(2, 19), // (2,19): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 19), // (2,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(2, 19), // (2,19): error CS0535: 'Test2' does not implement interface member 'I1.P3' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P3").WithLocation(2, 19), // (6,15): error CS0535: 'Test3' does not implement interface member 'I1.E1' // class Test3 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test3", "I1.E1").WithLocation(6, 15), // (6,15): error CS0738: 'Test3' does not implement interface member 'I1.P1'. 'Test3.P1' cannot implement 'I1.P1' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P1", "Test3.P1", "int").WithLocation(6, 15), // (6,15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(6, 15), // (6,15): error CS0738: 'Test3' does not implement interface member 'I1.P3'. 'Test3.P3' cannot implement 'I1.P3' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P3", "Test3.P3", "int").WithLocation(6, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var i3 = compilation1.GetTypeByMetadataName("I3"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var i1P1 = i1.GetMember<PropertySymbol>("P1"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i1P3 = i1.GetMember<PropertySymbol>("P3"); var i1E1 = i1.GetMember<EventSymbol>("E1"); var i2i1P1get = i2.GetMember<MethodSymbol>("I1.get_P1"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); var i2i1P3set = i2.GetMember<MethodSymbol>("I1.set_P3"); var i2i1E1add = i2.GetMember<MethodSymbol>("I1.add_E1"); var i2i1E1remove = i2.GetMember<MethodSymbol>("I1.remove_E1"); Assert.Null(i3.FindImplementationForInterfaceMember(i1P1)); Assert.Null(i3.FindImplementationForInterfaceMember(i1P2)); Assert.Null(i3.FindImplementationForInterfaceMember(i1P3)); Assert.Null(i3.FindImplementationForInterfaceMember(i1E1)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P1)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P3)); Assert.Null(i2.FindImplementationForInterfaceMember(i1E1)); Assert.Same(i2i1P1get, test2.FindImplementationForInterfaceMember(i1P1.GetMethod)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(i2i1P3set, test2.FindImplementationForInterfaceMember(i1P3.SetMethod)); Assert.Same(i2i1E1add, test2.FindImplementationForInterfaceMember(i1E1.AddMethod)); Assert.Same(i2i1E1remove, test2.FindImplementationForInterfaceMember(i1E1.RemoveMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P3)); Assert.Null(test2.FindImplementationForInterfaceMember(i1E1)); Assert.Same(i2i1P1get, test3.FindImplementationForInterfaceMember(i1P1.GetMethod)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(i2i1P3set, test3.FindImplementationForInterfaceMember(i1P3.SetMethod)); Assert.Same(i2i1E1add, test3.FindImplementationForInterfaceMember(i1E1.AddMethod)); Assert.Same(i2i1E1remove, test3.FindImplementationForInterfaceMember(i1E1.RemoveMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P1)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P3)); Assert.Null(test3.FindImplementationForInterfaceMember(i1E1)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_07() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname virtual instance int32 get_P2() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::get_P2 .method public hidebysig newslot specialname virtual instance void set_P2(int32 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::set_P2 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .property instance int32 I1.P2() { .get instance int32 I2::I1.get_P2() } // end of property I2::I1.P2 } // end of class I2 "; var source1 = @" class Test2 : I2, I1 { } class Test3 : I2 { public long P2 {get => throw null; set => throw null;} } interface I3 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(2, 19), // (6,15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(6, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var i3 = compilation1.GetTypeByMetadataName("I3"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i2i1P2 = i2.GetMember<PropertySymbol>("I1.P2"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); Assert.Null(i3.FindImplementationForInterfaceMember(i1P2)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_08() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname virtual instance int32 get_P2() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::get_P2 .method public hidebysig newslot specialname virtual instance void set_P2(int32 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::set_P2 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .property instance int32 I1.P2() { .set instance void I2::I1.set_P2(int32) } // end of property I2::I1.P2 } // end of class I2 "; var source1 = @" class Test2 : I2, I1 { } class Test3 : I2 { public long P2 {get => throw null; set => throw null;} } interface I3 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(2, 19), // (6,15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(6, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var i3 = compilation1.GetTypeByMetadataName("I3"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i2i1P2 = i2.GetMember<PropertySymbol>("I1.P2"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); Assert.Null(i3.FindImplementationForInterfaceMember(i1P2)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_09() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname virtual instance int32 get_P2() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::get_P2 .method public hidebysig newslot specialname virtual instance void set_P2(int32 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::set_P2 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .property instance int32 I1.P21() { .get instance int32 I2::I1.get_P2() } // end of property I2::I1.P2 .property instance int32 I1.P22() { .set instance void I2::I1.set_P2(int32) } // end of property I2::I1.P2 } // end of class I2 "; var source1 = @" class Test2 : I2, I1 { } class Test3 : I2 { public long P2 {get => throw null; set => throw null;} } interface I3 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(2, 19), // (6,15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(6, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var i3 = compilation1.GetTypeByMetadataName("I3"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); Assert.Null(i3.FindImplementationForInterfaceMember(i1P2)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34453, "https://github.com/dotnet/roslyn/issues/34453")] public void CheckForImplementationOfCorrespondingPropertyOrEvent_01() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance string get_P1() cil managed { } // end of method I1::get_P1 .property instance string P1() { .get instance string I1::get_P1() } // end of property I1::P1 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object { .method public hidebysig specialname virtual instance string get_P1() cil managed { // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr ""C1"" IL_0005: ret } // end of method C1::get_P1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor .property instance string P2() { .get instance string C1::get_P1() } // end of property C1::P1 } // end of class C1 "; var source1 = @" class C2 : C1, I1 { static void Main() { I1 x = new C2(); System.Console.WriteLine(x.P1); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,16): error CS0535: 'C2' does not implement interface member 'I1.P1' // class C2 : C1, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1").WithLocation(2, 16) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var c2 = compilation1.GetTypeByMetadataName("C2"); var p1 = i1.GetMember<PropertySymbol>("P1"); Assert.Null(c2.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(c2.FindImplementationForInterfaceMember(p1)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34453, "https://github.com/dotnet/roslyn/issues/34453")] public void CheckForImplementationOfCorrespondingPropertyOrEvent_02() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname virtual instance string get_P1() cil managed { // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr ""I1"" IL_0005: ret } // end of method I1::get_P1 .property instance string P1() { .get instance string I1::get_P1() } // end of property I1::P1 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object { .method public hidebysig specialname virtual instance string get_P1() cil managed { // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr ""C1"" IL_0005: ret } // end of method C1::get_P1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor .property instance string P2() { .get instance string C1::get_P1() } // end of property C1::P1 } // end of class C1 "; var source1 = @" class C2 : C1, I1 { static void Main() { I1 x = new C2(); System.Console.WriteLine(x.P1); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,16): error CS0535: 'C2' does not implement interface member 'I1.P1' // class C2 : C1, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1").WithLocation(2, 16) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var c2 = compilation1.GetTypeByMetadataName("C2"); var p1 = i1.GetMember<PropertySymbol>("P1"); Assert.Null(c2.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(c2.FindImplementationForInterfaceMember(p1)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34453, "https://github.com/dotnet/roslyn/issues/34453")] public void CheckForImplementationOfCorrespondingPropertyOrEvent_03() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance string get_P1() cil managed { } // end of method I1::get_P1 .property instance string P1() { .get instance string I1::get_P1() } // end of property I1::P1 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object { .method public hidebysig specialname virtual instance string get_P1() cil managed { // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr ""C1"" IL_0005: ret } // end of method C1::get_P1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor } // end of class C1 "; var source1 = @" class C2 : C1, I1 { static void Main() { I1 x = new C2(); System.Console.WriteLine(x.P1); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,16): error CS0535: 'C2' does not implement interface member 'I1.P1' // class C2 : C1, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1").WithLocation(2, 16), // (2,16): error CS0470: Method 'C1.get_P1()' cannot implement interface accessor 'I1.P1.get' for type 'C2'. Use an explicit interface implementation. // class C2 : C1, I1 Diagnostic(ErrorCode.ERR_MethodImplementingAccessor, "I1").WithArguments("C1.get_P1()", "I1.P1.get", "C2").WithLocation(2, 16) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var c1 = compilation1.GetTypeByMetadataName("C1"); var c2 = compilation1.GetTypeByMetadataName("C2"); var p1 = i1.GetMember<PropertySymbol>("P1"); Assert.Same(c1.GetMember("get_P1"), c2.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(c2.FindImplementationForInterfaceMember(p1)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34453, "https://github.com/dotnet/roslyn/issues/34453")] public void CheckForImplementationOfCorrespondingPropertyOrEvent_04() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname virtual instance string get_P1() cil managed { // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr ""I1"" IL_0005: ret } // end of method I1::get_P1 .property instance string P1() { .get instance string I1::get_P1() } // end of property I1::P1 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object { .method public hidebysig specialname virtual instance string get_P1() cil managed { // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr ""C1"" IL_0005: ret } // end of method C1::get_P1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor } // end of class C1 "; var source1 = @" class C2 : C1, I1 { static void Main() { I1 x = new C2(); System.Console.WriteLine(x.P1); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,16): error CS0535: 'C2' does not implement interface member 'I1.P1' // class C2 : C1, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1").WithLocation(2, 16), // (2,16): error CS0470: Method 'C1.get_P1()' cannot implement interface accessor 'I1.P1.get' for type 'C2'. Use an explicit interface implementation. // class C2 : C1, I1 Diagnostic(ErrorCode.ERR_MethodImplementingAccessor, "I1").WithArguments("C1.get_P1()", "I1.P1.get", "C2").WithLocation(2, 16) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var c1 = compilation1.GetTypeByMetadataName("C1"); var c2 = compilation1.GetTypeByMetadataName("C2"); var p1 = i1.GetMember<PropertySymbol>("P1"); Assert.Same(c1.GetMember("get_P1"), c2.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(c2.FindImplementationForInterfaceMember(p1)); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_11() { var source1 = @" interface A : A.B { public interface B { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'A.B' causes a cycle in the interface hierarchy of 'A' // interface A : A.B Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "A").WithArguments("A", "A.B").WithLocation(2, 11) ); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_12() { var source1 = @" interface A : A.B.I { public interface B : A { public interface I { } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'A.B.I' causes a cycle in the interface hierarchy of 'A' // interface A : A.B.I Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "A").WithArguments("A", "A.B.I").WithLocation(2, 11), // (4,22): error CS0529: Inherited interface 'A' causes a cycle in the interface hierarchy of 'A.B' // public interface B : A Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "B").WithArguments("A.B", "A").WithLocation(4, 22) ); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_13() { var source1 = @" interface IA : IB.IQ { } interface IB : IA { interface IQ { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'IB.IQ' causes a cycle in the interface hierarchy of 'IA' // interface IA : IB.IQ Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IA").WithArguments("IA", "IB.IQ").WithLocation(2, 11), // (6,11): error CS0529: Inherited interface 'IA' causes a cycle in the interface hierarchy of 'IB' // interface IB : IA Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IB").WithArguments("IB", "IA").WithLocation(6, 11) ); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_14() { var source1 = @" interface IB : IA { interface IQ { } } interface IA : IB.IQ { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'IA' causes a cycle in the interface hierarchy of 'IB' // interface IB : IA Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IB").WithArguments("IB", "IA").WithLocation(2, 11), // (7,11): error CS0529: Inherited interface 'IB.IQ' causes a cycle in the interface hierarchy of 'IA' // interface IA : IB.IQ Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IA").WithArguments("IA", "IB.IQ").WithLocation(7, 11) ); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_15() { var source1 = @" class B : IA { public interface IQ { } } interface IA : B.IQ { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_16() { var source1 = @" interface I1 { class C : I1 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_17() { var source1 = @" class C : C.I1 { interface I1 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_18() { var source1 = @" public class CB : CB.CCB.IB, CB.ICB.IB { public class CCB { public interface IB { } } public interface ICB { public interface IB { } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_19() { var source1 = @" public class CD : CD.ICD.CB { public interface ICD { public class CB { } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,14): error CS0146: Circular base type dependency involving 'CD.ICD.CB' and 'CD' // public class CD : CD.ICD.CB Diagnostic(ErrorCode.ERR_CircularBase, "CD").WithArguments("CD.ICD.CB", "CD").WithLocation(2, 14) ); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_20() { var source1 = @" public interface IE : IE.CIE.IB, IE.IIE.IB { public class CIE { public interface IB { } } public interface IIE { public interface IB { } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,18): error CS0529: Inherited interface 'IE.CIE.IB' causes a cycle in the interface hierarchy of 'IE' // public interface IE : IE.CIE.IB, IE.IIE.IB Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IE").WithArguments("IE", "IE.CIE.IB").WithLocation(2, 18), // (2,18): error CS0529: Inherited interface 'IE.IIE.IB' causes a cycle in the interface hierarchy of 'IE' // public interface IE : IE.CIE.IB, IE.IIE.IB Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IE").WithArguments("IE", "IE.IIE.IB").WithLocation(2, 18) ); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_21() { var source1 = @" class C1 : C1.C2.I3 { public class C2 { public interface I3 { } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_22() { var source1 = @" class CA : IB.CQ { public interface I1 { } } interface IB : CA.I1 { public class CQ { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,7): error CS0146: Circular base type dependency involving 'IB.CQ' and 'CA' // class CA : IB.CQ Diagnostic(ErrorCode.ERR_CircularBase, "CA").WithArguments("IB.CQ", "CA").WithLocation(2, 7), // (8,11): error CS0529: Inherited interface 'CA.I1' causes a cycle in the interface hierarchy of 'IB' // interface IB : CA.I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IB").WithArguments("IB", "CA.I1").WithLocation(8, 11) ); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_23() { var source1 = @" interface IB : CA.I1 { public class CQ { } } class CA : IB.CQ { public interface I1 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'CA.I1' causes a cycle in the interface hierarchy of 'IB' // interface IB : CA.I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IB").WithArguments("IB", "CA.I1").WithLocation(2, 11), // (8,7): error CS0146: Circular base type dependency involving 'IB.CQ' and 'CA' // class CA : IB.CQ Diagnostic(ErrorCode.ERR_CircularBase, "CA").WithArguments("IB.CQ", "CA").WithLocation(8, 7) ); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_24() { var source1 = @" interface I100 { public class C100 { public void Test1() { System.Console.WriteLine(""I100.C100.Test1""); } public static void Test2() { System.Console.WriteLine(""I100.C100.Test2""); } } } interface I101 : I100 { private static C100 Test1() => new C100(); static void Main() { Test1().Test1(); C100.Test2(); } }"; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I100.C100.Test1 I100.C100.Test2", verify: VerifyOnMonoOrCoreClr); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_25() { var source1 = @" interface I100 { public class C100 { public void Test1() { System.Console.WriteLine(""I100.C100.Test1""); } public static void Test2() { System.Console.WriteLine(""I100.C100.Test2""); } } } interface I101 : I100 { private static I100.C100 Test1() => new I100.C100(); static void Main() { Test1().Test1(); I100.C100.Test2(); } }"; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I100.C100.Test1 I100.C100.Test2", verify: VerifyOnMonoOrCoreClr); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_26() { var source1 = @" interface I100 { public class C100 { public void Test1() { System.Console.WriteLine(""I100.C100.Test1""); } public static void Test2() { System.Console.WriteLine(""I100.C100.Test2""); } } } interface I101 : I100 { private static I101.C100 Test1() => new I101.C100(); static void Main() { Test1().Test1(); I101.C100.Test2(); } }"; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I100.C100.Test1 I100.C100.Test2", verify: VerifyOnMonoOrCoreClr); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_27() { var source1 = @" public interface I100 { public class C100 { public void Test1() { System.Console.WriteLine(""I100.C100.Test1""); } } } public class C100 { public void Test1() { System.Console.WriteLine(""C100.Test1""); } } public interface I101 : I100 { C100 Test1(); } class Test : I101 { public virtual C100 Test1() => new C100(); static void Main() { I101 x = new Test(); x.Test1().Test1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (26,14): error CS0738: 'Test' does not implement interface member 'I101.Test1()'. 'Test.Test1()' cannot implement 'I101.Test1()' because it does not have the matching return type of 'I100.C100'. // class Test : I101 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I101").WithArguments("Test", "I101.Test1()", "Test.Test1()", "I100.C100").WithLocation(26, 14) ); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_28() { var source1 = @" public interface I100 { public class C100 { public void Test1() { System.Console.WriteLine(""I100.C100.Test1""); } } } public class C100 { public void Test1() { System.Console.WriteLine(""C100.Test1""); } } public interface I101 : I100 { C100 Test1(); } class Test : I101 { public virtual I100.C100 Test1() => new I100.C100(); static void Main() { I101 x = new Test(); x.Test1().Test1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: "I100.C100.Test1"); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_29() { var source1 = @" interface A : C.E { } interface B : A { public interface E {} } interface C : B { public interface E {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'C.E' causes a cycle in the interface hierarchy of 'A' // interface A : C.E Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "A").WithArguments("A", "C.E").WithLocation(2, 11), // (6,11): error CS0529: Inherited interface 'A' causes a cycle in the interface hierarchy of 'B' // interface B : A Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "B").WithArguments("B", "A").WithLocation(6, 11), // (12,11): error CS0529: Inherited interface 'B' causes a cycle in the interface hierarchy of 'C' // interface C : B Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "C").WithArguments("C", "B").WithLocation(12, 11) ); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_30() { var source1 = @" #nullable enable interface A : B, C<object> { } interface B : C<object?> { } interface C<T> { public interface E {} } interface D : A.E { A.E Test(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,11): warning CS8645: 'C<object>' is already listed in the interface list on type 'A' with different nullability of reference types. // interface A : B, C<object> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "A").WithArguments("C<object>", "A").WithLocation(4, 11) ); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_31() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { new interface I2 { void Test(I2 x); } } interface I4 : I1, I3 { class C1 : I2 { public void Test(I2 x) {} } } interface I5 : I3, I1 { class C2 : I2 { public void Test(I2 x) {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_32() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { new interface I2 { void Test(I2 x); } } interface I4 : I1, I3 { class C1 : I2 { void I2.Test(I2 x) {} } } interface I5 : I3, I1 { class C2 : I2 { void I2.Test(I2 x) {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_33() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { interface I2 { } } class C1 { public interface I4 { } } class C3 : C1 { public interface I4 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (10,15): warning CS0108: 'I3.I2' hides inherited member 'I1.I2'. Use the new keyword if hiding was intended. // interface I2 Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2", "I1.I2").WithLocation(10, 15), // (23,22): warning CS0108: 'C3.I4' hides inherited member 'C1.I4'. Use the new keyword if hiding was intended. // public interface I4 Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4", "C1.I4").WithLocation(23, 22) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_34() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { new interface I2 { } } class C1 { public interface I4 { } } class C3 : C1 { new public interface I4 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_35() { var source1 = @" interface I1 { void I2(); } interface I3 : I1 { interface I2 { } } class C1 { public void I4() { } } class C3 : C1 { public interface I4 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (9,15): warning CS0108: 'I3.I2' hides inherited member 'I1.I2()'. Use the new keyword if hiding was intended. // interface I2 Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2", "I1.I2()").WithLocation(9, 15), // (22,22): warning CS0108: 'C3.I4' hides inherited member 'C1.I4()'. Use the new keyword if hiding was intended. // public interface I4 Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4", "C1.I4()").WithLocation(22, 22) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_36() { var source1 = @" interface I1 { void I2(); } interface I3 : I1 { new interface I2 { } } class C1 { public void I4() { } } class C3 : C1 { new public interface I4 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_37() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { void I2(); } class C1 { public interface I4 { } } class C3 : C1 { public void I4() { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (11,10): warning CS0108: 'I3.I2()' hides inherited member 'I1.I2'. Use the new keyword if hiding was intended. // void I2(); Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2()", "I1.I2").WithLocation(11, 10), // (23,17): warning CS0108: 'C3.I4()' hides inherited member 'C1.I4'. Use the new keyword if hiding was intended. // public void I4() Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4()", "C1.I4").WithLocation(23, 17) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_38() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { new void I2(); } class C1 { public interface I4 { } } class C3 : C1 { new public void I4() { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_39() { var source1 = @" interface I1 { static int I2 = 0; } interface I3 : I1 { static int I2 = 1; } class C1 { public static int I4 = 2; } class C3 : C1 { public static int I4 = 3; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,16): warning CS0108: 'I3.I2' hides inherited member 'I1.I2'. Use the new keyword if hiding was intended. // static int I2 = 1; Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2", "I1.I2").WithLocation(9, 16), // (19,23): warning CS0108: 'C3.I4' hides inherited member 'C1.I4'. Use the new keyword if hiding was intended. // public static int I4 = 3; Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4", "C1.I4").WithLocation(19, 23) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_40() { var source1 = @" interface I1 { static int I2 = 0; } interface I3 : I1 { new static int I2 = 1; } class C1 { public static int I4 = 2; } class C3 : C1 { new public static int I4 = 3; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_41() { var source1 = @" interface I1 { void I2(); } interface I3 : I1 { static int I2 = 0; } class C1 { public void I4() { } } class C3 : C1 { public static int I4 = 1; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,16): warning CS0108: 'I3.I2' hides inherited member 'I1.I2()'. Use the new keyword if hiding was intended. // static int I2 = 0; Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2", "I1.I2()").WithLocation(9, 16), // (20,23): warning CS0108: 'C3.I4' hides inherited member 'C1.I4()'. Use the new keyword if hiding was intended. // public static int I4 = 1; Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4", "C1.I4()").WithLocation(20, 23) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_42() { var source1 = @" interface I1 { void I2(); } interface I3 : I1 { new static int I2 = 0; } class C1 { public void I4() { } } class C3 : C1 { new public static int I4 = 1; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_43() { var source1 = @" interface I1 { static int I2 = 0; } interface I3 : I1 { void I2(); } class C1 { public static int I4 = 1; } class C3 : C1 { public void I4() { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,10): warning CS0108: 'I3.I2()' hides inherited member 'I1.I2'. Use the new keyword if hiding was intended. // void I2(); Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2()", "I1.I2").WithLocation(9, 10), // (19,17): warning CS0108: 'C3.I4()' hides inherited member 'C1.I4'. Use the new keyword if hiding was intended. // public void I4() Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4()", "C1.I4").WithLocation(19, 17) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_44() { var source1 = @" interface I1 { static int I2 = 0; } interface I3 : I1 { new void I2(); } class C1 { public static int I4 = 1; } class C3 : C1 { new public void I4() { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_45() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { interface I2<T> { } } class C1 { public interface I4 { } } class C3 : C1 { public interface I4<T> { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_46() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { new interface I2<T> { } } class C1 { public interface I4 { } } class C3 : C1 { public new interface I4<T> { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (10,19): warning CS0109: The member 'I3.I2<T>' does not hide an accessible member. The new keyword is not required. // new interface I2<T> Diagnostic(ErrorCode.WRN_NewNotRequired, "I2").WithArguments("I3.I2<T>").WithLocation(10, 19), // (23,26): warning CS0109: The member 'C3.I4<T>' does not hide an accessible member. The new keyword is not required. // public new interface I4<T> Diagnostic(ErrorCode.WRN_NewNotRequired, "I4").WithArguments("C3.I4<T>").WithLocation(23, 26) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_47() { var source1 = @" interface I1<T> { interface I2 { } interface I2<U> { } } interface I3 : I1<int> { interface I2 { } } class C1<T> { public interface I4 { } public interface I4<U> { } } class C3 : C1<int> { public interface I4 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (13,15): warning CS0108: 'I3.I2' hides inherited member 'I1<int>.I2'. Use the new keyword if hiding was intended. // interface I2 Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2", "I1<int>.I2").WithLocation(13, 15), // (29,22): warning CS0108: 'C3.I4' hides inherited member 'C1<int>.I4'. Use the new keyword if hiding was intended. // public interface I4 Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4", "C1<int>.I4").WithLocation(29, 22) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_48() { var source1 = @" interface I1 { static int I2 = 1; } interface I3 : I1 { interface I2 { } } class C1 { public static int I4 = 2; } class C3 : C1 { public interface I4 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,15): warning CS0108: 'I3.I2' hides inherited member 'I1.I2'. Use the new keyword if hiding was intended. // interface I2 Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2", "I1.I2").WithLocation(9, 15), // (21,22): warning CS0108: 'C3.I4' hides inherited member 'C1.I4'. Use the new keyword if hiding was intended. // public interface I4 Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4", "C1.I4").WithLocation(21, 22) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_49() { var source1 = @" interface I1 { static int I2 = 1; } interface I3 : I1 { new interface I2 { } } class C1 { public static int I4 = 2; } class C3 : C1 { new public interface I4 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_50() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { static int I2 = 0; } class C1 { public interface I4 { } } class C3 : C1 { public static int I4 = 2; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (10,16): warning CS0108: 'I3.I2' hides inherited member 'I1.I2'. Use the new keyword if hiding was intended. // static int I2 = 0; Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2", "I1.I2").WithLocation(10, 16), // (21,23): warning CS0108: 'C3.I4' hides inherited member 'C1.I4'. Use the new keyword if hiding was intended. // public static int I4 = 2; Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4", "C1.I4").WithLocation(21, 23) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_51() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { new static int I2 = 0; } class C1 { public interface I4 { } } class C3 : C1 { new public static int I4 = 2; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_01() { var source1 = @" interface I1<out T1, in T2, T3> { delegate void D11(T1 x); delegate T2 D12(); delegate T3 D13(T3 x); void M1(T1 x); T2 M2(); T3 M3(T3 x); interface I2 { void M21(T1 x); T2 M22(); T3 M23(T3 x); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,23): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I1<T1, T2, T3>.D11.Invoke(T1)'. 'T1' is covariant. // delegate void D11(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I1<T1, T2, T3>.D11.Invoke(T1)", "T1", "covariant", "contravariantly").WithLocation(4, 23), // (5,14): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I1<T1, T2, T3>.D12.Invoke()'. 'T2' is contravariant. // delegate T2 D12(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I1<T1, T2, T3>.D12.Invoke()", "T2", "contravariant", "covariantly").WithLocation(5, 14), // (8,13): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I1<T1, T2, T3>.M1(T1)'. 'T1' is covariant. // void M1(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I1<T1, T2, T3>.M1(T1)", "T1", "covariant", "contravariantly").WithLocation(8, 13), // (9,5): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I1<T1, T2, T3>.M2()'. 'T2' is contravariant. // T2 M2(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I1<T1, T2, T3>.M2()", "T2", "contravariant", "covariantly").WithLocation(9, 5), // (14,18): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I1<T1, T2, T3>.I2.M21(T1)'. 'T1' is covariant. // void M21(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I1<T1, T2, T3>.I2.M21(T1)", "T1", "covariant", "contravariantly").WithLocation(14, 18), // (15,9): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I1<T1, T2, T3>.I2.M22()'. 'T2' is contravariant. // T2 M22(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I1<T1, T2, T3>.I2.M22()", "T2", "contravariant", "covariantly").WithLocation(15, 9) ); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_02() { var source1 = @" interface I2<in T1, out T2> { delegate void D21(T1 x); delegate T2 D22(); void M1(T1 x); T2 M2(); interface I2 { void M21(T1 x); T2 M22(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_03() { var source1 = @" interface I1<out T1, in T2, T3> { interface I2 { delegate void D11(T1 x); delegate T2 D12(); delegate T3 D13(T3 x); interface I3 { void M31(T1 x); T2 M32(); T3 M33(T3 x); } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,27): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I1<T1, T2, T3>.I2.D11.Invoke(T1)'. 'T1' is covariant. // delegate void D11(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I1<T1, T2, T3>.I2.D11.Invoke(T1)", "T1", "covariant", "contravariantly").WithLocation(6, 27), // (7,18): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I1<T1, T2, T3>.I2.D12.Invoke()'. 'T2' is contravariant. // delegate T2 D12(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I1<T1, T2, T3>.I2.D12.Invoke()", "T2", "contravariant", "covariantly").WithLocation(7, 18), // (12,22): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I1<T1, T2, T3>.I2.I3.M31(T1)'. 'T1' is covariant. // void M31(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I1<T1, T2, T3>.I2.I3.M31(T1)", "T1", "covariant", "contravariantly").WithLocation(12, 22), // (13,13): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I1<T1, T2, T3>.I2.I3.M32()'. 'T2' is contravariant. // T2 M32(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I1<T1, T2, T3>.I2.I3.M32()", "T2", "contravariant", "covariantly").WithLocation(13, 13) ); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_04() { var source1 = @" interface I2<in T1, out T2> { interface I2 { delegate void D21(T1 x); delegate T2 D22(); interface I3 { void M31(T1 x); T2 M32(); } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_05() { var source1 = @" interface I1<out T1> { class C1 { void MC1(T1 x) {} class C {} struct S {} enum E {} } struct S1 { void MS1(T1 x) {} class C {} struct S {} enum E {} } enum E1 {} } interface I2<in T2> { class C2 { T2 MC2() => default; class C {} struct S {} enum E {} } struct S2 { T2 MS2() => default; class C {} struct S {} enum E {} } enum E2 {} } interface I3<T3> { class C3 { T3 MC3(T3 x) => default; class C {} struct S {} enum E {} } struct S3 { T3 MS3(T3 x) => default; class C {} struct S {} enum E {} } enum E3 {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,11): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // class C1 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "C1").WithLocation(4, 11), // (11,12): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // struct S1 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "S1").WithLocation(11, 12), // (18,10): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // enum E1 {} Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "E1").WithLocation(18, 10), // (23,11): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // class C2 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "C2").WithLocation(23, 11), // (30,12): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // struct S2 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "S2").WithLocation(30, 12), // (37,10): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // enum E2 {} Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "E2").WithLocation(37, 10) ); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_06() { var source1 = @" interface I1<out T1> { interface I0 { class C1 { interface I { class C {} struct S {} enum E {} } } struct S1 { interface I { class C {} struct S {} enum E {} } } enum E1 {} } } interface I2<in T2> { interface I0 { class C2 { interface I { class C {} struct S {} enum E {} } } struct S2 { interface I { class C {} struct S {} enum E {} } } enum E2 {} } } interface I3<T3> { interface I0 { class C3 { interface I { class C {} struct S {} enum E {} } } struct S3 { interface I { class C {} struct S {} enum E {} } } enum E3 {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,15): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // class C1 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "C1").WithLocation(6, 15), // (15,16): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // struct S1 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "S1").WithLocation(15, 16), // (24,14): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // enum E1 {} Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "E1").WithLocation(24, 14), // (32,15): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // class C2 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "C2").WithLocation(32, 15), // (41,16): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // struct S2 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "S2").WithLocation(41, 16), // (50,14): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // enum E2 {} Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "E2").WithLocation(50, 14) ); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_07() { var source1 = @" public interface I1<out T1, in T2, T3> { void M1() { T1 x = local(default, default); T1 local(T1 x, I2 y) { System.Console.WriteLine(""M1""); return x; } } void M2() { T2 x = local(default, default); T2 local(T2 x, I2.I3 y) { System.Console.WriteLine(""M2""); return x; } } void M3() { T3 x = local(default); T3 local(T3 x) { System.Console.WriteLine(""M3""); return x; } } interface I2 { void M4() { System.Console.WriteLine(""M4""); } interface I3 { } } delegate T1 D1(T2 x); delegate T3 D3(T3 x); } "; var source2 = @" class C1 : I1<C1, C1, C1>, I1<C1, object, C1>.I2 { static void Main() { I1<C1, C1, C1> x = new C1(); x.M1(); x.M2(); x.M3(); var y = (I1<C1, object, C1>.I2)x; I1<object, C1, C1>.I2 z = y; z.M4(); I1<C1, object, C1>.D1 d1 = M5; I1<object, C1, C1>.D1 d2 = d1; _ = d2(new C1()); } static C1 M5(object x) { System.Console.WriteLine(""M5""); return (C1)x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2 M3 M4 M5"); } } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_08() { var source1 = @" public interface I1<out T1, in T2> { void M1() { System.Func<T1, T1> d = (T1 x) => { System.Console.WriteLine(""M1""); return x; }; d(default); } void M2() { System.Func<T2, T2> d = (T2 x) => { System.Console.WriteLine(""M2""); return x; }; d(default); } } class C1 : I1<C1, C1> { static void Main() { I1<C1, C1> x = new C1(); x.M1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2"); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_09() { var source1 = @" using System.Collections.Generic; class Program : I2<int> { static void Main() { ((I2<int>)new Program()).M2().GetEnumerator().MoveNext(); } } interface I2<out T> { IEnumerable<int> M2() { System.Console.WriteLine(""M2""); yield break; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M2"); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_10() { var source1 = @" class Program { static void Main() { I2<string, string>.F1 = ""a""; I2<string, string>.F2 = ""b""; System.Console.WriteLine(I2<string, string>.F1); System.Console.WriteLine(I2<string, string>.F2); } } interface I2<out T1, in T2> { static T1 F1 = default; static T2 F2 = default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"a b"); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_11() { var source1 = @" public interface I1<out T1, in T2> { void M1() { T1 x = local(default); T1 local(T1 x) { System.Console.WriteLine(GetString(""M1"")); return x; } } string GetString(string s) => s; void M2() { T2 x = local(default); T2 local(T2 x) { System.Console.WriteLine(GetString(""M2"")); return x; } } } "; var source2 = @" class C1 : I1<C1, C1> { static void Main() { I1<C1, C1> x = new C1(); x.M1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2"); } } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_12() { var source1 = @" interface I1<out T1, in T2> { private void M1(T1 x) {} private T2 M2() => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,21): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I1<T1, T2>.M1(T1)'. 'T1' is covariant. // private void M1(T1 x) {} Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I1<T1, T2>.M1(T1)", "T1", "covariant", "contravariantly").WithLocation(4, 21), // (5,13): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I1<T1, T2>.M2()'. 'T2' is contravariant. // private T2 M2() => default; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I1<T1, T2>.M2()", "T2", "contravariant", "covariantly").WithLocation(5, 13) ); } [Fact] public void VarianceSafety_13() { var source1 = @" class Program { static void Main() { I2<string, string>.P1 = ""a""; I2<string, string>.P2 = ""b""; System.Console.WriteLine(I2<string, string>.P1); System.Console.WriteLine(I2<string, string>.P2); } } interface I2<out T1, in T2> { static T1 P1 { get; set; } static T2 P2 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (15,12): error CS8904: Invalid variance: The type parameter 'T1' must be invariantly valid on 'I2<T1, T2>.P1' unless language version '9.0' or greater is used. 'T1' is covariant. // static T1 P1 { get; set; } Diagnostic(ErrorCode.ERR_UnexpectedVarianceStaticMember, "T1").WithArguments("I2<T1, T2>.P1", "T1", "covariant", "invariantly", "9.0").WithLocation(15, 12), // (16,12): error CS8904: Invalid variance: The type parameter 'T2' must be invariantly valid on 'I2<T1, T2>.P2' unless language version '9.0' or greater is used. 'T2' is contravariant. // static T2 P2 { get; set; } Diagnostic(ErrorCode.ERR_UnexpectedVarianceStaticMember, "T2").WithArguments("I2<T1, T2>.P2", "T2", "contravariant", "invariantly", "9.0").WithLocation(16, 12) ); compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"a b").VerifyDiagnostics(); } [Fact] public void VarianceSafety_14() { var source1 = @" class Program { static void Main() { System.Console.WriteLine(I2<string, string>.M1(""a"")); System.Console.WriteLine(I2<string, string>.M2(""b"")); } } interface I2<out T1, in T2> { static T1 M1(T1 x) => x; static T2 M2(T2 x) => x; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (13,18): error CS8904: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.M1(T1)' unless language version '9.0' or greater is used. 'T1' is covariant. // static T1 M1(T1 x) => x; Diagnostic(ErrorCode.ERR_UnexpectedVarianceStaticMember, "T1").WithArguments("I2<T1, T2>.M1(T1)", "T1", "covariant", "contravariantly", "9.0").WithLocation(13, 18), // (14,12): error CS8904: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.M2(T2)' unless language version '9.0' or greater is used. 'T2' is contravariant. // static T2 M2(T2 x) => x; Diagnostic(ErrorCode.ERR_UnexpectedVarianceStaticMember, "T2").WithArguments("I2<T1, T2>.M2(T2)", "T2", "contravariant", "covariantly", "9.0").WithLocation(14, 12) ); compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"a b").VerifyDiagnostics(); } [Fact] public void VarianceSafety_15() { var source1 = @" class Program { static void Main() { I2<string, string>.E1 += Print1; I2<string, string>.E2 += Print2; I2<string, string>.Raise(); } static void Print1(System.Func<string, string> x) { System.Console.WriteLine(x(""a"")); } static void Print2(System.Func<string, string> x) { System.Console.WriteLine(x(""b"")); } } interface I2<out T1, in T2> { static event System.Action<System.Func<T1, T1>> E1; static event System.Action<System.Func<T2, T2>> E2; static void Raise() { E1(Print); E2(Print); } static T3 Print<T3>(T3 x) { return x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (24,53): error CS8904: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.E1' unless language version '9.0' or greater is used. 'T1' is covariant. // static event System.Action<System.Func<T1, T1>> E1; Diagnostic(ErrorCode.ERR_UnexpectedVarianceStaticMember, "E1").WithArguments("I2<T1, T2>.E1", "T1", "covariant", "contravariantly", "9.0").WithLocation(24, 53), // (25,53): error CS8904: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.E2' unless language version '9.0' or greater is used. 'T2' is contravariant. // static event System.Action<System.Func<T2, T2>> E2; Diagnostic(ErrorCode.ERR_UnexpectedVarianceStaticMember, "E2").WithArguments("I2<T1, T2>.E2", "T2", "contravariant", "covariantly", "9.0").WithLocation(25, 53) ); compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"a b").VerifyDiagnostics(); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_01() { var source1 = @" interface I1 { int I1::M1() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,9): error CS0540: 'I1.M1()': containing type does not implement interface 'I1' // int I1::M1() => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("I1.M1()", "I1").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I1::M1() => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11) ); AssertNoMethodImplementation(compilation1); } private static void AssertNoMethodImplementation(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); Assert.Empty(i1.GetMembers().OfType<MethodSymbol>().Single().ExplicitInterfaceImplementations); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_02() { var source1 = @" interface I1 : I1 { int I1::M1() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I1").WithLocation(2, 11), // (4,9): error CS0540: 'I1.M1()': containing type does not implement interface 'I1' // int I1::M1() => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("I1.M1()", "I1").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I1::M1() => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11) ); AssertNoMethodImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_03() { var source1 = @" interface I1 { int I2::M1() => throw null; } interface I2 { int M1(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,9): error CS0540: 'I1.I2.M1()': containing type does not implement interface 'I2' // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.I2.M1()", "I2").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); Assert.Same(i2.GetMembers().OfType<MethodSymbol>().Single(), i1.GetMembers().OfType<MethodSymbol>().Single().ExplicitInterfaceImplementations.Single()); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_04() { var source1 = @" interface I1 : I2 { int I2::M1() => throw null; } interface I2 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(2, 11), // (4,9): error CS0540: 'I1.M1()': containing type does not implement interface 'I2' // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.M1()", "I2").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11), // (4,13): error CS0539: 'I1.M1()' in explicit interface declaration is not found among members of the interface that can be implemented // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M1").WithArguments("I1.M1()").WithLocation(4, 13), // (7,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(7, 11) ); AssertNoMethodImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_05() { var source1 = @" interface I2 : I1 { } interface I1 : I2 { int I2::M1() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(2, 11), // (6,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(6, 11), // (8,9): error CS0540: 'I1.M1()': containing type does not implement interface 'I2' // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.M1()", "I2").WithLocation(8, 9), // (8,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(8, 11), // (8,13): error CS0539: 'I1.M1()' in explicit interface declaration is not found among members of the interface that can be implemented // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M1").WithArguments("I1.M1()").WithLocation(8, 13) ); AssertNoMethodImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_06() { var source1 = @" interface I1 { int I1::P1 => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,9): error CS0540: 'I1.P1': containing type does not implement interface 'I1' // int I1::P1 => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("I1.P1", "I1").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I1::P1 => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11) ); AssertNoPropertyImplementation(compilation1); } private static void AssertNoPropertyImplementation(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Empty(m.ExplicitInterfaceImplementations); Assert.Empty(m.GetMethod.ExplicitInterfaceImplementations); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_07() { var source1 = @" interface I1 : I1 { int I1::P1 => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I1").WithLocation(2, 11), // (4,9): error CS0540: 'I1.P1': containing type does not implement interface 'I1' // int I1::P1 => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("I1.P1", "I1").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I1::P1 => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11) ); AssertNoPropertyImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_08() { var source1 = @" interface I1 { int I2::P1 => throw null; } interface I2 { int P1 {get;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,9): error CS0540: 'I1.I2.P1': containing type does not implement interface 'I2' // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.I2.P1", "I2").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var m1 = i1.GetMembers().OfType<PropertySymbol>().Single(); var m2 = i2.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(m2, m1.ExplicitInterfaceImplementations.Single()); Assert.Same(m2.GetMethod, m1.GetMethod.ExplicitInterfaceImplementations.Single()); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_09() { var source1 = @" interface I1 : I2 { int I2::P1 => throw null; } interface I2 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(2, 11), // (4,9): error CS0540: 'I1.P1': containing type does not implement interface 'I2' // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.P1", "I2").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11), // (4,13): error CS0539: 'I1.P1' in explicit interface declaration is not found among members of the interface that can be implemented // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("I1.P1").WithLocation(4, 13), // (7,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(7, 11) ); AssertNoPropertyImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_10() { var source1 = @" interface I2 : I1 { } interface I1 : I2 { int I2::P1 => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(2, 11), // (6,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(6, 11), // (8,9): error CS0540: 'I1.P1': containing type does not implement interface 'I2' // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.P1", "I2").WithLocation(8, 9), // (8,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(8, 11), // (8,13): error CS0539: 'I1.P1' in explicit interface declaration is not found among members of the interface that can be implemented // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("I1.P1").WithLocation(8, 13) ); AssertNoPropertyImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_11() { var source1 = @" interface I1 { event System.Action I1::E1 { add => throw null; remove => throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,25): error CS0540: 'I1.E1': containing type does not implement interface 'I1' // event System.Action I1::E1 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("I1.E1", "I1").WithLocation(4, 25), // (4,27): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // event System.Action I1::E1 Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 27) ); AssertNoEventImplementation(compilation1); } private static void AssertNoEventImplementation(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Empty(m.ExplicitInterfaceImplementations); Assert.Empty(m.AddMethod.ExplicitInterfaceImplementations); Assert.Empty(m.RemoveMethod.ExplicitInterfaceImplementations); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_12() { var source1 = @" interface I1 : I1 { event System.Action I1::E1 { add => throw null; remove => throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I1").WithLocation(2, 11), // (4,25): error CS0540: 'I1.E1': containing type does not implement interface 'I1' // event System.Action I1::E1 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("I1.E1", "I1").WithLocation(4, 25), // (4,27): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // event System.Action I1::E1 Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 27) ); AssertNoEventImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_13() { var source1 = @" interface I1 { event System.Action I2::E1 { add => throw null; remove => throw null;} } interface I2 { event System.Action E1; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,25): error CS0540: 'I1.I2.E1': containing type does not implement interface 'I2' // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.I2.E1", "I2").WithLocation(4, 25), // (4,27): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 27) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var m1 = i1.GetMembers().OfType<EventSymbol>().Single(); var m2 = i2.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(m2, m1.ExplicitInterfaceImplementations.Single()); Assert.Same(m2.AddMethod, m1.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m2.RemoveMethod, m1.RemoveMethod.ExplicitInterfaceImplementations.Single()); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_14() { var source1 = @" interface I1 : I2 { event System.Action I2::E1 { add => throw null; remove => throw null;} } interface I2 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(2, 11), // (4,25): error CS0540: 'I1.E1': containing type does not implement interface 'I2' // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.E1", "I2").WithLocation(4, 25), // (4,27): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 27), // (4,29): error CS0539: 'I1.E1' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "E1").WithArguments("I1.E1").WithLocation(4, 29), // (8,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(8, 11) ); AssertNoEventImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_15() { var source1 = @" interface I2 : I1 { } interface I1 : I2 { event System.Action I2::E1 { add => throw null; remove => throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(2, 11), // (6,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(6, 11), // (8,25): error CS0540: 'I1.E1': containing type does not implement interface 'I2' // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.E1", "I2").WithLocation(8, 25), // (8,27): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(8, 27), // (8,29): error CS0539: 'I1.E1' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "E1").WithArguments("I1.E1").WithLocation(8, 29) ); AssertNoEventImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_16() { var source1 = @" interface I1<T> { int I1<int>.P1 => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,9): error CS0540: 'I1<T>.P1': containing type does not implement interface 'I1<int>' // int I1<int>.P1 => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<int>").WithArguments("I1<T>.P1", "I1<int>").WithLocation(4, 9) ); } [Fact, WorkItem(41481, "https://github.com/dotnet/roslyn/issues/41481")] public void IncompletePropertyImplementationSyntax_01() { var source1 = @"interface A { object A.B{"; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (3,12): error CS0540: 'A.B': containing type does not implement interface 'A' // object A.B{ Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "A").WithArguments("A.B", "A").WithLocation(3, 12), // (3,14): error CS0548: 'A.B': property or indexer must have at least one accessor // object A.B{ Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "B").WithArguments("A.B").WithLocation(3, 14), // (3,16): error CS1513: } expected // object A.B{ Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(3, 16), // (3,16): error CS1513: } expected // object A.B{ Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(3, 16) ); } [Fact, WorkItem(49341, "https://github.com/dotnet/roslyn/issues/49341")] public void RefReturningAutoProperty_01() { var source1 = @" interface IA { static ref int PA { get;} } interface IB { static ref int PB { get; set;} } interface IC { static ref int PC { set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,20): error CS8145: Auto-implemented properties cannot return by reference // static ref int PA { get;} Diagnostic(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, "PA").WithArguments("IA.PA").WithLocation(4, 20), // (9,20): error CS8145: Auto-implemented properties cannot return by reference // static ref int PB { get; set;} Diagnostic(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, "PB").WithArguments("IB.PB").WithLocation(9, 20), // (9,30): error CS8147: Properties which return by reference cannot have set accessors // static ref int PB { get; set;} Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("IB.PB.set").WithLocation(9, 30), // (14,20): error CS8146: Properties which return by reference must have a get accessor // static ref int PC { set;} Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "PC").WithArguments("IC.PC").WithLocation(14, 20) ); } [Fact, WorkItem(49341, "https://github.com/dotnet/roslyn/issues/49341")] public void RefReturningAutoProperty_02() { var source1 = @" interface IA { ref int PA { get;} } interface IB { ref int PB { get; set;} } interface IC { ref int PC { set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,23): error CS8147: Properties which return by reference cannot have set accessors // ref int PB { get; set;} Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("IB.PB.set").WithLocation(9, 23), // (14,13): error CS8146: Properties which return by reference must have a get accessor // ref int PC { set;} Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "PC").WithArguments("IC.PC").WithLocation(14, 13) ); } [Fact, WorkItem(49341, "https://github.com/dotnet/roslyn/issues/49341")] public void RefReturningAutoProperty_03() { var source1 = @" interface IA { sealed ref int PA { get;} } interface IB { sealed ref int PB { get; set;} } interface IC { sealed ref int PC { set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,25): error CS0501: 'IA.PA.get' must declare a body because it is not marked abstract, extern, or partial // sealed ref int PA { get;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("IA.PA.get").WithLocation(4, 25), // (9,25): error CS0501: 'IB.PB.get' must declare a body because it is not marked abstract, extern, or partial // sealed ref int PB { get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("IB.PB.get").WithLocation(9, 25), // (9,30): error CS8147: Properties which return by reference cannot have set accessors // sealed ref int PB { get; set;} Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("IB.PB.set").WithLocation(9, 30), // (9,30): error CS0501: 'IB.PB.set' must declare a body because it is not marked abstract, extern, or partial // sealed ref int PB { get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("IB.PB.set").WithLocation(9, 30), // (14,20): error CS8146: Properties which return by reference must have a get accessor // sealed ref int PC { set;} Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "PC").WithArguments("IC.PC").WithLocation(14, 20), // (14,25): error CS0501: 'IC.PC.set' must declare a body because it is not marked abstract, extern, or partial // sealed ref int PC { set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("IC.PC.set").WithLocation(14, 25) ); } [Fact, WorkItem(50491, "https://github.com/dotnet/roslyn/issues/50491")] public void RuntimeFeatureAsInterface_01() { var source1 = @" namespace System.Runtime.CompilerServices { public static partial interface RuntimeFeature { public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); } } "; var compilation1 = CreateEmptyCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (4,37): error CS0106: The modifier 'static' is not valid for this item // public static partial interface RuntimeFeature Diagnostic(ErrorCode.ERR_BadMemberFlag, "RuntimeFeature").WithArguments("static").WithLocation(4, 37), // (6,22): error CS0518: Predefined type 'System.String' is not defined or imported // public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "string").WithArguments("System.String").WithLocation(6, 22), // (6,29): error CS8701: Target runtime doesn't support default interface implementation. // public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "DefaultImplementationsOfInterfaces").WithLocation(6, 29) ); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); } [Fact, WorkItem(50491, "https://github.com/dotnet/roslyn/issues/50491")] public void RuntimeFeatureAsInterface_02() { var source1 = @" namespace System.Runtime.CompilerServices { public partial interface RuntimeFeature { public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); } } "; var compilation1 = CreateEmptyCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (6,22): error CS0518: Predefined type 'System.String' is not defined or imported // public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "string").WithArguments("System.String").WithLocation(6, 22), // (6,29): error CS8701: Target runtime doesn't support default interface implementation. // public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "DefaultImplementationsOfInterfaces").WithLocation(6, 29) ); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); } [Fact, WorkItem(50491, "https://github.com/dotnet/roslyn/issues/50491")] public void RuntimeFeatureAsInterface_03() { var source1 = @" namespace System.Runtime.CompilerServices { public partial interface RuntimeFeature { public const string DefaultImplementationsOfInterfaces = ""Test""; } } class Test { static void Main() { System.Console.WriteLine(System.Runtime.CompilerServices.RuntimeFeature.DefaultImplementationsOfInterfaces); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "Test", verify: VerifyOnMonoOrCoreClr); } [Fact, WorkItem(53565, "https://github.com/dotnet/roslyn/issues/53565")] public void PartialPropertyImplementation_01() { var source1 = @" interface I1 { int P1 {get; set;} int P2 {get => throw null; internal set{}} int P3 {get => throw null; set{}} } class C0 : I1 { int I1.P1 {get; set;} } class C1 : C0, I1 { public int P1 { get { System.Console.WriteLine(""C1.get_P1""); return 0; } } public int P2 { get { System.Console.WriteLine(""C1.get_P2""); return 0; } } public int P3 { get { System.Console.WriteLine(""C1.get_P3""); return 0; } } static void Main() { I1 x = new C1(); _ = x.P1; _ = x.P2; _ = x.P3; } } "; foreach (var parseOptions in new[] { TestOptions.Regular8, TestOptions.Regular9, TestOptions.Regular }) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"C1.get_P1 C1.get_P2 C1.get_P3 ", verify: VerifyOnMonoOrCoreClr); var c1 = compilation1.GetTypeByMetadataName("C1"); foreach (var p in c1.GetMembers().OfType<PropertySymbol>()) { Assert.True(p.GetMethod.IsMetadataVirtual()); Assert.True(p.GetMethod.IsMetadataFinal); } } } [Fact, WorkItem(53565, "https://github.com/dotnet/roslyn/issues/53565")] public void PartialPropertyImplementation_02() { var source1 = @" interface I1 { internal int P1 {get; set;} internal int P2 {get => throw null; set{}} } class C0 : I1 { int I1.P1 {get; set;} } class C1 : C0, I1 { public int P1 { get { System.Console.WriteLine(""C1.get_P1""); return 0; } } public int P2 { get { System.Console.WriteLine(""C1.get_P2""); return 0; } } static void Main() { I1 x = new C1(); _ = x.P1; _ = x.P2; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"C1.get_P1 C1.get_P2 ", verify: VerifyOnMonoOrCoreClr); var c1 = compilation1.GetTypeByMetadataName("C1"); foreach (var p in c1.GetMembers().OfType<PropertySymbol>()) { Assert.True(p.GetMethod.IsMetadataVirtual()); Assert.True(p.GetMethod.IsMetadataFinal); } } } }
// 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. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { [CompilerTrait(CompilerFeature.DefaultInterfaceImplementation)] public class DefaultInterfaceImplementationTests : CSharpTestBase { [Fact] [WorkItem(33083, "https://github.com/dotnet/roslyn/issues/33083")] public void MethodImplementation_011() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } "; ValidateMethodImplementation_011(source1); } private static Verification VerifyOnMonoOrCoreClr { get { return ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped; } } private void ValidateMethodImplementation_011(string source) { foreach (string access in new[] { "x.M1();", "new System.Action(x.M1)();" }) { foreach (string typeKind in new[] { "class", "struct" }) { string source1 = source + typeKind + " Test1 " + @": I1 { static void Main() { I1 x = new Test1(); " + access + @" } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { ValidateMethodImplementationTest1_011(m, "void I1.M1()"); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var source2 = typeKind + " Test2 " + @": I1 { static void Main() { I1 x = new Test2(); " + access + @" } } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate2(ModuleSymbol m) { ValidateMethodImplementationTest2_011(m, "void I1.M1()"); } Validate2(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); } } } } private static void ValidateMethodImplementationTest1_011(ModuleSymbol m, string expectedImplementation) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var m1 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); if (m is PEModuleSymbol peModule) { int rva; peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)m1).Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); } var test1 = m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal(expectedImplementation, test1.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); Assert.Equal("I1", test1.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Assert.Same(m1, i1.FindImplementationForInterfaceMember(m1)); } private static void ValidateMethodImplementationTest2_011(ModuleSymbol m, string expectedImplementation) { var test2 = m.GlobalNamespace.GetTypeMember("Test2"); var i1 = test2.InterfacesNoUseSiteDiagnostics().Single(); Assert.Equal("I1", i1.ToTestDisplayString()); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.Equal(expectedImplementation, test2.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); Assert.Same(m1, i1.FindImplementationForInterfaceMember(m1)); } [Fact] public void MethodImplementation_012() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 { public void M1() { System.Console.WriteLine(""Test1 M1""); } static void Main() { I1 x = new Test1(); x.M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { ValidateMethodImplementationTest1_011(m, "void Test1.M1()"); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test1 M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var source2 = @" class Test2 : I1 { public void M1() { System.Console.WriteLine(""Test2 M1""); } static void Main() { I1 x = new Test2(); x.M1(); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate2(ModuleSymbol m) { ValidateMethodImplementationTest2_011(m, "void Test2.M1()"); } Validate2(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test2 M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate2(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test2 M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); } [Fact] public void MethodImplementation_013() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 { void I1.M1() { System.Console.WriteLine(""Test1 M1""); } static void Main() { I1 x = new Test1(); x.M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { ValidateMethodImplementationTest1_011(m, "void Test1.I1.M1()"); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test1 M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var source2 = @" class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2 M1""); } static void Main() { I1 x = new Test2(); x.M1(); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate2(ModuleSymbol m) { ValidateMethodImplementationTest2_011(m, "void Test2.I1.M1()"); } Validate2(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test2 M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate2(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test2 M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); } [Fact] public void MethodImplementation_021() { var source1 = @" interface I1 { void M1() { System.Console.WriteLine(""M1""); } void M2() { System.Console.WriteLine(""M2""); } } class Base { void M1() { } } class Derived : Base, I1 { void M2() { } static void Main() { I1 x = new Derived(); x.M1(); x.M2(); } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var m1 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M1"); var m2 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M2"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Same(m1, derived.FindImplementationForInterfaceMember(m1)); Assert.Same(m2, derived.FindImplementationForInterfaceMember(m2)); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void MethodImplementation_022() { var source1 = @" interface I1 { void M1() { System.Console.WriteLine(""M1""); } void M2() { System.Console.WriteLine(""M2""); } } class Base : Test { void M1() { } } class Derived : Base, I1 { void M2() { } static void Main() { I1 x = new Derived(); x.M1(); x.M2(); } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var m1 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M1"); var m2 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M2"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Same(m1, derived.FindImplementationForInterfaceMember(m1)); Assert.Same(m2, derived.FindImplementationForInterfaceMember(m2)); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void MethodImplementation_023() { var source1 = @" interface I1 { void M1() {} void M2() {} } class Base : Test { void M1() { } } class Derived : Base, I1 { void M2() { } static void Main() { I1 x = new Derived(); x.M1(); x.M2(); } } class Test : I1 { void I1.M1() { System.Console.WriteLine(""Test.M1""); } void I1.M2() { System.Console.WriteLine(""Test.M2""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var m1 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M1"); var m2 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M2"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Equal("void Test.I1.M1()", derived.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); Assert.Equal("void Test.I1.M2()", derived.FindImplementationForInterfaceMember(m2).ToTestDisplayString()); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"Test.M1 Test.M2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void MethodImplementation_024() { var source1 = @" interface I1 { void M1() {} void M2() {} } class Base : Test { new void M1() { } } class Derived : Base, I1 { new void M2() { } static void Main() { I1 x = new Derived(); x.M1(); x.M2(); } } class Test : I1 { public void M1() { System.Console.WriteLine(""Test.M1""); } public void M2() { System.Console.WriteLine(""Test.M2""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var m1 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M1"); var m2 = m.GlobalNamespace.GetMember<MethodSymbol>("I1.M2"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Equal("void Test.M1()", derived.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); Assert.Equal("void Test.M2()", derived.FindImplementationForInterfaceMember(m2).ToTestDisplayString()); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"Test.M1 Test.M2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void MethodImplementation_031() { var source1 = @" interface I1 { void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 { public static void M1() { } static void Main() { I1 x = new Test1(); x.M1(); } } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_032() { var source1 = @" interface I1 { void M1() { System.Console.WriteLine(""M1""); } } class Test1 : Test2, I1 { public static void M1() { } static void Main() { I1 x = new Test1(); x.M1(); } } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_033() { var source1 = @" interface I1 { void M1() {} } class Test1 : Test2, I1 { public static void M1() { } static void Main() { I1 x = new Test1(); x.M1(); } } class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2.M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Equal("void Test2.I1.M1()", test1.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test2.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_034() { var source1 = @" interface I1 { void M1() {} } class Test1 : Test2, I1 { new public static void M1() { } static void Main() { I1 x = new Test1(); x.M1(); } } class Test2 : I1 { public void M1() { System.Console.WriteLine(""Test2.M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Equal("void Test2.M1()", test1.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test2.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_041() { var source1 = @" interface I1 { void M1() { System.Console.WriteLine(""M1""); } int M2() => 2; } class Test1 : I1 { public int M1() { return 0; } public ref int M2() { throw null; } static void Main() { I1 x = new Test1(); x.M1(); System.Console.WriteLine(x.M2()); } } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var m2 = compilation1.GetMember<MethodSymbol>("I1.M2"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); Assert.Same(m2, test1.FindImplementationForInterfaceMember(m2)); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_042() { var source1 = @" interface I1 { void M1() { System.Console.WriteLine(""M1""); } int M2() => 2; } class Test1 : Test2, I1 { public int M1() { return 0; } public ref int M2() { throw null; } static void Main() { I1 x = new Test1(); x.M1(); System.Console.WriteLine(x.M2()); } } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var m2 = compilation1.GetMember<MethodSymbol>("I1.M2"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); Assert.Same(m2, test1.FindImplementationForInterfaceMember(m2)); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_043() { var source1 = @" interface I1 { void M1() {} int M2() => 1; } class Test1 : Test2, I1 { public int M1() { return 0; } public ref int M2() { throw null; } static void Main() { I1 x = new Test1(); x.M1(); System.Console.WriteLine(x.M2()); } } class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2.M1""); } int I1.M2() => 2; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var m2 = compilation1.GetMember<MethodSymbol>("I1.M2"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Equal("void Test2.I1.M1()", test1.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); Assert.Equal("System.Int32 Test2.I1.M2()", test1.FindImplementationForInterfaceMember(m2).ToTestDisplayString()); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"Test2.M1 2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_044() { var source1 = @" interface I1 { void M1() {} int M2() => 1; } class Test1 : Test2, I1 { new public int M1() { return 0; } new public ref int M2() { throw null; } static void Main() { I1 x = new Test1(); x.M1(); System.Console.WriteLine(x.M2()); } } class Test2 : I1 { public void M1() { System.Console.WriteLine(""Test2.M1""); } public int M2() => 2; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); var m2 = compilation1.GetMember<MethodSymbol>("I1.M2"); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Equal("void Test2.M1()", test1.FindImplementationForInterfaceMember(m1).ToTestDisplayString()); Assert.Equal("System.Int32 Test2.M2()", test1.FindImplementationForInterfaceMember(m2).ToTestDisplayString()); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"Test2.M1 2", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test1Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); } [Fact] public void MethodImplementation_051() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); compilation1.VerifyDiagnostics( // (4,10): error CS8501: Target runtime doesn't support default interface implementation. // void M1() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(4, 10) ); Assert.True(m1.IsMetadataVirtual()); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); m1 = compilation3.GetMember<MethodSymbol>("I1.M1"); var test2 = compilation3.GetTypeByMetadataName("Test2"); Assert.Same(m1, test2.FindImplementationForInterfaceMember(m1)); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.M1()' cannot implement interface member 'I1.M1()' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.M1()", "I1.M1()", "Test2").WithLocation(2, 15) ); } [Fact] public void MethodImplementation_052() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" class Test2 : I1 {} "; foreach (var reference in new[] { compilation1.EmitToImageReference(), compilation1.ToMetadataReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var m1 = compilation3.GetMember<MethodSymbol>("I1.M1"); var test2 = compilation3.GetTypeByMetadataName("Test2"); Assert.Same(m1, test2.FindImplementationForInterfaceMember(m1)); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.M1()' cannot implement interface member 'I1.M1()' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.M1()", "I1.M1()", "Test2").WithLocation(2, 15) ); } } [Fact] public void MethodImplementation_053() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" public interface I2 { void M2(); } class Test2 : I2 { public void M2() {} } "; foreach (var reference in new[] { compilation1.EmitToImageReference(), compilation1.ToMetadataReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var m1 = compilation3.GetMember<MethodSymbol>("I1.M1"); var test2 = compilation3.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(m1)); compilation3.VerifyDiagnostics(); } } [Fact] public void MethodImplementation_061() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); compilation1.VerifyDiagnostics( // (4,10): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // void M1() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M1").WithArguments("default interface implementation", "8.0").WithLocation(4, 10), // (4,10): error CS8701: Target runtime doesn't support default interface implementation. // void M1() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(4, 10) ); Assert.True(m1.IsMetadataVirtual()); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); m1 = compilation3.GetMember<MethodSymbol>("I1.M1"); var test2 = compilation3.GetTypeByMetadataName("Test2"); Assert.Same(m1, test2.FindImplementationForInterfaceMember(m1)); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.M1()' cannot implement interface member 'I1.M1()' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.M1()", "I1.M1()", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.M1()' cannot implement interface member 'I1.M1()' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.M1()", "I1.M1()", "Test2").WithLocation(2, 15) ); } [Fact] public void MethodImplementation_071() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); compilation1.VerifyDiagnostics( // (4,10): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // void M1() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M1").WithArguments("default interface implementation", "8.0").WithLocation(4, 10) ); Assert.True(m1.IsMetadataVirtual()); var source2 = @" class Test2 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); m1 = compilation2.GetMember<MethodSymbol>("I1.M1"); var test2 = compilation2.GetTypeByMetadataName("Test2"); Assert.Same(m1, test2.FindImplementationForInterfaceMember(m1)); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test2Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test2"); Assert.Equal("I1", test2Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); }); var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); m1 = compilation3.GetMember<MethodSymbol>("I1.M1"); test2 = compilation3.GetTypeByMetadataName("Test2"); Assert.Same(m1, test2.FindImplementationForInterfaceMember(m1)); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.M1()' cannot implement interface member 'I1.M1()' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.M1()", "I1.M1()", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15) ); } [Fact] public void MethodImplementation_081() { var source1 = @" public interface I1 { I1 M1() { throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); compilation1.VerifyDiagnostics( // (4,8): error CS8501: Target runtime doesn't support default interface implementation. // I1 M1() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(4, 8) ); Assert.True(m1.IsMetadataVirtual()); } [Fact] public void MethodImplementation_091() { var source1 = @" public interface I1 { static void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsStatic); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); compilation1.VerifyDiagnostics( // (4,17): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static void M1() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M1").WithArguments("default interface implementation", "8.0").WithLocation(4, 17) ); Assert.False(m1.IsMetadataVirtual()); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (4,17): error CS8701: Target runtime doesn't support default interface implementation. // static void M1() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(4, 17) ); } [Fact] public void MethodImplementation_101() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""M1""); } } public interface I2 : I1 {} class Test1 : I2 { static void Main() { I1 x = new Test1(); x.M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var m1 = compilation1.GetMember<MethodSymbol>("I1.M1"); Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); compilation1.VerifyDiagnostics(); Assert.True(m1.IsMetadataVirtual()); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var result = (PEMethodSymbol)i1.GetMember("M1"); Assert.True(result.IsMetadataVirtual()); Assert.False(result.IsAbstract); Assert.True(result.IsVirtual); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); int rva; ((PEModuleSymbol)m).Module.GetMethodDefPropsOrThrow(result.Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); var test1Result = m.GlobalNamespace.GetTypeMember("Test1"); var interfaces = test1Result.InterfacesNoUseSiteDiagnostics().ToArray(); Assert.Equal(2, interfaces.Length); Assert.Equal("I2", interfaces[0].ToTestDisplayString()); Assert.Equal("I1", interfaces[1].ToTestDisplayString()); }); var source2 = @" class Test2 : I2 { static void Main() { I1 x = new Test2(); x.M1(); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); m1 = compilation2.GetMember<MethodSymbol>("I1.M1"); var test2 = compilation2.GetTypeByMetadataName("Test2"); Assert.Same(m1, test2.FindImplementationForInterfaceMember(m1)); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test2Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test2"); var interfaces = test2Result.InterfacesNoUseSiteDiagnostics().ToArray(); Assert.Equal(2, interfaces.Length); Assert.Equal("I2", interfaces[0].ToTestDisplayString()); Assert.Equal("I1", interfaces[1].ToTestDisplayString()); }); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); m1 = compilation3.GetMember<MethodSymbol>("I1.M1"); test2 = compilation3.GetTypeByMetadataName("Test2"); Assert.Same(m1, test2.FindImplementationForInterfaceMember(m1)); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test2Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test2"); var interfaces = test2Result.InterfacesNoUseSiteDiagnostics().ToArray(); Assert.Equal(2, interfaces.Length); Assert.Equal("I2", interfaces[0].ToTestDisplayString()); Assert.Equal("I1", interfaces[1].ToTestDisplayString()); }); } [Fact] public void MethodImplementation_111() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2 : I1<string> { } "; var source2 = @" #nullable enable class Test1 : I2, I1<string?> { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[2].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I1<string?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I1.M1 I1.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementation_112() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2 : I1<string> { } "; var source2 = @" #nullable enable class Test1 : I1<string?>, I2 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I1<System.String?>", "I2", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I1<System.String>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[0].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I1<System.String>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[2].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I1<string?>, I2 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string>", "Test1").WithLocation(4, 7) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I1.M1 I1.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementation_113() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2 : I1<string> { } public interface I3 : I1<string?> { } "; var source2 = @" #nullable enable class Test1 : I2, I3 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I1.M1 I1.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementation_114() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2 : I1<string> { } public interface I3 : I1<string?> { } "; var source2 = @" #nullable enable class Test1 : I3, I2 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I3", "I1<System.String?>", "I2", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I1<System.String>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I1<System.String>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I3, I2 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string>", "Test1").WithLocation(4, 7) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I1.M1 I1.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void PropertyImplementation_101() { var source1 = @" public interface I1 { int P1 { get { System.Console.WriteLine(""get P1""); return 0; } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "; ValidatePropertyImplementation_101(source1); } private void ValidatePropertyImplementation_101(string source1) { ValidatePropertyImplementation_101(source1, "P1", haveGet: true, haveSet: false, accessCode: @" _ = i1.P1; ", expectedOutput: "get P1"); } private void ValidatePropertyImplementation_101(string source1, string propertyName, bool haveGet, bool haveSet, string accessCode, string expectedOutput) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { ValidatePropertyImplementationTest1_101(m, propertyName, haveGet, haveSet); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { I1 i1 = new Test2(); " + accessCode + @" } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate2(ModuleSymbol m) { ValidatePropertyImplementationTest2_101(m, propertyName, haveGet, haveSet); } Validate2(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate2(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); } private static void ValidatePropertyImplementationTest1_101(ModuleSymbol m, string propertyName, bool haveGet, bool haveSet) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var p1 = i1.GetMember<PropertySymbol>(propertyName); Assert.Equal(!haveSet, p1.IsReadOnly); Assert.Equal(!haveGet, p1.IsWriteOnly); if (haveGet) { ValidateAccessor(p1.GetMethod); } else { Assert.Null(p1.GetMethod); } if (haveSet) { ValidateAccessor(p1.SetMethod); } else { Assert.Null(p1.SetMethod); } void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); if (m is PEModuleSymbol peModule) { int rva; if (haveGet) { peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)p1.GetMethod).Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); } if (haveSet) { peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)p1.SetMethod).Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); } } var test1 = m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); if (haveGet) { Assert.Same(p1.GetMethod, test1.FindImplementationForInterfaceMember(p1.GetMethod)); } if (haveSet) { Assert.Same(p1.SetMethod, test1.FindImplementationForInterfaceMember(p1.SetMethod)); } } private static void ValidatePropertyImplementationTest2_101(ModuleSymbol m, string propertyName, bool haveGet, bool haveSet) { var test2 = m.GlobalNamespace.GetTypeMember("Test2"); Assert.Equal("I1", test2.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); var p1 = test2.InterfacesNoUseSiteDiagnostics().Single().GetMember<PropertySymbol>(propertyName); Assert.Same(p1, test2.FindImplementationForInterfaceMember(p1)); if (haveGet) { var getP1 = p1.GetMethod; Assert.Same(getP1, test2.FindImplementationForInterfaceMember(getP1)); } if (haveSet) { var setP1 = p1.SetMethod; Assert.Same(setP1, test2.FindImplementationForInterfaceMember(setP1)); } } [Fact] public void PropertyImplementation_102() { var source1 = @" public interface I1 { int P1 { get { System.Console.WriteLine(""get P1""); return 0; } set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.P1 = i1.P1; } } "; ValidatePropertyImplementation_102(source1); } private void ValidatePropertyImplementation_102(string source1) { ValidatePropertyImplementation_101(source1, "P1", haveGet: true, haveSet: true, accessCode: @" i1.P1 = i1.P1; ", expectedOutput: @"get P1 set P1"); } [Fact] public void PropertyImplementation_103() { var source1 = @" public interface I1 { int P1 { set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } } "; ValidatePropertyImplementation_103(source1); } private void ValidatePropertyImplementation_103(string source1) { ValidatePropertyImplementation_101(source1, "P1", haveGet: false, haveSet: true, accessCode: @" i1.P1 = 1; ", expectedOutput: "set P1"); } [Fact] public void PropertyImplementation_104() { var source1 = @" public interface I1 { int P1 => Test1.GetInt(); } class Test1 : I1 { public static int GetInt() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "; ValidatePropertyImplementation_101(source1); } [Fact] public void PropertyImplementation_105() { var source1 = @" public interface I1 { int P1 {add; remove;} => 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,13): error CS1014: A get, set or init accessor expected // int P1 {add; remove;} => 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "add").WithLocation(4, 13), // (4,18): error CS1014: A get, set or init accessor expected // int P1 {add; remove;} => 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "remove").WithLocation(4, 18), // (4,9): error CS0548: 'I1.P1': property or indexer must have at least one accessor // int P1 {add; remove;} => 0; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "P1").WithArguments("I1.P1").WithLocation(4, 9), // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // int P1 {add; remove;} => 0; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "int P1 {add; remove;} => 0;").WithLocation(4, 5) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.P1"); Assert.True(p1.IsAbstract); Assert.Null(p1.GetMethod); Assert.Null(p1.SetMethod); Assert.True(p1.IsReadOnly); Assert.True(p1.IsWriteOnly); } [Fact] public void PropertyImplementation_106() { var source1 = @" public interface I1 { int P1 {get; set;} => 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // int P1 {get; set;} => 0; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "int P1 {get; set;} => 0;").WithLocation(4, 5) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.P1"); Assert.True(p1.IsAbstract); Assert.True(p1.GetMethod.IsAbstract); Assert.True(p1.SetMethod.IsAbstract); Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); } [Fact] public void PropertyImplementation_107() { var source1 = @" public interface I1 { int P1 {add; remove;} = 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics( // (4,13): error CS1014: A get, set or init accessor expected // int P1 {add; remove;} = 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "add").WithLocation(4, 13), // (4,18): error CS1014: A get, set or init accessor expected // int P1 {add; remove;} = 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "remove").WithLocation(4, 18), // (4,9): error CS8053: Instance properties in interfaces cannot have initializers. // int P1 {add; remove;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P1").WithArguments("I1.P1").WithLocation(4, 9), // (4,9): error CS0548: 'I1.P1': property or indexer must have at least one accessor // int P1 {add; remove;} = 0; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "P1").WithArguments("I1.P1").WithLocation(4, 9) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.P1"); Assert.True(p1.IsAbstract); Assert.Null(p1.GetMethod); Assert.Null(p1.SetMethod); Assert.True(p1.IsReadOnly); Assert.True(p1.IsWriteOnly); } [Fact] public void PropertyImplementation_108() { var source1 = @" public interface I1 { int P1 {get; set;} = 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics( // (4,9): error CS8053: Instance properties in interfaces cannot have initializers.. // int P1 {get; set;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P1").WithArguments("I1.P1").WithLocation(4, 9) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.P1"); Assert.True(p1.IsAbstract); Assert.True(p1.GetMethod.IsAbstract); Assert.True(p1.SetMethod.IsAbstract); Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); } [Fact] public void PropertyImplementation_109() { var source1 = @" public interface I1 { int P1 { get { System.Console.WriteLine(""get P1""); return 0; } set; } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // According to LDM decision captured at https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-04-18.md, // we don't want to allow only one accessor to have an implementation. compilation1.VerifyDiagnostics( // (11,9): error CS0501: 'I1.P1.set' must declare a body because it is not marked abstract, extern, or partial // set; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.P1.set").WithLocation(11, 9) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.P1"); var getP1 = p1.GetMethod; var setP1 = p1.SetMethod; Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(getP1.IsAbstract); Assert.True(getP1.IsVirtual); Assert.False(setP1.IsAbstract); Assert.True(setP1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(getP1, test1.FindImplementationForInterfaceMember(getP1)); Assert.Same(setP1, test1.FindImplementationForInterfaceMember(setP1)); Assert.True(getP1.IsMetadataVirtual()); Assert.True(setP1.IsMetadataVirtual()); } [Fact] public void PropertyImplementation_110() { var source1 = @" public interface I1 { int P1 { get; set => System.Console.WriteLine(""set P1""); } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // According to LDM decision captured at https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-04-18.md, // we don't want to allow only one accessor to have an implementation. compilation1.VerifyDiagnostics( // (6,9): error CS0501: 'I1.P1.get' must declare a body because it is not marked abstract, extern, or partial // get; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.P1.get").WithLocation(6, 9) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.P1"); var getP1 = p1.GetMethod; var setP1 = p1.SetMethod; Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(getP1.IsAbstract); Assert.True(getP1.IsVirtual); Assert.False(setP1.IsAbstract); Assert.True(setP1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(getP1, test1.FindImplementationForInterfaceMember(getP1)); Assert.Same(setP1, test1.FindImplementationForInterfaceMember(setP1)); Assert.True(getP1.IsMetadataVirtual()); Assert.True(setP1.IsMetadataVirtual()); } [Fact] public void PropertyImplementation_201() { var source1 = @" interface I1 { int P1 => 1; int P2 => 2; int P3 { get => 3; } int P4 { get => 4; } int P5 { set => System.Console.WriteLine(5); } int P6 { set => System.Console.WriteLine(6); } int P7 { get { return 7;} set {System.Console.WriteLine(71);} } int P8 { get { return 8;} set {System.Console.WriteLine(81);} } } class Base { int P1 => 10; int P3 { get => 30; } int P5 { set => System.Console.WriteLine(50); } int P7 { get { return 70;} set {} } } class Derived : Base, I1 { int P2 => 20; int P4 { get => 40; } int P6 { set => System.Console.WriteLine(60); } int P8 { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1.P1); System.Console.WriteLine(i1.P2); System.Console.WriteLine(i1.P3); System.Console.WriteLine(i1.P4); i1.P5 = 0; i1.P6 = 0; System.Console.WriteLine(i1.P7); i1.P7 = 0; System.Console.WriteLine(i1.P8); i1.P8 = 0; } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidatePropertyImplementation_201(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"1 2 3 4 5 6 7 71 8 81 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidatePropertyImplementation_201(m); }); } private static void ValidatePropertyImplementation_201(ModuleSymbol m) { var p1 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P1"); var p2 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P2"); var p3 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P3"); var p4 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P4"); var p5 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P5"); var p6 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P6"); var p7 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P7"); var p8 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P8"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Same(p1, derived.FindImplementationForInterfaceMember(p1)); Assert.Same(p2, derived.FindImplementationForInterfaceMember(p2)); Assert.Same(p3, derived.FindImplementationForInterfaceMember(p3)); Assert.Same(p4, derived.FindImplementationForInterfaceMember(p4)); Assert.Same(p5, derived.FindImplementationForInterfaceMember(p5)); Assert.Same(p6, derived.FindImplementationForInterfaceMember(p6)); Assert.Same(p7, derived.FindImplementationForInterfaceMember(p7)); Assert.Same(p8, derived.FindImplementationForInterfaceMember(p8)); Assert.Same(p1.GetMethod, derived.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Same(p2.GetMethod, derived.FindImplementationForInterfaceMember(p2.GetMethod)); Assert.Same(p3.GetMethod, derived.FindImplementationForInterfaceMember(p3.GetMethod)); Assert.Same(p4.GetMethod, derived.FindImplementationForInterfaceMember(p4.GetMethod)); Assert.Same(p5.SetMethod, derived.FindImplementationForInterfaceMember(p5.SetMethod)); Assert.Same(p6.SetMethod, derived.FindImplementationForInterfaceMember(p6.SetMethod)); Assert.Same(p7.GetMethod, derived.FindImplementationForInterfaceMember(p7.GetMethod)); Assert.Same(p8.GetMethod, derived.FindImplementationForInterfaceMember(p8.GetMethod)); Assert.Same(p7.SetMethod, derived.FindImplementationForInterfaceMember(p7.SetMethod)); Assert.Same(p8.SetMethod, derived.FindImplementationForInterfaceMember(p8.SetMethod)); } [Fact] public void PropertyImplementation_202() { var source1 = @" interface I1 { int P1 => 1; int P2 => 2; int P3 { get => 3; } int P4 { get => 4; } int P5 { set => System.Console.WriteLine(5); } int P6 { set => System.Console.WriteLine(6); } int P7 { get { return 7;} set {System.Console.WriteLine(71);} } int P8 { get { return 8;} set {System.Console.WriteLine(81);} } } class Base : Test { int P1 => 10; int P3 { get => 30; } int P5 { set => System.Console.WriteLine(50); } int P7 { get { return 70;} set {} } } class Derived : Base, I1 { int P2 => 20; int P4 { get => 40; } int P6 { set => System.Console.WriteLine(60); } int P8 { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1.P1); System.Console.WriteLine(i1.P2); System.Console.WriteLine(i1.P3); System.Console.WriteLine(i1.P4); i1.P5 = 0; i1.P6 = 0; System.Console.WriteLine(i1.P7); i1.P7 = 0; System.Console.WriteLine(i1.P8); i1.P8 = 0; } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidatePropertyImplementation_201(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"1 2 3 4 5 6 7 71 8 81 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidatePropertyImplementation_201(m); }); } [Fact] public void PropertyImplementation_203() { var source1 = @" interface I1 { int P1 => 1; int P2 => 2; int P3 { get => 3; } int P4 { get => 4; } int P5 { set => System.Console.WriteLine(5); } int P6 { set => System.Console.WriteLine(6); } int P7 { get { return 7;} set {} } int P8 { get { return 8;} set {} } } class Base : Test { int P1 => 10; int P3 { get => 30; } int P5 { set => System.Console.WriteLine(50); } int P7 { get { return 70;} set {} } } class Derived : Base, I1 { int P2 => 20; int P4 { get => 40; } int P6 { set => System.Console.WriteLine(60); } int P8 { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1.P1); System.Console.WriteLine(i1.P2); System.Console.WriteLine(i1.P3); System.Console.WriteLine(i1.P4); i1.P5 = 0; i1.P6 = 0; System.Console.WriteLine(i1.P7); i1.P7 = 0; System.Console.WriteLine(i1.P8); i1.P8 = 0; } } class Test : I1 { int I1.P1 => 100; int I1.P2 => 200; int I1.P3 { get => 300; } int I1.P4 { get => 400; } int I1.P5 { set => System.Console.WriteLine(500); } int I1.P6 { set => System.Console.WriteLine(600); } int I1.P7 { get { return 700;} set {System.Console.WriteLine(701);} } int I1.P8 { get { return 800;} set {System.Console.WriteLine(801);} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var p1 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P1"); var p2 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P2"); var p3 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P3"); var p4 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P4"); var p5 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P5"); var p6 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P6"); var p7 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P7"); var p8 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P8"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Equal("System.Int32 Test.I1.P1 { get; }", derived.FindImplementationForInterfaceMember(p1).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P2 { get; }", derived.FindImplementationForInterfaceMember(p2).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P3 { get; }", derived.FindImplementationForInterfaceMember(p3).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P4 { get; }", derived.FindImplementationForInterfaceMember(p4).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P5 { set; }", derived.FindImplementationForInterfaceMember(p5).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P6 { set; }", derived.FindImplementationForInterfaceMember(p6).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P7 { get; set; }", derived.FindImplementationForInterfaceMember(p7).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P8 { get; set; }", derived.FindImplementationForInterfaceMember(p8).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P1.get", derived.FindImplementationForInterfaceMember(p1.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P2.get", derived.FindImplementationForInterfaceMember(p2.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P3.get", derived.FindImplementationForInterfaceMember(p3.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P4.get", derived.FindImplementationForInterfaceMember(p4.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.P5.set", derived.FindImplementationForInterfaceMember(p5.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.P6.set", derived.FindImplementationForInterfaceMember(p6.SetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P7.get", derived.FindImplementationForInterfaceMember(p7.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.P8.get", derived.FindImplementationForInterfaceMember(p8.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.P7.set", derived.FindImplementationForInterfaceMember(p7.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.P8.set", derived.FindImplementationForInterfaceMember(p8.SetMethod).ToTestDisplayString()); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"100 200 300 400 500 600 700 701 800 801 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void PropertyImplementation_204() { var source1 = @" interface I1 { int P1 => 1; int P2 => 2; int P3 { get => 3; } int P4 { get => 4; } int P5 { set => System.Console.WriteLine(5); } int P6 { set => System.Console.WriteLine(6); } int P7 { get { return 7;} set {} } int P8 { get { return 8;} set {} } } class Base : Test { new int P1 => 10; new int P3 { get => 30; } new int P5 { set => System.Console.WriteLine(50); } new int P7 { get { return 70;} set {} } } class Derived : Base, I1 { new int P2 => 20; new int P4 { get => 40; } new int P6 { set => System.Console.WriteLine(60); } new int P8 { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1.P1); System.Console.WriteLine(i1.P2); System.Console.WriteLine(i1.P3); System.Console.WriteLine(i1.P4); i1.P5 = 0; i1.P6 = 0; System.Console.WriteLine(i1.P7); i1.P7 = 0; System.Console.WriteLine(i1.P8); i1.P8 = 0; } } class Test : I1 { public int P1 => 100; public int P2 => 200; public int P3 { get => 300; } public int P4 { get => 400; } public int P5 { set => System.Console.WriteLine(500); } public int P6 { set => System.Console.WriteLine(600); } public int P7 { get { return 700;} set {System.Console.WriteLine(701);} } public int P8 { get { return 800;} set {System.Console.WriteLine(801);} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var p1 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P1"); var p2 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P2"); var p3 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P3"); var p4 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P4"); var p5 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P5"); var p6 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P6"); var p7 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P7"); var p8 = m.GlobalNamespace.GetMember<PropertySymbol>("I1.P8"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Equal("System.Int32 Test.P1 { get; }", derived.FindImplementationForInterfaceMember(p1).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P2 { get; }", derived.FindImplementationForInterfaceMember(p2).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P3 { get; }", derived.FindImplementationForInterfaceMember(p3).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P4 { get; }", derived.FindImplementationForInterfaceMember(p4).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P5 { set; }", derived.FindImplementationForInterfaceMember(p5).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P6 { set; }", derived.FindImplementationForInterfaceMember(p6).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P7 { get; set; }", derived.FindImplementationForInterfaceMember(p7).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P8 { get; set; }", derived.FindImplementationForInterfaceMember(p8).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P1.get", derived.FindImplementationForInterfaceMember(p1.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P2.get", derived.FindImplementationForInterfaceMember(p2.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P3.get", derived.FindImplementationForInterfaceMember(p3.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P4.get", derived.FindImplementationForInterfaceMember(p4.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.P5.set", derived.FindImplementationForInterfaceMember(p5.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.P6.set", derived.FindImplementationForInterfaceMember(p6.SetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P7.get", derived.FindImplementationForInterfaceMember(p7.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.P8.get", derived.FindImplementationForInterfaceMember(p8.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.P7.set", derived.FindImplementationForInterfaceMember(p7.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.P8.set", derived.FindImplementationForInterfaceMember(p8.SetMethod).ToTestDisplayString()); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"100 200 300 400 500 600 700 701 800 801 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void PropertyImplementation_501() { var source1 = @" public interface I1 { int P1 => 1; int P3 { get => 3; } int P5 { set => System.Console.WriteLine(5); } int P7 { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,15): error CS8501: Target runtime doesn't support default interface implementation. // int P1 => 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "1").WithLocation(4, 15), // (6,7): error CS8501: Target runtime doesn't support default interface implementation. // { get => 3; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(6, 7), // (8,7): error CS8501: Target runtime doesn't support default interface implementation. // { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(8, 7), // (11,9): error CS8501: Target runtime doesn't support default interface implementation. // get { return 7;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(11, 9), // (12,9): error CS8501: Target runtime doesn't support default interface implementation. // set {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(12, 9) ); ValidatePropertyImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.P7.set' cannot implement interface member 'I1.P7.set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.set", "I1.P7.set", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P1.get' cannot implement interface member 'I1.P1.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P1.get", "I1.P1.get", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P3.get' cannot implement interface member 'I1.P3.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P3.get", "I1.P3.get", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P5.set' cannot implement interface member 'I1.P5.set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P5.set", "I1.P5.set", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P7.get' cannot implement interface member 'I1.P7.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.get", "I1.P7.get", "Test2").WithLocation(2, 15) ); ValidatePropertyImplementation_501(compilation3.SourceModule, "Test2"); } private static void ValidatePropertyImplementation_501(ModuleSymbol m, string typeName) { var derived = m.GlobalNamespace.GetTypeMember(typeName); var i1 = derived.InterfacesNoUseSiteDiagnostics().Single(); Assert.Equal("I1", i1.ToTestDisplayString()); var p1 = i1.GetMember<PropertySymbol>("P1"); var p3 = i1.GetMember<PropertySymbol>("P3"); var p5 = i1.GetMember<PropertySymbol>("P5"); var p7 = i1.GetMember<PropertySymbol>("P7"); Assert.True(p1.IsVirtual); Assert.True(p3.IsVirtual); Assert.True(p5.IsVirtual); Assert.True(p7.IsVirtual); Assert.False(p1.IsAbstract); Assert.False(p3.IsAbstract); Assert.False(p5.IsAbstract); Assert.False(p7.IsAbstract); Assert.Same(p1, derived.FindImplementationForInterfaceMember(p1)); Assert.Same(p3, derived.FindImplementationForInterfaceMember(p3)); Assert.Same(p5, derived.FindImplementationForInterfaceMember(p5)); Assert.Same(p7, derived.FindImplementationForInterfaceMember(p7)); Assert.True(p1.GetMethod.IsVirtual); Assert.True(p3.GetMethod.IsVirtual); Assert.True(p5.SetMethod.IsVirtual); Assert.True(p7.GetMethod.IsVirtual); Assert.True(p7.SetMethod.IsVirtual); Assert.True(p1.GetMethod.IsMetadataVirtual()); Assert.True(p3.GetMethod.IsMetadataVirtual()); Assert.True(p5.SetMethod.IsMetadataVirtual()); Assert.True(p7.GetMethod.IsMetadataVirtual()); Assert.True(p7.SetMethod.IsMetadataVirtual()); Assert.False(p1.GetMethod.IsAbstract); Assert.False(p3.GetMethod.IsAbstract); Assert.False(p5.SetMethod.IsAbstract); Assert.False(p7.GetMethod.IsAbstract); Assert.False(p7.SetMethod.IsAbstract); Assert.Same(p1.GetMethod, derived.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Same(p3.GetMethod, derived.FindImplementationForInterfaceMember(p3.GetMethod)); Assert.Same(p5.SetMethod, derived.FindImplementationForInterfaceMember(p5.SetMethod)); Assert.Same(p7.GetMethod, derived.FindImplementationForInterfaceMember(p7.GetMethod)); Assert.Same(p7.SetMethod, derived.FindImplementationForInterfaceMember(p7.SetMethod)); } [Fact] public void PropertyImplementation_502() { var source1 = @" public interface I1 { int P1 => 1; int P3 { get => 3; } int P5 { set => System.Console.WriteLine(5); } int P7 { get { return 7;} set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.P7.set' cannot implement interface member 'I1.P7.set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.set", "I1.P7.set", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P1.get' cannot implement interface member 'I1.P1.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P1.get", "I1.P1.get", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P3.get' cannot implement interface member 'I1.P3.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P3.get", "I1.P3.get", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P5.set' cannot implement interface member 'I1.P5.set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P5.set", "I1.P5.set", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P7.get' cannot implement interface member 'I1.P7.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.get", "I1.P7.get", "Test2").WithLocation(2, 15) ); ValidatePropertyImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void PropertyImplementation_503() { var source1 = @" public interface I1 { int P1 => 1; int P3 { get => 3; } int P5 { set => System.Console.WriteLine(5); } int P7 { get { return 7;} set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" public interface I2 { void M2(); } class Test2 : I2 { public void M2() {} } "; var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, targetFramework: TargetFramework.DesktopLatestExtended, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var test2 = compilation3.GetTypeByMetadataName("Test2"); var i1 = compilation3.GetTypeByMetadataName("I1"); Assert.Equal("I1", i1.ToTestDisplayString()); var p1 = i1.GetMember<PropertySymbol>("P1"); var p3 = i1.GetMember<PropertySymbol>("P3"); var p5 = i1.GetMember<PropertySymbol>("P5"); var p7 = i1.GetMember<PropertySymbol>("P7"); Assert.Null(test2.FindImplementationForInterfaceMember(p1)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p5)); Assert.Null(test2.FindImplementationForInterfaceMember(p7)); Assert.Null(test2.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p3.GetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p5.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p7.GetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p7.SetMethod)); compilation3.VerifyDiagnostics(); } [Fact] public void PropertyImplementation_601() { var source1 = @" public interface I1 { int P1 => 1; int P3 { get => 3; } int P5 { set => System.Console.WriteLine(5); } int P7 { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,15): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P1 => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1").WithArguments("default interface implementation", "8.0").WithLocation(4, 15), // (4,15): error CS8701: Target runtime doesn't support default interface implementation. // int P1 => 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "1").WithLocation(4, 15), // (5,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P3 { get => 3; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(5, 14), // (5,14): error CS8701: Target runtime doesn't support default interface implementation. // int P3 { get => 3; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(5, 14), // (6,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P5 { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(6, 14), // (6,14): error CS8701: Target runtime doesn't support default interface implementation. // int P5 { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(6, 14), // (7,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P7 { get { return 7;} set {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(7, 14), // (7,14): error CS8701: Target runtime doesn't support default interface implementation. // int P7 { get { return 7;} set {} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(7, 14), // (7,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P7 { get { return 7;} set {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(7, 31), // (7,31): error CS8701: Target runtime doesn't support default interface implementation. // int P7 { get { return 7;} set {} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(7, 31) ); ValidatePropertyImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.P7.set' cannot implement interface member 'I1.P7.set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.set", "I1.P7.set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P7.set' cannot implement interface member 'I1.P7.set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.set", "I1.P7.set", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P1.get' cannot implement interface member 'I1.P1.get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P1.get", "I1.P1.get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P1.get' cannot implement interface member 'I1.P1.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P1.get", "I1.P1.get", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P3.get' cannot implement interface member 'I1.P3.get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P3.get", "I1.P3.get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P3.get' cannot implement interface member 'I1.P3.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P3.get", "I1.P3.get", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P5.set' cannot implement interface member 'I1.P5.set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P5.set", "I1.P5.set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P5.set' cannot implement interface member 'I1.P5.set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P5.set", "I1.P5.set", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P7.get' cannot implement interface member 'I1.P7.get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.get", "I1.P7.get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.P7.get' cannot implement interface member 'I1.P7.get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.get", "I1.P7.get", "Test2").WithLocation(2, 15) ); ValidatePropertyImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void PropertyImplementation_701() { var source1 = @" public interface I1 { int P1 => 1; int P3 { get => 3; } int P5 { set => System.Console.WriteLine(5); } int P7 { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,15): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P1 => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1").WithArguments("default interface implementation", "8.0").WithLocation(4, 15), // (5,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P3 { get => 3; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(5, 14), // (6,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P5 { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(6, 14), // (7,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P7 { get { return 7;} set {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(7, 14), // (7,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int P7 { get { return 7;} set {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(7, 31) ); ValidatePropertyImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidatePropertyImplementation_501(compilation2.SourceModule, "Test2"); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test2Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test2"); Assert.Equal("I1", test2Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidatePropertyImplementation_501(m, "Test2"); }); var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.P7.set' cannot implement interface member 'I1.P7.set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.set", "I1.P7.set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P1.get' cannot implement interface member 'I1.P1.get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P1.get", "I1.P1.get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P3.get' cannot implement interface member 'I1.P3.get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P3.get", "I1.P3.get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P5.set' cannot implement interface member 'I1.P5.set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P5.set", "I1.P5.set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.P7.get' cannot implement interface member 'I1.P7.get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.P7.get", "I1.P7.get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15) ); ValidatePropertyImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void PropertyImplementation_901() { var source1 = @" public interface I1 { static int P1 => 1; static int P3 { get => 3; } static int P5 { set => System.Console.WriteLine(5); } static int P7 { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,16): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static int P1 => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "P1").WithArguments("default interface implementation", "8.0").WithLocation(4, 16), // (5,16): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static int P3 { get => 3; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "P3").WithArguments("default interface implementation", "8.0").WithLocation(5, 16), // (6,16): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static int P5 { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "P5").WithArguments("default interface implementation", "8.0").WithLocation(6, 16), // (7,16): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static int P7 { get { return 7;} set {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "P7").WithArguments("default interface implementation", "8.0").WithLocation(7, 16) ); var derived = compilation1.SourceModule.GlobalNamespace.GetTypeMember("Test1"); var i1 = derived.InterfacesNoUseSiteDiagnostics().Single(); Assert.Equal("I1", i1.ToTestDisplayString()); var p1 = i1.GetMember<PropertySymbol>("P1"); var p3 = i1.GetMember<PropertySymbol>("P3"); var p5 = i1.GetMember<PropertySymbol>("P5"); var p7 = i1.GetMember<PropertySymbol>("P7"); Assert.True(p1.IsStatic); Assert.True(p3.IsStatic); Assert.True(p5.IsStatic); Assert.True(p7.IsStatic); Assert.False(p1.IsVirtual); Assert.False(p3.IsVirtual); Assert.False(p5.IsVirtual); Assert.False(p7.IsVirtual); Assert.False(p1.IsAbstract); Assert.False(p3.IsAbstract); Assert.False(p5.IsAbstract); Assert.False(p7.IsAbstract); Assert.Null(derived.FindImplementationForInterfaceMember(p1)); Assert.Null(derived.FindImplementationForInterfaceMember(p3)); Assert.Null(derived.FindImplementationForInterfaceMember(p5)); Assert.Null(derived.FindImplementationForInterfaceMember(p7)); Assert.True(p1.GetMethod.IsStatic); Assert.True(p3.GetMethod.IsStatic); Assert.True(p5.SetMethod.IsStatic); Assert.True(p7.GetMethod.IsStatic); Assert.True(p7.SetMethod.IsStatic); Assert.False(p1.GetMethod.IsVirtual); Assert.False(p3.GetMethod.IsVirtual); Assert.False(p5.SetMethod.IsVirtual); Assert.False(p7.GetMethod.IsVirtual); Assert.False(p7.SetMethod.IsVirtual); Assert.False(p1.GetMethod.IsMetadataVirtual()); Assert.False(p3.GetMethod.IsMetadataVirtual()); Assert.False(p5.SetMethod.IsMetadataVirtual()); Assert.False(p7.GetMethod.IsMetadataVirtual()); Assert.False(p7.SetMethod.IsMetadataVirtual()); Assert.False(p1.GetMethod.IsAbstract); Assert.False(p3.GetMethod.IsAbstract); Assert.False(p5.SetMethod.IsAbstract); Assert.False(p7.GetMethod.IsAbstract); Assert.False(p7.SetMethod.IsAbstract); Assert.Null(derived.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(derived.FindImplementationForInterfaceMember(p3.GetMethod)); Assert.Null(derived.FindImplementationForInterfaceMember(p5.SetMethod)); Assert.Null(derived.FindImplementationForInterfaceMember(p7.GetMethod)); Assert.Null(derived.FindImplementationForInterfaceMember(p7.SetMethod)); } [Fact] public void IndexerImplementation_101() { var source1 = @" public interface I1 { int this[int i] { get { System.Console.WriteLine(""get P1""); return 0; } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "; ValidateIndexerImplementation_101(source1); } private void ValidateIndexerImplementation_101(string source1) { ValidatePropertyImplementation_101(source1, "this[]", haveGet: true, haveSet: false, accessCode: @" _ = i1[0]; ", expectedOutput: "get P1"); } [Fact] public void IndexerImplementation_102() { var source1 = @" public interface I1 { int this[int i] { get { System.Console.WriteLine(""get P1""); return 0; } set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1[0] = i1[0]; } } "; ValidateIndexerImplementation_102(source1); } private void ValidateIndexerImplementation_102(string source1) { ValidatePropertyImplementation_101(source1, "this[]", haveGet: true, haveSet: true, accessCode: @" i1[0] = i1[0]; ", expectedOutput: @"get P1 set P1"); } [Fact] public void IndexerImplementation_103() { var source1 = @" public interface I1 { int this[int i] { set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } } "; ValidateIndexerImplementation_103(source1); } private void ValidateIndexerImplementation_103(string source1) { ValidatePropertyImplementation_101(source1, "this[]", haveGet: false, haveSet: true, accessCode: @" i1[0] = 1; ", expectedOutput: "set P1"); } [Fact] public void IndexerImplementation_104() { var source1 = @" public interface I1 { int this[int i] => Test1.GetInt(); } class Test1 : I1 { public static int GetInt() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "; ValidateIndexerImplementation_101(source1); } [Fact] public void IndexerImplementation_105() { var source1 = @" public interface I1 { int this[int i] {add; remove;} => 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,22): error CS1014: A get, set or init accessor expected // int this[int i] {add; remove;} => 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "add").WithLocation(4, 22), // (4,27): error CS1014: A get, set or init accessor expected // int this[int i] {add; remove;} => 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "remove").WithLocation(4, 27), // (4,9): error CS0548: 'I1.this[int]': property or indexer must have at least one accessor // int this[int i] {add; remove;} => 0; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I1.this[int]").WithLocation(4, 9), // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // int this[int i] {add; remove;} => 0; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "int this[int i] {add; remove;} => 0;").WithLocation(4, 5) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.this[]"); Assert.True(p1.IsAbstract); Assert.Null(p1.GetMethod); Assert.Null(p1.SetMethod); Assert.True(p1.IsReadOnly); Assert.True(p1.IsWriteOnly); } [Fact] public void IndexerImplementation_106() { var source1 = @" public interface I1 { int this[int i] {get; set;} => 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // int this[int i] {get; set;} => 0; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "int this[int i] {get; set;} => 0;").WithLocation(4, 5) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.this[]"); Assert.True(p1.IsAbstract); Assert.True(p1.GetMethod.IsAbstract); Assert.True(p1.SetMethod.IsAbstract); Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); } [Fact] public void IndexerImplementation_107() { var source1 = @" public interface I1 { int this[int i] {add; remove;} = 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,36): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // int this[int i] {add; remove;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(4, 36), // (4,22): error CS1014: A get, set or init accessor expected // int this[int i] {add; remove;} = 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "add").WithLocation(4, 22), // (4,27): error CS1014: A get, set or init accessor expected // int this[int i] {add; remove;} = 0; Diagnostic(ErrorCode.ERR_GetOrSetExpected, "remove").WithLocation(4, 27), // (4,9): error CS0548: 'I1.this[int]': property or indexer must have at least one accessor // int this[int i] {add; remove;} = 0; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I1.this[int]").WithLocation(4, 9) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.this[]"); Assert.True(p1.IsAbstract); Assert.Null(p1.GetMethod); Assert.Null(p1.SetMethod); Assert.True(p1.IsReadOnly); Assert.True(p1.IsWriteOnly); } [Fact] public void IndexerImplementation_108() { var source1 = @" public interface I1 { int this[int i] {get; set;} = 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,33): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // int this[int i] {get; set;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(4, 33) ); var p1 = compilation1.GetMember<PropertySymbol>("I1.this[]"); Assert.True(p1.IsAbstract); Assert.True(p1.GetMethod.IsAbstract); Assert.True(p1.SetMethod.IsAbstract); Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); } [Fact] public void IndexerImplementation_109() { var source1 = @" public interface I1 { int this[int i] { get { System.Console.WriteLine(""get P1""); return 0; } set; } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // According to LDM decision captured at https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-04-18.md, // we don't want to allow only one accessor to have an implementation. compilation1.VerifyDiagnostics( // (11,9): error CS0501: 'I1.this[int].set' must declare a body because it is not marked abstract, extern, or partial // set; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.this[int].set") ); var p1 = compilation1.GetMember<PropertySymbol>("I1.this[]"); var getP1 = p1.GetMethod; var setP1 = p1.SetMethod; Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(getP1.IsAbstract); Assert.True(getP1.IsVirtual); Assert.False(setP1.IsAbstract); Assert.True(setP1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(getP1, test1.FindImplementationForInterfaceMember(getP1)); Assert.Same(setP1, test1.FindImplementationForInterfaceMember(setP1)); Assert.True(getP1.IsMetadataVirtual()); Assert.True(setP1.IsMetadataVirtual()); } [Fact] public void IndexerImplementation_110() { var source1 = @" public interface I1 { int this[int i] { get; set => System.Console.WriteLine(""set P1""); } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // According to LDM decision captured at https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-04-18.md, // we don't want to allow only one accessor to have an implementation. compilation1.VerifyDiagnostics( // (6,9): error CS0501: 'I1.this[int].get' must declare a body because it is not marked abstract, extern, or partial // get; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.this[int].get") ); var p1 = compilation1.GetMember<PropertySymbol>("I1.this[]"); var getP1 = p1.GetMethod; var setP1 = p1.SetMethod; Assert.False(p1.IsReadOnly); Assert.False(p1.IsWriteOnly); Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(getP1.IsAbstract); Assert.True(getP1.IsVirtual); Assert.False(setP1.IsAbstract); Assert.True(setP1.IsVirtual); var test1 = compilation1.GetTypeByMetadataName("Test1"); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(getP1, test1.FindImplementationForInterfaceMember(getP1)); Assert.Same(setP1, test1.FindImplementationForInterfaceMember(setP1)); Assert.True(getP1.IsMetadataVirtual()); Assert.True(setP1.IsMetadataVirtual()); } [Fact] public void IndexerImplementation_201() { var source1 = @" interface I1 { int this[sbyte i] => 1; int this[byte i] => 2; int this[short i] { get => 3; } int this[ushort i] { get => 4; } int this[int i] { set => System.Console.WriteLine(5); } int this[uint i] { set => System.Console.WriteLine(6); } int this[long i] { get { return 7;} set {System.Console.WriteLine(71);} } int this[ulong i] { get { return 8;} set {System.Console.WriteLine(81);} } } class Base { int this[sbyte i] => 10; int this[short i] { get => 30; } int this[int i] { set => System.Console.WriteLine(50); } int this[long i] { get { return 70;} set {} } } class Derived : Base, I1 { int this[byte i] => 20; int this[ushort i] { get => 40; } int this[uint i] { set => System.Console.WriteLine(60); } int this[ulong i] { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1[(sbyte)0]); System.Console.WriteLine(i1[(byte)0]); System.Console.WriteLine(i1[(short)0]); System.Console.WriteLine(i1[(ushort)0]); i1[(int)0] = 0; i1[(uint)0] = 0; System.Console.WriteLine(i1[(long)0]); i1[(long)0] = 0; System.Console.WriteLine(i1[(ulong)0]); i1[(ulong)0] = 0; } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateIndexerImplementation_201(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"1 2 3 4 5 6 7 71 8 81 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidateIndexerImplementation_201(m); }); } private static void ValidateIndexerImplementation_201(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var indexers = i1.GetMembers("this[]"); var p1 = (PropertySymbol)indexers[0]; var p2 = (PropertySymbol)indexers[1]; var p3 = (PropertySymbol)indexers[2]; var p4 = (PropertySymbol)indexers[3]; var p5 = (PropertySymbol)indexers[4]; var p6 = (PropertySymbol)indexers[5]; var p7 = (PropertySymbol)indexers[6]; var p8 = (PropertySymbol)indexers[7]; var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Same(p1, derived.FindImplementationForInterfaceMember(p1)); Assert.Same(p2, derived.FindImplementationForInterfaceMember(p2)); Assert.Same(p3, derived.FindImplementationForInterfaceMember(p3)); Assert.Same(p4, derived.FindImplementationForInterfaceMember(p4)); Assert.Same(p5, derived.FindImplementationForInterfaceMember(p5)); Assert.Same(p6, derived.FindImplementationForInterfaceMember(p6)); Assert.Same(p7, derived.FindImplementationForInterfaceMember(p7)); Assert.Same(p8, derived.FindImplementationForInterfaceMember(p8)); Assert.Same(p1.GetMethod, derived.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Same(p2.GetMethod, derived.FindImplementationForInterfaceMember(p2.GetMethod)); Assert.Same(p3.GetMethod, derived.FindImplementationForInterfaceMember(p3.GetMethod)); Assert.Same(p4.GetMethod, derived.FindImplementationForInterfaceMember(p4.GetMethod)); Assert.Same(p5.SetMethod, derived.FindImplementationForInterfaceMember(p5.SetMethod)); Assert.Same(p6.SetMethod, derived.FindImplementationForInterfaceMember(p6.SetMethod)); Assert.Same(p7.GetMethod, derived.FindImplementationForInterfaceMember(p7.GetMethod)); Assert.Same(p8.GetMethod, derived.FindImplementationForInterfaceMember(p8.GetMethod)); Assert.Same(p7.SetMethod, derived.FindImplementationForInterfaceMember(p7.SetMethod)); Assert.Same(p8.SetMethod, derived.FindImplementationForInterfaceMember(p8.SetMethod)); } [Fact] public void IndexerImplementation_202() { var source1 = @" interface I1 { int this[sbyte i] => 1; int this[byte i] => 2; int this[short i] { get => 3; } int this[ushort i] { get => 4; } int this[int i] { set => System.Console.WriteLine(5); } int this[uint i] { set => System.Console.WriteLine(6); } int this[long i] { get { return 7;} set {System.Console.WriteLine(71);} } int this[ulong i] { get { return 8;} set {System.Console.WriteLine(81);} } } class Base : Test { int this[sbyte i] => 10; int this[short i] { get => 30; } int this[int i] { set => System.Console.WriteLine(50); } int this[long i] { get { return 70;} set {} } } class Derived : Base, I1 { int this[byte i] => 20; int this[ushort i] { get => 40; } int this[uint i] { set => System.Console.WriteLine(60); } int this[ulong i] { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1[(sbyte)0]); System.Console.WriteLine(i1[(byte)0]); System.Console.WriteLine(i1[(short)0]); System.Console.WriteLine(i1[(ushort)0]); i1[(int)0] = 0; i1[(uint)0] = 0; System.Console.WriteLine(i1[(long)0]); i1[(long)0] = 0; System.Console.WriteLine(i1[(ulong)0]); i1[(ulong)0] = 0; } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateIndexerImplementation_201(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"1 2 3 4 5 6 7 71 8 81 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidateIndexerImplementation_201(m); }); } [Fact] public void IndexerImplementation_203() { var source1 = @" interface I1 { int this[sbyte i] => 1; int this[byte i] => 2; int this[short i] { get => 3; } int this[ushort i] { get => 4; } int this[int i] { set => System.Console.WriteLine(5); } int this[uint i] { set => System.Console.WriteLine(6); } int this[long i] { get { return 7;} set {} } int this[ulong i] { get { return 8;} set {} } } class Base : Test { int this[sbyte i] => 10; int this[short i] { get => 30; } int this[int i] { set => System.Console.WriteLine(50); } int this[long i] { get { return 70;} set {} } } class Derived : Base, I1 { int this[byte i] => 20; int this[ushort i] { get => 40; } int this[uint i] { set => System.Console.WriteLine(60); } int this[ulong i] { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1[(sbyte)0]); System.Console.WriteLine(i1[(byte)0]); System.Console.WriteLine(i1[(short)0]); System.Console.WriteLine(i1[(ushort)0]); i1[(int)0] = 0; i1[(uint)0] = 0; System.Console.WriteLine(i1[(long)0]); i1[(long)0] = 0; System.Console.WriteLine(i1[(ulong)0]); i1[(ulong)0] = 0; } } class Test : I1 { int I1.this[sbyte i] => 100; int I1.this[byte i] => 200; int I1.this[short i] { get => 300; } int I1.this[ushort i] { get => 400; } int I1.this[int i] { set => System.Console.WriteLine(500); } int I1.this[uint i] { set => System.Console.WriteLine(600); } int I1.this[long i] { get { return 700;} set {System.Console.WriteLine(701);} } int I1.this[ulong i] { get { return 800;} set {System.Console.WriteLine(801);} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var indexers = i1.GetMembers("this[]"); var p1 = (PropertySymbol)indexers[0]; var p2 = (PropertySymbol)indexers[1]; var p3 = (PropertySymbol)indexers[2]; var p4 = (PropertySymbol)indexers[3]; var p5 = (PropertySymbol)indexers[4]; var p6 = (PropertySymbol)indexers[5]; var p7 = (PropertySymbol)indexers[6]; var p8 = (PropertySymbol)indexers[7]; var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); string name = m is PEModuleSymbol ? "Item" : "this"; Assert.Equal("System.Int32 Test.I1." + name + "[System.SByte i] { get; }", derived.FindImplementationForInterfaceMember(p1).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1." + name + "[System.Byte i] { get; }", derived.FindImplementationForInterfaceMember(p2).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1." + name + "[System.Int16 i] { get; }", derived.FindImplementationForInterfaceMember(p3).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1." + name + "[System.UInt16 i] { get; }", derived.FindImplementationForInterfaceMember(p4).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1." + name + "[System.Int32 i] { set; }", derived.FindImplementationForInterfaceMember(p5).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1." + name + "[System.UInt32 i] { set; }", derived.FindImplementationForInterfaceMember(p6).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1." + name + "[System.Int64 i] { get; set; }", derived.FindImplementationForInterfaceMember(p7).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1." + name + "[System.UInt64 i] { get; set; }", derived.FindImplementationForInterfaceMember(p8).ToTestDisplayString()); if (m is PEModuleSymbol) { Assert.Equal("System.Int32 Test.I1.get_Item(System.SByte i)", derived.FindImplementationForInterfaceMember(p1.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.get_Item(System.Byte i)", derived.FindImplementationForInterfaceMember(p2.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.get_Item(System.Int16 i)", derived.FindImplementationForInterfaceMember(p3.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.get_Item(System.UInt16 i)", derived.FindImplementationForInterfaceMember(p4.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.set_Item(System.Int32 i, System.Int32 value)", derived.FindImplementationForInterfaceMember(p5.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.set_Item(System.UInt32 i, System.Int32 value)", derived.FindImplementationForInterfaceMember(p6.SetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.get_Item(System.Int64 i)", derived.FindImplementationForInterfaceMember(p7.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.get_Item(System.UInt64 i)", derived.FindImplementationForInterfaceMember(p8.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.set_Item(System.Int64 i, System.Int32 value)", derived.FindImplementationForInterfaceMember(p7.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.set_Item(System.UInt64 i, System.Int32 value)", derived.FindImplementationForInterfaceMember(p8.SetMethod).ToTestDisplayString()); } else { Assert.Equal("System.Int32 Test.I1.this[System.SByte i].get", derived.FindImplementationForInterfaceMember(p1.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.this[System.Byte i].get", derived.FindImplementationForInterfaceMember(p2.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.this[System.Int16 i].get", derived.FindImplementationForInterfaceMember(p3.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.this[System.UInt16 i].get", derived.FindImplementationForInterfaceMember(p4.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.this[System.Int32 i].set", derived.FindImplementationForInterfaceMember(p5.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.this[System.UInt32 i].set", derived.FindImplementationForInterfaceMember(p6.SetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.this[System.Int64 i].get", derived.FindImplementationForInterfaceMember(p7.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.I1.this[System.UInt64 i].get", derived.FindImplementationForInterfaceMember(p8.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.this[System.Int64 i].set", derived.FindImplementationForInterfaceMember(p7.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.this[System.UInt64 i].set", derived.FindImplementationForInterfaceMember(p8.SetMethod).ToTestDisplayString()); } } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"100 200 300 400 500 600 700 701 800 801 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void IndexerImplementation_204() { var source1 = @" interface I1 { int this[sbyte i] => 1; int this[byte i] => 2; int this[short i] { get => 3; } int this[ushort i] { get => 4; } int this[int i] { set => System.Console.WriteLine(5); } int this[uint i] { set => System.Console.WriteLine(6); } int this[long i] { get { return 7;} set {} } int this[ulong i] { get { return 8;} set {} } } class Base : Test { new int this[sbyte i] => 10; new int this[short i] { get => 30; } new int this[int i] { set => System.Console.WriteLine(50); } new int this[long i] { get { return 70;} set {} } } class Derived : Base, I1 { new int this[byte i] => 20; new int this[ushort i] { get => 40; } new int this[uint i] { set => System.Console.WriteLine(60); } new int this[ulong i] { get { return 80;} set {} } static void Main() { I1 i1 = new Derived(); System.Console.WriteLine(i1[(sbyte)0]); System.Console.WriteLine(i1[(byte)0]); System.Console.WriteLine(i1[(short)0]); System.Console.WriteLine(i1[(ushort)0]); i1[(int)0] = 0; i1[(uint)0] = 0; System.Console.WriteLine(i1[(long)0]); i1[(long)0] = 0; System.Console.WriteLine(i1[(ulong)0]); i1[(ulong)0] = 0; } } class Test : I1 { public int this[sbyte i] => 100; public int this[byte i] => 200; public int this[short i] { get => 300; } public int this[ushort i] { get => 400; } public int this[int i] { set => System.Console.WriteLine(500); } public int this[uint i] { set => System.Console.WriteLine(600); } public int this[long i] { get { return 700;} set {System.Console.WriteLine(701);} } public int this[ulong i] { get { return 800;} set {System.Console.WriteLine(801);} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var indexers = i1.GetMembers("this[]"); var p1 = (PropertySymbol)indexers[0]; var p2 = (PropertySymbol)indexers[1]; var p3 = (PropertySymbol)indexers[2]; var p4 = (PropertySymbol)indexers[3]; var p5 = (PropertySymbol)indexers[4]; var p6 = (PropertySymbol)indexers[5]; var p7 = (PropertySymbol)indexers[6]; var p8 = (PropertySymbol)indexers[7]; var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Equal("System.Int32 Test.this[System.SByte i] { get; }", derived.FindImplementationForInterfaceMember(p1).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.Byte i] { get; }", derived.FindImplementationForInterfaceMember(p2).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.Int16 i] { get; }", derived.FindImplementationForInterfaceMember(p3).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.UInt16 i] { get; }", derived.FindImplementationForInterfaceMember(p4).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.Int32 i] { set; }", derived.FindImplementationForInterfaceMember(p5).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.UInt32 i] { set; }", derived.FindImplementationForInterfaceMember(p6).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.Int64 i] { get; set; }", derived.FindImplementationForInterfaceMember(p7).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.UInt64 i] { get; set; }", derived.FindImplementationForInterfaceMember(p8).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.SByte i].get", derived.FindImplementationForInterfaceMember(p1.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.Byte i].get", derived.FindImplementationForInterfaceMember(p2.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.Int16 i].get", derived.FindImplementationForInterfaceMember(p3.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.UInt16 i].get", derived.FindImplementationForInterfaceMember(p4.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.this[System.Int32 i].set", derived.FindImplementationForInterfaceMember(p5.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.this[System.UInt32 i].set", derived.FindImplementationForInterfaceMember(p6.SetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.Int64 i].get", derived.FindImplementationForInterfaceMember(p7.GetMethod).ToTestDisplayString()); Assert.Equal("System.Int32 Test.this[System.UInt64 i].get", derived.FindImplementationForInterfaceMember(p8.GetMethod).ToTestDisplayString()); Assert.Equal("void Test.this[System.Int64 i].set", derived.FindImplementationForInterfaceMember(p7.SetMethod).ToTestDisplayString()); Assert.Equal("void Test.this[System.UInt64 i].set", derived.FindImplementationForInterfaceMember(p8.SetMethod).ToTestDisplayString()); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"100 200 300 400 500 600 700 701 800 801 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void IndexerImplementation_501() { var source1 = @" public interface I1 { int this[sbyte i] => 1; int this[short i] { get => 3; } int this[int i] { set => System.Console.WriteLine(5); } int this[long i] { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,26): error CS8501: Target runtime doesn't support default interface implementation. // int this[sbyte i] => 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "1").WithLocation(4, 26), // (6,7): error CS8501: Target runtime doesn't support default interface implementation. // { get => 3; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(6, 7), // (8,7): error CS8501: Target runtime doesn't support default interface implementation. // { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(8, 7), // (11,9): error CS8501: Target runtime doesn't support default interface implementation. // get { return 7;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(11, 9), // (12,9): error CS8501: Target runtime doesn't support default interface implementation. // set {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(12, 9) ); ValidateIndexerImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.this[long].set' cannot implement interface member 'I1.this[long].set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].set", "I1.this[long].set", "Test2"), // (2,15): error CS8502: 'I1.this[sbyte].get' cannot implement interface member 'I1.this[sbyte].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[sbyte].get", "I1.this[sbyte].get", "Test2"), // (2,15): error CS8502: 'I1.this[short].get' cannot implement interface member 'I1.this[short].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[short].get", "I1.this[short].get", "Test2"), // (2,15): error CS8502: 'I1.this[int].set' cannot implement interface member 'I1.this[int].set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[int].set", "I1.this[int].set", "Test2"), // (2,15): error CS8502: 'I1.this[long].get' cannot implement interface member 'I1.this[long].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].get", "I1.this[long].get", "Test2") ); ValidateIndexerImplementation_501(compilation3.SourceModule, "Test2"); } private static void ValidateIndexerImplementation_501(ModuleSymbol m, string typeName) { var derived = m.GlobalNamespace.GetTypeMember(typeName); var i1 = derived.InterfacesNoUseSiteDiagnostics().Single(); Assert.Equal("I1", i1.ToTestDisplayString()); var indexers = i1.GetMembers("this[]"); var p1 = (PropertySymbol)indexers[0]; var p3 = (PropertySymbol)indexers[1]; var p5 = (PropertySymbol)indexers[2]; var p7 = (PropertySymbol)indexers[3]; Assert.True(p1.IsVirtual); Assert.True(p3.IsVirtual); Assert.True(p5.IsVirtual); Assert.True(p7.IsVirtual); Assert.False(p1.IsAbstract); Assert.False(p3.IsAbstract); Assert.False(p5.IsAbstract); Assert.False(p7.IsAbstract); Assert.Same(p1, derived.FindImplementationForInterfaceMember(p1)); Assert.Same(p3, derived.FindImplementationForInterfaceMember(p3)); Assert.Same(p5, derived.FindImplementationForInterfaceMember(p5)); Assert.Same(p7, derived.FindImplementationForInterfaceMember(p7)); Assert.True(p1.GetMethod.IsVirtual); Assert.True(p3.GetMethod.IsVirtual); Assert.True(p5.SetMethod.IsVirtual); Assert.True(p7.GetMethod.IsVirtual); Assert.True(p7.SetMethod.IsVirtual); Assert.True(p1.GetMethod.IsMetadataVirtual()); Assert.True(p3.GetMethod.IsMetadataVirtual()); Assert.True(p5.SetMethod.IsMetadataVirtual()); Assert.True(p7.GetMethod.IsMetadataVirtual()); Assert.True(p7.SetMethod.IsMetadataVirtual()); Assert.False(p1.GetMethod.IsAbstract); Assert.False(p3.GetMethod.IsAbstract); Assert.False(p5.SetMethod.IsAbstract); Assert.False(p7.GetMethod.IsAbstract); Assert.False(p7.SetMethod.IsAbstract); Assert.Same(p1.GetMethod, derived.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Same(p3.GetMethod, derived.FindImplementationForInterfaceMember(p3.GetMethod)); Assert.Same(p5.SetMethod, derived.FindImplementationForInterfaceMember(p5.SetMethod)); Assert.Same(p7.GetMethod, derived.FindImplementationForInterfaceMember(p7.GetMethod)); Assert.Same(p7.SetMethod, derived.FindImplementationForInterfaceMember(p7.SetMethod)); } [Fact] public void IndexerImplementation_502() { var source1 = @" public interface I1 { int this[sbyte i] => 1; int this[short i] { get => 3; } int this[int i] { set => System.Console.WriteLine(5); } int this[long i] { get { return 7;} set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.this[short].get' cannot implement interface member 'I1.this[short].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[short].get", "I1.this[short].get", "Test2"), // (2,15): error CS8502: 'I1.this[int].set' cannot implement interface member 'I1.this[int].set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[int].set", "I1.this[int].set", "Test2"), // (2,15): error CS8502: 'I1.this[long].get' cannot implement interface member 'I1.this[long].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].get", "I1.this[long].get", "Test2"), // (2,15): error CS8502: 'I1.this[long].set' cannot implement interface member 'I1.this[long].set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].set", "I1.this[long].set", "Test2"), // (2,15): error CS8502: 'I1.this[sbyte].get' cannot implement interface member 'I1.this[sbyte].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[sbyte].get", "I1.this[sbyte].get", "Test2") ); ValidateIndexerImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void IndexerImplementation_503() { var source1 = @" public interface I1 { int this[sbyte i] => 1; int this[short i] { get => 3; } int this[int i] { set => System.Console.WriteLine(5); } int this[long i] { get { return 7;} set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" public interface I2 { void M2(); } class Test2 : I2 { public void M2() {} } "; var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var test2 = compilation3.GetTypeByMetadataName("Test2"); var i1 = compilation3.GetTypeByMetadataName("I1"); Assert.Equal("I1", i1.ToTestDisplayString()); var indexers = i1.GetMembers("this[]"); var p1 = (PropertySymbol)indexers[0]; var p3 = (PropertySymbol)indexers[1]; var p5 = (PropertySymbol)indexers[2]; var p7 = (PropertySymbol)indexers[3]; Assert.Null(test2.FindImplementationForInterfaceMember(p1)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p5)); Assert.Null(test2.FindImplementationForInterfaceMember(p7)); Assert.Null(test2.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p3.GetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p5.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p7.GetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p7.SetMethod)); compilation3.VerifyDiagnostics(); } [Fact] public void IndexerImplementation_601() { var source1 = @" public interface I1 { int this[sbyte i] => 1; int this[short i] { get => 3; } int this[int i] { set => System.Console.WriteLine(5); } int this[long i] { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,26): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int this[sbyte i] => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1").WithArguments("default interface implementation", "8.0").WithLocation(4, 26), // (4,26): error CS8701: Target runtime doesn't support default interface implementation. // int this[sbyte i] => 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "1").WithLocation(4, 26), // (6,7): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // { get => 3; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(6, 7), // (6,7): error CS8701: Target runtime doesn't support default interface implementation. // { get => 3; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(6, 7), // (8,7): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(8, 7), // (8,7): error CS8701: Target runtime doesn't support default interface implementation. // { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(8, 7), // (11,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // get { return 7;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(11, 9), // (11,9): error CS8701: Target runtime doesn't support default interface implementation. // get { return 7;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(11, 9), // (12,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // set {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(12, 9), // (12,9): error CS8701: Target runtime doesn't support default interface implementation. // set {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(12, 9) ); ValidateIndexerImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.this[long].set' cannot implement interface member 'I1.this[long].set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].set", "I1.this[long].set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.this[long].set' cannot implement interface member 'I1.this[long].set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].set", "I1.this[long].set", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[sbyte].get' cannot implement interface member 'I1.this[sbyte].get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[sbyte].get", "I1.this[sbyte].get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.this[sbyte].get' cannot implement interface member 'I1.this[sbyte].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[sbyte].get", "I1.this[sbyte].get", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[short].get' cannot implement interface member 'I1.this[short].get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[short].get", "I1.this[short].get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.this[short].get' cannot implement interface member 'I1.this[short].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[short].get", "I1.this[short].get", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[int].set' cannot implement interface member 'I1.this[int].set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[int].set", "I1.this[int].set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.this[int].set' cannot implement interface member 'I1.this[int].set' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[int].set", "I1.this[int].set", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[long].get' cannot implement interface member 'I1.this[long].get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].get", "I1.this[long].get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.this[long].get' cannot implement interface member 'I1.this[long].get' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].get", "I1.this[long].get", "Test2").WithLocation(2, 15) ); ValidateIndexerImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void IndexerImplementation_701() { var source1 = @" public interface I1 { int this[sbyte i] => 1; int this[short i] { get => 3; } int this[int i] { set => System.Console.WriteLine(5); } int this[long i] { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,26): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int this[sbyte i] => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1").WithArguments("default interface implementation", "8.0").WithLocation(4, 26), // (6,7): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // { get => 3; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(6, 7), // (8,7): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(8, 7), // (11,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // get { return 7;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(11, 9), // (12,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // set {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(12, 9) ); ValidateIndexerImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateIndexerImplementation_501(compilation2.SourceModule, "Test2"); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test2Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test2"); Assert.Equal("I1", test2Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidateIndexerImplementation_501(m, "Test2"); }); var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.this[long].set' cannot implement interface member 'I1.this[long].set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].set", "I1.this[long].set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[sbyte].get' cannot implement interface member 'I1.this[sbyte].get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[sbyte].get", "I1.this[sbyte].get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[short].get' cannot implement interface member 'I1.this[short].get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[short].get", "I1.this[short].get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[int].set' cannot implement interface member 'I1.this[int].set' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[int].set", "I1.this[int].set", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.this[long].get' cannot implement interface member 'I1.this[long].get' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.this[long].get", "I1.this[long].get", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15) ); ValidateIndexerImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void IndexerImplementation_901() { var source1 = @" public interface I1 { static int this[sbyte i] => 1; static int this[short i] { get => 3; } static int this[int i] { set => System.Console.WriteLine(5); } static int this[long i] { get { return 7;} set {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,16): error CS0106: The modifier 'static' is not valid for this item // static int this[sbyte i] => 1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(4, 16), // (4,33): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static int this[sbyte i] => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1").WithArguments("default interface implementation", "8.0").WithLocation(4, 33), // (5,16): error CS0106: The modifier 'static' is not valid for this item // static int this[short i] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(5, 16), // (6,7): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // { get => 3; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(6, 7), // (7,16): error CS0106: The modifier 'static' is not valid for this item // static int this[int i] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(7, 16), // (8,7): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // { set => System.Console.WriteLine(5); } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(8, 7), // (9,16): error CS0106: The modifier 'static' is not valid for this item // static int this[long i] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(9, 16), // (11,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // get { return 7;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(11, 9), // (12,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // set {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(12, 9) ); ValidateIndexerImplementation_501(compilation1.SourceModule, "Test1"); } [Fact] public void EventImplementation_101() { var source1 = @" public interface I1 { event System.Action E1 { add { System.Console.WriteLine(""add E1""); } } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (4,25): error CS0065: 'I1.E1': event property must have both add and remove accessors // event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 25) }, haveAdd: true, haveRemove: false); } private void ValidateEventImplementation_101(string source1, DiagnosticDescription[] expected, bool haveAdd, bool haveRemove) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics(expected); ValidateEventImplementationTest1_101(compilation1.SourceModule, haveAdd, haveRemove); var source2 = @" class Test2 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate2(ModuleSymbol m) { ValidateEventImplementationTest2_101(m, haveAdd, haveRemove); } Validate2(compilation2.SourceModule); compilation2.VerifyDiagnostics(); Assert.NotEmpty(expected); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); } private static void ValidateEventImplementationTest1_101(ModuleSymbol m, bool haveAdd, bool haveRemove) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var e1 = i1.GetMember<EventSymbol>("E1"); var addE1 = e1.AddMethod; var rmvE1 = e1.RemoveMethod; if (haveAdd) { ValidateAccessor(addE1); } else { Assert.Null(addE1); } if (haveRemove) { ValidateAccessor(rmvE1); } else { Assert.Null(rmvE1); } void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } Assert.False(e1.IsAbstract); Assert.True(e1.IsVirtual); Assert.False(e1.IsSealed); Assert.False(e1.IsStatic); Assert.False(e1.IsExtern); Assert.False(e1.IsOverride); Assert.Equal(Accessibility.Public, e1.DeclaredAccessibility); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); if (m is PEModuleSymbol peModule) { int rva; if (haveAdd) { peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)addE1).Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); } if (haveRemove) { peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)rmvE1).Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); } } var test1 = m.GlobalNamespace.GetTypeMember("Test1"); Assert.Equal("I1", test1.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Assert.Same(e1, test1.FindImplementationForInterfaceMember(e1)); if (haveAdd) { Assert.Same(addE1, test1.FindImplementationForInterfaceMember(addE1)); } if (haveRemove) { Assert.Same(rmvE1, test1.FindImplementationForInterfaceMember(rmvE1)); } } private static void ValidateEventImplementationTest2_101(ModuleSymbol m, bool haveAdd, bool haveRemove) { var test2 = m.GlobalNamespace.GetTypeMember("Test2"); Assert.Equal("I1", test2.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); var e1 = test2.InterfacesNoUseSiteDiagnostics().Single().GetMember<EventSymbol>("E1"); Assert.Same(e1, test2.FindImplementationForInterfaceMember(e1)); if (haveAdd) { var addP1 = e1.AddMethod; Assert.Same(addP1, test2.FindImplementationForInterfaceMember(addP1)); } if (haveRemove) { var rmvP1 = e1.RemoveMethod; Assert.Same(rmvP1, test2.FindImplementationForInterfaceMember(rmvP1)); } } [Fact] public void EventImplementation_102() { var source1 = @" public interface I1 { event System.Action E1 { add => System.Console.WriteLine(""add E1""); remove => System.Console.WriteLine(""remove E1""); } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.E1 += null; i1.E1 -= null; } } "; ValidateEventImplementation_102(source1); } private void ValidateEventImplementation_102(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { ValidateEventImplementationTest1_101(m, haveAdd: true, haveRemove: true); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"add E1 remove E1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { I1 i1 = new Test2(); i1.E1 += null; i1.E1 -= null; } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate2(ModuleSymbol m) { ValidateEventImplementationTest2_101(m, haveAdd: true, haveRemove: true); } Validate2(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"add E1 remove E1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate2(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"add E1 remove E1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); } [Fact] public void EventImplementation_103() { var source1 = @" public interface I1 { event System.Action E1 { remove { System.Console.WriteLine(""remove E1""); } } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (4,25): error CS0065: 'I1.E1': event property must have both add and remove accessors // event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 25) }, haveAdd: false, haveRemove: true); } [Fact] public void EventImplementation_104() { var source1 = @" public interface I1 { event System.Action E1 { add; } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (6,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 12), // (4,25): error CS0065: 'I1.E1': event property must have both add and remove accessors // event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 25) }, haveAdd: true, haveRemove: false); } [Fact] public void EventImplementation_105() { var source1 = @" public interface I1 { event System.Action E1 { remove; } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (6,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 15), // (4,25): error CS0065: 'I1.E1': event property must have both add and remove accessors // event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 25) }, haveAdd: false, haveRemove: true); } [Fact] public void EventImplementation_106() { var source1 = @" public interface I1 { event System.Action E1 { } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (4,25): error CS0065: 'I1.E1': event property must have both add and remove accessors // event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 25) }, haveAdd: false, haveRemove: false); } [Fact] public void EventImplementation_107() { var source1 = @" public interface I1 { event System.Action E1 { add; remove; } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (6,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 12), // (7,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(7, 15) }, haveAdd: true, haveRemove: true); } [Fact] public void EventImplementation_108() { var source1 = @" public interface I1 { event System.Action E1 { get; set; } => 0; } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (8,7): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration // } => 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(8, 7), // (6,9): error CS1055: An add or remove accessor expected // get; Diagnostic(ErrorCode.ERR_AddOrRemoveExpected, "get").WithLocation(6, 9), // (7,9): error CS1055: An add or remove accessor expected // set; Diagnostic(ErrorCode.ERR_AddOrRemoveExpected, "set").WithLocation(7, 9), // (4,25): error CS0065: 'I1.E1': event property must have both add and remove accessors // event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1") }, haveAdd: false, haveRemove: false); } [Fact] public void EventImplementation_109() { var source1 = @" public interface I1 { event System.Action E1 { add => throw null; remove; } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (7,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(7, 15) }, haveAdd: true, haveRemove: true); } [Fact] public void EventImplementation_110() { var source1 = @" public interface I1 { event System.Action E1 { add; remove => throw null; } } class Test1 : I1 {} "; ValidateEventImplementation_101(source1, new[] { // (6,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 12) }, haveAdd: true, haveRemove: true); } [Fact] public void EventImplementation_201() { var source1 = @" interface I1 { event System.Action E7 { add {System.Console.WriteLine(""add E7"");} remove {System.Console.WriteLine(""remove E7"");} } event System.Action E8 { add {System.Console.WriteLine(""add E8"");} remove {System.Console.WriteLine(""remove E8"");} } } class Base { event System.Action E7; } class Derived : Base, I1 { event System.Action E8 { add {} remove {} } static void Main() { I1 i1 = new Derived(); i1.E7 += null; i1.E7 -= null; i1.E8 += null; i1.E8 -= null; } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (10,25): warning CS0067: The event 'Base.E7' is never used // event System.Action E7; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E7").WithArguments("Base.E7").WithLocation(10, 25) ); ValidateEventImplementation_201(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"add E7 remove E7 add E8 remove E8", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidateEventImplementation_201(m); }); } private static void ValidateEventImplementation_201(ModuleSymbol m) { var e7 = m.GlobalNamespace.GetMember<EventSymbol>("I1.E7"); var e8 = m.GlobalNamespace.GetMember<EventSymbol>("I1.E8"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Same(e7, derived.FindImplementationForInterfaceMember(e7)); Assert.Same(e8, derived.FindImplementationForInterfaceMember(e8)); Assert.Same(e7.AddMethod, derived.FindImplementationForInterfaceMember(e7.AddMethod)); Assert.Same(e8.AddMethod, derived.FindImplementationForInterfaceMember(e8.AddMethod)); Assert.Same(e7.RemoveMethod, derived.FindImplementationForInterfaceMember(e7.RemoveMethod)); Assert.Same(e8.RemoveMethod, derived.FindImplementationForInterfaceMember(e8.RemoveMethod)); } [Fact] public void EventImplementation_202() { var source1 = @" interface I1 { event System.Action E7 { add {System.Console.WriteLine(""add E7"");} remove {System.Console.WriteLine(""remove E7"");} } event System.Action E8 { add {System.Console.WriteLine(""add E8"");} remove {System.Console.WriteLine(""remove E8"");} } } class Base : Test { event System.Action E7; } class Derived : Base, I1 { event System.Action E8 { add {} remove {} } static void Main() { I1 i1 = new Derived(); i1.E7 += null; i1.E7 -= null; i1.E8 += null; i1.E8 -= null; } } class Test : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (10,25): warning CS0067: The event 'Base.E7' is never used // event System.Action E7; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E7").WithArguments("Base.E7").WithLocation(10, 25) ); ValidateEventImplementation_201(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"add E7 remove E7 add E8 remove E8", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidateEventImplementation_201(m); }); } [Fact] public void EventImplementation_203() { var source1 = @" interface I1 { event System.Action E7 { add {} remove {} } event System.Action E8 { add {} remove {} } } class Base : Test { event System.Action E7; } class Derived : Base, I1 { event System.Action E8 { add {} remove {} } static void Main() { I1 i1 = new Derived(); i1.E7 += null; i1.E7 -= null; i1.E8 += null; i1.E8 -= null; } } class Test : I1 { event System.Action I1.E7 { add {System.Console.WriteLine(""add E7"");} remove {System.Console.WriteLine(""remove E7"");} } event System.Action I1.E8 { add {System.Console.WriteLine(""add E8"");} remove {System.Console.WriteLine(""remove E8"");} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (10,25): warning CS0067: The event 'Base.E7' is never used // event System.Action E7; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E7").WithArguments("Base.E7").WithLocation(10, 25) ); void Validate(ModuleSymbol m) { var e7 = m.GlobalNamespace.GetMember<EventSymbol>("I1.E7"); var e8 = m.GlobalNamespace.GetMember<EventSymbol>("I1.E8"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Equal("event System.Action Test.I1.E7", derived.FindImplementationForInterfaceMember(e7).ToTestDisplayString()); Assert.Equal("event System.Action Test.I1.E8", derived.FindImplementationForInterfaceMember(e8).ToTestDisplayString()); Assert.Equal("void Test.I1.E7.add", derived.FindImplementationForInterfaceMember(e7.AddMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.E8.add", derived.FindImplementationForInterfaceMember(e8.AddMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.E7.remove", derived.FindImplementationForInterfaceMember(e7.RemoveMethod).ToTestDisplayString()); Assert.Equal("void Test.I1.E8.remove", derived.FindImplementationForInterfaceMember(e8.RemoveMethod).ToTestDisplayString()); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"add E7 remove E7 add E8 remove E8", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void EventImplementation_204() { var source1 = @" interface I1 { event System.Action E7 { add {} remove {} } event System.Action E8 { add {} remove {} } } class Base : Test { new event System.Action E7; } class Derived : Base, I1 { new event System.Action E8 { add {} remove {} } static void Main() { I1 i1 = new Derived(); i1.E7 += null; i1.E7 -= null; i1.E8 += null; i1.E8 -= null; } } class Test : I1 { public event System.Action E7 { add {System.Console.WriteLine(""add E7"");} remove {System.Console.WriteLine(""remove E7"");} } public event System.Action E8 { add {System.Console.WriteLine(""add E8"");} remove {System.Console.WriteLine(""remove E8"");} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (10,29): warning CS0067: The event 'Base.E7' is never used // new event System.Action E7; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E7").WithArguments("Base.E7").WithLocation(10, 29) ); void Validate(ModuleSymbol m) { var e7 = m.GlobalNamespace.GetMember<EventSymbol>("I1.E7"); var e8 = m.GlobalNamespace.GetMember<EventSymbol>("I1.E8"); var derived = m.ContainingAssembly.GetTypeByMetadataName("Derived"); Assert.Equal("event System.Action Test.E7", derived.FindImplementationForInterfaceMember(e7).ToTestDisplayString()); Assert.Equal("event System.Action Test.E8", derived.FindImplementationForInterfaceMember(e8).ToTestDisplayString()); Assert.Equal("void Test.E7.add", derived.FindImplementationForInterfaceMember(e7.AddMethod).ToTestDisplayString()); Assert.Equal("void Test.E8.add", derived.FindImplementationForInterfaceMember(e8.AddMethod).ToTestDisplayString()); Assert.Equal("void Test.E7.remove", derived.FindImplementationForInterfaceMember(e7.RemoveMethod).ToTestDisplayString()); Assert.Equal("void Test.E8.remove", derived.FindImplementationForInterfaceMember(e8.RemoveMethod).ToTestDisplayString()); } Validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"add E7 remove E7 add E8 remove E8", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var derivedResult = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Derived"); Assert.Equal("I1", derivedResult.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); Validate(m); }); } [Fact] public void EventImplementation_501() { var source1 = @" public interface I1 { event System.Action E7 { add {} remove {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (6,9): error CS8501: Target runtime doesn't support default interface implementation. // add {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(6, 9), // (7,9): error CS8501: Target runtime doesn't support default interface implementation. // remove {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(7, 9) ); ValidateEventImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.E7.remove' cannot implement interface member 'I1.E7.remove' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.remove", "I1.E7.remove", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.E7.add' cannot implement interface member 'I1.E7.add' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.add", "I1.E7.add", "Test2").WithLocation(2, 15) ); ValidateEventImplementation_501(compilation3.SourceModule, "Test2"); } private static void ValidateEventImplementation_501(ModuleSymbol m, string typeName) { var derived = m.GlobalNamespace.GetTypeMember(typeName); var i1 = derived.InterfacesNoUseSiteDiagnostics().Single(); Assert.Equal("I1", i1.ToTestDisplayString()); var e7 = i1.GetMember<EventSymbol>("E7"); Assert.True(e7.IsVirtual); Assert.False(e7.IsAbstract); Assert.Same(e7, derived.FindImplementationForInterfaceMember(e7)); Assert.True(e7.AddMethod.IsVirtual); Assert.True(e7.RemoveMethod.IsVirtual); Assert.True(e7.AddMethod.IsMetadataVirtual()); Assert.True(e7.RemoveMethod.IsMetadataVirtual()); Assert.False(e7.AddMethod.IsAbstract); Assert.False(e7.RemoveMethod.IsAbstract); Assert.Same(e7.AddMethod, derived.FindImplementationForInterfaceMember(e7.AddMethod)); Assert.Same(e7.RemoveMethod, derived.FindImplementationForInterfaceMember(e7.RemoveMethod)); } [Fact] public void EventImplementation_502() { var source1 = @" public interface I1 { event System.Action E7 { add {} remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, targetFramework: TargetFramework.DesktopLatestExtended, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8502: 'I1.E7.remove' cannot implement interface member 'I1.E7.remove' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.remove", "I1.E7.remove", "Test2").WithLocation(2, 15), // (2,15): error CS8502: 'I1.E7.add' cannot implement interface member 'I1.E7.add' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.add", "I1.E7.add", "Test2").WithLocation(2, 15) ); ValidateEventImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void EventImplementation_503() { var source1 = @" public interface I1 { event System.Action E7 { add {} remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" public interface I2 { void M2(); } class Test2 : I2 { public void M2() {} } "; var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var test2 = compilation3.GetTypeByMetadataName("Test2"); var i1 = compilation3.GetTypeByMetadataName("I1"); Assert.Equal("I1", i1.ToTestDisplayString()); var e7 = i1.GetMember<EventSymbol>("E7"); Assert.Null(test2.FindImplementationForInterfaceMember(e7)); Assert.Null(test2.FindImplementationForInterfaceMember(e7.AddMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(e7.RemoveMethod)); compilation3.VerifyDiagnostics(); } [Fact] public void EventImplementation_601() { var source1 = @" public interface I1 { event System.Action E7 { add {} remove {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (6,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // add {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(6, 9), // (6,9): error CS8701: Target runtime doesn't support default interface implementation. // add {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(6, 9), // (7,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // remove {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(7, 9), // (7,9): error CS8701: Target runtime doesn't support default interface implementation. // remove {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(7, 9) ); ValidateEventImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular7_3); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.E7.remove' cannot implement interface member 'I1.E7.remove' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.remove", "I1.E7.remove", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.E7.remove' cannot implement interface member 'I1.E7.remove' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.remove", "I1.E7.remove", "Test2").WithLocation(2, 15), // (2,15): error CS8506: 'I1.E7.add' cannot implement interface member 'I1.E7.add' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.add", "I1.E7.add", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8502: 'I1.E7.add' cannot implement interface member 'I1.E7.add' in type 'Test2' because the target runtime doesn't support default interface implementation. // class Test2 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.add", "I1.E7.add", "Test2").WithLocation(2, 15) ); ValidateEventImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void EventImplementation_701() { var source1 = @" public interface I1 { event System.Action E7 { add {} remove {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (6,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // add {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(6, 9), // (7,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // remove {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(7, 9) ); ValidateEventImplementation_501(compilation1.SourceModule, "Test1"); var source2 = @" class Test2 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateEventImplementation_501(compilation2.SourceModule, "Test2"); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => { var test2Result = (PENamedTypeSymbol)m.GlobalNamespace.GetTypeMember("Test2"); Assert.Equal("I1", test2Result.InterfacesNoUseSiteDiagnostics().Single().ToTestDisplayString()); ValidateEventImplementation_501(m, "Test2"); }); var compilation3 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8506: 'I1.E7.remove' cannot implement interface member 'I1.E7.remove' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.remove", "I1.E7.remove", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15), // (2,15): error CS8506: 'I1.E7.add' cannot implement interface member 'I1.E7.add' in type 'Test2' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.E7.add", "I1.E7.add", "Test2", "default interface implementation", "7.3", "8.0").WithLocation(2, 15) ); ValidateEventImplementation_501(compilation3.SourceModule, "Test2"); } [Fact] public void EventImplementation_901() { var source1 = @" public interface I1 { static event System.Action E7 { add {} remove {} } } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static event System.Action E7 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "E7").WithArguments("default interface implementation", "8.0").WithLocation(4, 32) ); var derived = compilation1.GlobalNamespace.GetTypeMember("Test1"); var i1 = derived.InterfacesNoUseSiteDiagnostics().Single(); Assert.Equal("I1", i1.ToTestDisplayString()); var e7 = i1.GetMember<EventSymbol>("E7"); Assert.False(e7.IsVirtual); Assert.False(e7.IsAbstract); Assert.True(e7.IsStatic); Assert.Null(derived.FindImplementationForInterfaceMember(e7)); Assert.False(e7.AddMethod.IsVirtual); Assert.False(e7.RemoveMethod.IsVirtual); Assert.False(e7.AddMethod.IsMetadataVirtual()); Assert.False(e7.RemoveMethod.IsMetadataVirtual()); Assert.False(e7.AddMethod.IsAbstract); Assert.False(e7.RemoveMethod.IsAbstract); Assert.True(e7.AddMethod.IsStatic); Assert.True(e7.RemoveMethod.IsStatic); Assert.Null(derived.FindImplementationForInterfaceMember(e7.AddMethod)); Assert.Null(derived.FindImplementationForInterfaceMember(e7.RemoveMethod)); } [Fact] public void BaseIsNotAllowed_01() { var source1 = @" public interface I1 { void M1() { base.GetHashCode(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (6,9): error CS0174: A base class is required for a 'base' reference // base.GetHashCode(); Diagnostic(ErrorCode.ERR_NoBaseClass, "base").WithLocation(6, 9) ); } [Fact] public void ThisIsAllowed_01() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""I1.M1""); } int P1 { get { System.Console.WriteLine(""I1.get_P1""); return 0; } set => System.Console.WriteLine(""I1.set_P1""); } event System.Action E1 { add => System.Console.WriteLine(""I1.add_E1""); remove => System.Console.WriteLine(""I1.remove_E1""); } } public interface I2 : I1 { void M2() { System.Console.WriteLine(""I2.M2""); System.Console.WriteLine(this.GetHashCode()); this.M1(); this.P1 = this.P1; this.E1 += null; this.E1 -= null; this.M3(); this.P3 = this.P3; this.E3 += null; this.E3 -= null; } int P2 { get { System.Console.WriteLine(""I2.get_P2""); System.Console.WriteLine(this.GetHashCode()); this.M1(); this.P1 = this.P1; this.E1 += null; this.E1 -= null; this.M3(); this.P3 = this.P3; this.E3 += null; this.E3 -= null; return 0; } set { System.Console.WriteLine(""I2.set_P2""); System.Console.WriteLine(this.GetHashCode()); this.M1(); this.P1 = this.P1; this.E1 += null; this.E1 -= null; this.M3(); this.P3 = this.P3; this.E3 += null; this.E3 -= null; } } event System.Action E2 { add { System.Console.WriteLine(""I2.add_E2""); System.Console.WriteLine(this.GetHashCode()); this.M1(); this.P1 = this.P1; this.E1 += null; this.E1 -= null; this.M3(); this.P3 = this.P3; this.E3 += null; this.E3 -= null; } remove { System.Console.WriteLine(""I2.remove_E2""); System.Console.WriteLine(this.GetHashCode()); this.M1(); this.P1 = this.P1; this.E1 += null; this.E1 -= null; this.M3(); this.P3 = this.P3; this.E3 += null; this.E3 -= null; } } void M3() { System.Console.WriteLine(""I2.M3""); } int P3 { get { System.Console.WriteLine(""I2.get_P3""); return 0; } set => System.Console.WriteLine(""I2.set_P3""); } event System.Action E3 { add => System.Console.WriteLine(""I2.add_E3""); remove => System.Console.WriteLine(""I2.remove_E3""); } } class Test1 : I2 { static void Main() { I2 x = new Test1(); x.M2(); x.P2 = x.P2; x.E2 += null; x.E2 -= null; } public override int GetHashCode() { return 123; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.get_P2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.set_P2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.add_E2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.remove_E2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 ", verify: VerifyOnMonoOrCoreClr); } [Fact] public void ThisIsAllowed_02() { var source1 = @" public interface I1 { public int F1; } public interface I2 : I1 { void M2() { this.F1 = this.F2; } int P2 { get { this.F1 = this.F2; return 0; } set { this.F1 = this.F2; } } event System.Action E2 { add { this.F1 = this.F2; } remove { this.F1 = this.F2; } } public int F2; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,16): error CS0525: Interfaces cannot contain fields // public int F1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F1").WithLocation(4, 16), // (39,16): error CS0525: Interfaces cannot contain fields // public int F2; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F2").WithLocation(39, 16) ); } [Fact] public void ImplicitThisIsAllowed_01() { var source1 = @" public interface I1 { void M1() { System.Console.WriteLine(""I1.M1""); } int P1 { get { System.Console.WriteLine(""I1.get_P1""); return 0; } set => System.Console.WriteLine(""I1.set_P1""); } event System.Action E1 { add => System.Console.WriteLine(""I1.add_E1""); remove => System.Console.WriteLine(""I1.remove_E1""); } } public interface I2 : I1 { void M2() { System.Console.WriteLine(""I2.M2""); System.Console.WriteLine(GetHashCode()); M1(); P1 = P1; E1 += null; E1 -= null; M3(); P3 = P3; E3 += null; E3 -= null; } int P2 { get { System.Console.WriteLine(""I2.get_P2""); System.Console.WriteLine(GetHashCode()); M1(); P1 = P1; E1 += null; E1 -= null; M3(); P3 = P3; E3 += null; E3 -= null; return 0; } set { System.Console.WriteLine(""I2.set_P2""); System.Console.WriteLine(GetHashCode()); M1(); P1 = P1; E1 += null; E1 -= null; M3(); P3 = P3; E3 += null; E3 -= null; } } event System.Action E2 { add { System.Console.WriteLine(""I2.add_E2""); System.Console.WriteLine(GetHashCode()); M1(); P1 = P1; E1 += null; E1 -= null; M3(); P3 = P3; E3 += null; E3 -= null; } remove { System.Console.WriteLine(""I2.remove_E2""); System.Console.WriteLine(GetHashCode()); M1(); P1 = P1; E1 += null; E1 -= null; M3(); P3 = P3; E3 += null; E3 -= null; } } void M3() { System.Console.WriteLine(""I2.M3""); } int P3 { get { System.Console.WriteLine(""I2.get_P3""); return 0; } set => System.Console.WriteLine(""I2.set_P3""); } event System.Action E3 { add => System.Console.WriteLine(""I2.add_E3""); remove => System.Console.WriteLine(""I2.remove_E3""); } } class Test1 : I2 { static void Main() { I2 x = new Test1(); x.M2(); x.P2 = x.P2; x.E2 += null; x.E2 -= null; } public override int GetHashCode() { return 123; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.get_P2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.set_P2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.add_E2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 I2.remove_E2 123 I1.M1 I1.get_P1 I1.set_P1 I1.add_E1 I1.remove_E1 I2.M3 I2.get_P3 I2.set_P3 I2.add_E3 I2.remove_E3 ", verify: VerifyOnMonoOrCoreClr); } [Fact] public void ImplicitThisIsAllowed_02() { var source1 = @" public interface I1 { public int F1; } public interface I2 : I1 { void M2() { F1 = F2; } int P2 { get { F1 = F2; return 0; } set { F1 = F2; } } event System.Action E2 { add { F1 = F2; } remove { F1 = F2; } } public int F2; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,16): error CS0525: Interfaces cannot contain fields // public int F1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F1").WithLocation(4, 16), // (39,16): error CS0525: Interfaces cannot contain fields // public int F2; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F2").WithLocation(39, 16) ); } [Fact] public void MethodModifiers_01() { var source1 = @" public interface I1 { public void M01(); protected void M02(); protected internal void M03(); internal void M04(); private void M05(); static void M06(); virtual void M07(); sealed void M08(); override void M09(); abstract void M10(); extern void M11(); async void M12(); private protected void M13(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (12,19): error CS0106: The modifier 'override' is not valid for this item // override void M09(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(12, 19), // (15,16): error CS1994: The 'async' modifier can only be used in methods that have a body. // async void M12(); Diagnostic(ErrorCode.ERR_BadAsyncLacksBody, "M12").WithLocation(15, 16), // (8,18): error CS0501: 'I1.M05()' must declare a body because it is not marked abstract, extern, or partial // private void M05(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M05").WithArguments("I1.M05()").WithLocation(8, 18), // (9,17): error CS0501: 'I1.M06()' must declare a body because it is not marked abstract, extern, or partial // static void M06(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M06").WithArguments("I1.M06()").WithLocation(9, 17), // (10,18): error CS0501: 'I1.M07()' must declare a body because it is not marked abstract, extern, or partial // virtual void M07(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M07").WithArguments("I1.M07()").WithLocation(10, 18), // (11,17): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // sealed void M08(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(11, 17), // (14,17): warning CS0626: Method, operator, or accessor 'I1.M11()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void M11(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M11").WithArguments("I1.M11()").WithLocation(14, 17) ); ValidateSymbolsMethodModifiers_01(compilation1); } private static void ValidateSymbolsMethodModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.False(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Equal(Accessibility.Public, m01.DeclaredAccessibility); var m02 = i1.GetMember<MethodSymbol>("M02"); Assert.True(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.True(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.False(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Equal(Accessibility.Protected, m02.DeclaredAccessibility); var m03 = i1.GetMember<MethodSymbol>("M03"); Assert.True(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.True(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.False(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, m03.DeclaredAccessibility); var m04 = i1.GetMember<MethodSymbol>("M04"); Assert.True(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.True(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.False(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Equal(Accessibility.Internal, m04.DeclaredAccessibility); var m05 = i1.GetMember<MethodSymbol>("M05"); Assert.False(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.False(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.False(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Equal(Accessibility.Private, m05.DeclaredAccessibility); var m06 = i1.GetMember<MethodSymbol>("M06"); Assert.False(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.False(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Equal(Accessibility.Public, m06.DeclaredAccessibility); var m07 = i1.GetMember<MethodSymbol>("M07"); Assert.False(m07.IsAbstract); Assert.True(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.False(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Equal(Accessibility.Public, m07.DeclaredAccessibility); var m08 = i1.GetMember<MethodSymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.False(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Equal(Accessibility.Public, m08.DeclaredAccessibility); var m09 = i1.GetMember<MethodSymbol>("M09"); Assert.True(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.True(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.False(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Equal(Accessibility.Public, m09.DeclaredAccessibility); var m10 = i1.GetMember<MethodSymbol>("M10"); Assert.True(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.True(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.False(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Equal(Accessibility.Public, m10.DeclaredAccessibility); var m11 = i1.GetMember<MethodSymbol>("M11"); Assert.False(m11.IsAbstract); Assert.True(m11.IsVirtual); Assert.True(m11.IsMetadataVirtual()); Assert.False(m11.IsSealed); Assert.False(m11.IsStatic); Assert.True(m11.IsExtern); Assert.False(m11.IsAsync); Assert.False(m11.IsOverride); Assert.Equal(Accessibility.Public, m11.DeclaredAccessibility); var m12 = i1.GetMember<MethodSymbol>("M12"); Assert.True(m12.IsAbstract); Assert.False(m12.IsVirtual); Assert.True(m12.IsMetadataVirtual()); Assert.False(m12.IsSealed); Assert.False(m12.IsStatic); Assert.False(m12.IsExtern); Assert.True(m12.IsAsync); Assert.False(m12.IsOverride); Assert.Equal(Accessibility.Public, m12.DeclaredAccessibility); var m13 = i1.GetMember<MethodSymbol>("M13"); Assert.True(m13.IsAbstract); Assert.False(m13.IsVirtual); Assert.True(m13.IsMetadataVirtual()); Assert.False(m13.IsSealed); Assert.False(m13.IsStatic); Assert.False(m13.IsExtern); Assert.False(m13.IsAsync); Assert.False(m13.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, m13.DeclaredAccessibility); } [Fact] public void MethodModifiers_02() { var source1 = @" public interface I1 { public void M01(); protected void M02(); protected internal void M03(); internal void M04(); private void M05(); static void M06(); virtual void M07(); sealed void M08(); override void M09(); abstract void M10(); extern void M11(); async void M12(); private protected void M13(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,17): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("public", "7.3", "8.0").WithLocation(4, 17), // (5,20): error CS8703: The modifier 'protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // protected void M02(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("protected", "7.3", "8.0").WithLocation(5, 20), // (6,29): error CS8703: The modifier 'protected internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // protected internal void M03(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("protected internal", "7.3", "8.0").WithLocation(6, 29), // (7,19): error CS8503: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal void M04(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("internal", "7.3", "8.0").WithLocation(7, 19), // (8,18): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private void M05(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("private", "7.3", "8.0").WithLocation(8, 18), // (9,17): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static void M06(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("static", "7.3", "8.0").WithLocation(9, 17), // (10,18): error CS8503: The modifier 'virtual' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual void M07(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("virtual", "7.3", "8.0").WithLocation(10, 18), // (11,17): error CS8503: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // sealed void M08(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "8.0").WithLocation(11, 17), // (12,19): error CS0106: The modifier 'override' is not valid for this item // override void M09(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(12, 19), // (13,19): error CS8503: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // abstract void M10(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("abstract", "7.3", "8.0").WithLocation(13, 19), // (14,17): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern void M11(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M11").WithArguments("extern", "7.3", "8.0").WithLocation(14, 17), // (15,16): error CS8503: The modifier 'async' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // async void M12(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M12").WithArguments("async", "7.3", "8.0").WithLocation(15, 16), // (15,16): error CS1994: The 'async' modifier can only be used in methods that have a body. // async void M12(); Diagnostic(ErrorCode.ERR_BadAsyncLacksBody, "M12").WithLocation(15, 16), // (8,18): error CS0501: 'I1.M05()' must declare a body because it is not marked abstract, extern, or partial // private void M05(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M05").WithArguments("I1.M05()").WithLocation(8, 18), // (9,17): error CS0501: 'I1.M06()' must declare a body because it is not marked abstract, extern, or partial // static void M06(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M06").WithArguments("I1.M06()").WithLocation(9, 17), // (10,18): error CS0501: 'I1.M07()' must declare a body because it is not marked abstract, extern, or partial // virtual void M07(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M07").WithArguments("I1.M07()").WithLocation(10, 18), // (11,17): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // sealed void M08(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(11, 17), // (14,17): warning CS0626: Method, operator, or accessor 'I1.M11()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void M11(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M11").WithArguments("I1.M11()").WithLocation(14, 17), // (16,28): error CS8703: The modifier 'private protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private protected void M13(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M13").WithArguments("private protected", "7.3", "8.0").WithLocation(16, 28) ); ValidateSymbolsMethodModifiers_01(compilation1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (5,20): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected void M02(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "M02").WithLocation(5, 20), // (6,29): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal void M03(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "M03").WithLocation(6, 29), // (8,18): error CS0501: 'I1.M05()' must declare a body because it is not marked abstract, extern, or partial // private void M05(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M05").WithArguments("I1.M05()").WithLocation(8, 18), // (9,17): error CS0501: 'I1.M06()' must declare a body because it is not marked abstract, extern, or partial // static void M06(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M06").WithArguments("I1.M06()").WithLocation(9, 17), // (10,18): error CS0501: 'I1.M07()' must declare a body because it is not marked abstract, extern, or partial // virtual void M07(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M07").WithArguments("I1.M07()").WithLocation(10, 18), // (11,17): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // sealed void M08(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(11, 17), // (12,19): error CS0106: The modifier 'override' is not valid for this item // override void M09(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(12, 19), // (14,17): error CS8701: Target runtime doesn't support default interface implementation. // extern void M11(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M11").WithLocation(14, 17), // (14,17): warning CS0626: Method, operator, or accessor 'I1.M11()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void M11(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M11").WithArguments("I1.M11()").WithLocation(14, 17), // (15,16): error CS1994: The 'async' modifier can only be used in methods that have a body. // async void M12(); Diagnostic(ErrorCode.ERR_BadAsyncLacksBody, "M12").WithLocation(15, 16), // (16,28): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected void M13(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "M13").WithLocation(16, 28) ); ValidateSymbolsMethodModifiers_01(compilation2); } [Fact] [WorkItem(33083, "https://github.com/dotnet/roslyn/issues/33083")] public void MethodModifiers_03() { var source1 = @" public interface I1 { public virtual void M1() { System.Console.WriteLine(""M1""); } } "; ValidateMethodImplementation_011(source1); } [Fact] public void MethodModifiers_04() { var source1 = @" public interface I1 { public abstract void M1(); void M2(); } class Test1 : I1 { public void M1() { System.Console.WriteLine(""M1""); } public void M2() { System.Console.WriteLine(""M2""); } static void Main() { I1 x = new Test1(); x.M1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: @"M1 M2", symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); foreach (var methodName in new[] { "M1", "M2" }) { var m1 = i1.GetMember<MethodSymbol>(methodName); Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Same(test1.GetMember(methodName), test1.FindImplementationForInterfaceMember(m1)); } } } [Fact] public void MethodModifiers_05() { var source1 = @" public interface I1 { public abstract void M1(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3); compilation1.VerifyDiagnostics( // (4,26): error CS8503: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract void M1(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M1").WithArguments("abstract", "7.3", "8.0").WithLocation(4, 26), // (4,26): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract void M1(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M1").WithArguments("public", "7.3", "8.0").WithLocation(4, 26) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); } [Fact] public void MethodModifiers_06() { var source1 = @" public interface I1 { public static void M1() { System.Console.WriteLine(""M1""); } internal static void M2() { System.Console.WriteLine(""M2""); M3(); } private static void M3() { System.Console.WriteLine(""M3""); } } class Test1 : I1 { static void Main() { I1.M1(); I1.M2(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2 M3", symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); foreach (var tuple in new[] { (name: "M1", access: Accessibility.Public), (name: "M2", access: Accessibility.Internal), (name: "M3", access: Accessibility.Private) }) { var m1 = i1.GetMember<MethodSymbol>(tuple.name); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.True(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(tuple.access, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); } } } [Fact] public void MethodModifiers_07() { var source1 = @" public interface I1 { abstract static void M1(); virtual static void M2() { } sealed static void M3() { } static void M4() { } } class Test1 : I1 { void I1.M4() {} void I1.M1() {} void I1.M2() {} void I1.M3() {} } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.Net60); compilation1.VerifyDiagnostics( // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static void M3() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M3").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (6,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M2() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M2").WithArguments("virtual").WithLocation(6, 25), // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M1(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M1").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (21,13): error CS0539: 'Test1.M4()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M4() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M4").WithArguments("Test1.M4()").WithLocation(21, 13), // (22,13): error CS0539: 'Test1.M1()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M1() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M1").WithArguments("Test1.M1()").WithLocation(22, 13), // (23,13): error CS0539: 'Test1.M2()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M2() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M2").WithArguments("Test1.M2()").WithLocation(23, 13), // (24,13): error CS0539: 'Test1.M3()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M3() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M3").WithArguments("Test1.M3()").WithLocation(24, 13), // (19,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M1()").WithLocation(19, 15), // (27,15): error CS0535: 'Test2' does not implement interface member 'I1.M1()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M1()").WithLocation(27, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.True(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.False(m2.IsAbstract); Assert.False(m2.IsVirtual); Assert.False(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.True(m2.IsStatic); Assert.False(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m2)); var m3 = i1.GetMember<MethodSymbol>("M3"); Assert.False(m3.IsAbstract); Assert.False(m3.IsVirtual); Assert.False(m3.IsMetadataVirtual()); Assert.False(m3.IsSealed); Assert.True(m3.IsStatic); Assert.False(m3.IsExtern); Assert.False(m3.IsAsync); Assert.False(m3.IsOverride); Assert.Equal(Accessibility.Public, m3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m3)); } [Fact] public void MethodModifiers_08() { var source1 = @" public interface I1 { private void M1() { System.Console.WriteLine(""M1""); } void M4() { System.Console.WriteLine(""M4""); M1(); } } class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M4(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M4 M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); } } [Fact] public void MethodModifiers_09() { var source1 = @" public interface I1 { abstract private void M1(); virtual private void M2() { } sealed private void M3() { } } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (10,25): error CS0238: 'I1.M3()' cannot be sealed because it is not an override // sealed private void M3() Diagnostic(ErrorCode.ERR_SealedNonOverride, "M3").WithArguments("I1.M3()").WithLocation(10, 25), // (6,26): error CS0621: 'I1.M2()': virtual or abstract members cannot be private // virtual private void M2() Diagnostic(ErrorCode.ERR_VirtualPrivate, "M2").WithArguments("I1.M2()").WithLocation(6, 26), // (4,27): error CS0621: 'I1.M1()': virtual or abstract members cannot be private // abstract private void M1(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "M1").WithArguments("I1.M1()").WithLocation(4, 27), // (15,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M1()").WithLocation(15, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.False(m2.IsAbstract); Assert.True(m2.IsVirtual); Assert.True(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.False(m2.IsStatic); Assert.False(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility); Assert.Same(m2, test1.FindImplementationForInterfaceMember(m2)); var m3 = i1.GetMember<MethodSymbol>("M3"); Assert.False(m3.IsAbstract); Assert.False(m3.IsVirtual); Assert.False(m3.IsMetadataVirtual()); Assert.True(m3.IsSealed); Assert.False(m3.IsStatic); Assert.False(m3.IsExtern); Assert.False(m3.IsAsync); Assert.False(m3.IsOverride); Assert.Equal(Accessibility.Private, m3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m3)); } [Fact] public void MethodModifiers_10_01() { var source1 = @" public interface I1 { internal abstract void M1(); void M2() {M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (9,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(9, 15) ); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.Internal); compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.Internal)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.Internal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.Internal); var source3 = @" class Test2 : I1 { } "; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 15) ); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.Internal); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.Internal)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.Internal); var compilation5 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.M1()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M1()").WithLocation(2, 15) ); ValidateI1M1NotImplemented(compilation5, "Test2"); } } private static void ValidateI1M1NotImplemented(CSharpCompilation compilation, string className) { var test2 = compilation.GetTypeByMetadataName(className); var i1 = compilation.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.Null(test2.FindImplementationForInterfaceMember(m1)); } private static void ValidateMethodModifiersImplicit_10(ModuleSymbol m, Accessibility accessibility) { ValidateMethodModifiers_10(m, implementedByBase: false, isExplicit: false, accessibility); } private static void ValidateMethodModifiersExplicit_10(ModuleSymbol m, Accessibility accessibility) { ValidateMethodModifiers_10(m, implementedByBase: false, isExplicit: true, accessibility); } private static void ValidateMethodModifiersImplicitInTest2_10(ModuleSymbol m, Accessibility accessibility) { ValidateMethodModifiers_10(m, implementedByBase: true, isExplicit: false, accessibility); } private static void ValidateMethodModifiersExplicitInTest2_10(ModuleSymbol m, Accessibility accessibility) { ValidateMethodModifiers_10(m, implementedByBase: true, isExplicit: true, accessibility); } private static void ValidateMethodModifiers_10(ModuleSymbol m, bool implementedByBase, bool isExplicit, Accessibility accessibility) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var m1 = i1.GetMember<MethodSymbol>("M1"); ValidateMethodModifiers_10(m1, accessibility); var implementation = (implementedByBase ? test1.BaseTypeNoUseSiteDiagnostics : test1).GetMember<MethodSymbol>((isExplicit ? "I1." : "") + "M1"); Assert.NotNull(implementation); Assert.Same(implementation, test1.FindImplementationForInterfaceMember(m1)); Assert.True(implementation.IsMetadataVirtual()); } private static void ValidateMethodModifiers_10(MethodSymbol m1, Accessibility accessibility) { Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(accessibility, m1.DeclaredAccessibility); } [Fact] public void MethodModifiers_10_02() { var source1 = @" public interface I1 { internal abstract void M1(); } public class TestHelper { public static void CallM1(I1 x) {x.M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallM1(new Test1()); } public virtual void M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.Internal, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 15) ); } private void ValidateMethodModifiers_10_02(string source1, string source2, Accessibility accessibility, params DiagnosticDescription[] expectedIn9) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expectedIn9); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, accessibility); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "Test1.M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, accessibility)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, accessibility); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), accessibility); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expectedIn9); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, accessibility); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "Test1.M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, accessibility)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, accessibility); } } [Fact] public void MethodModifiers_10_03() { var source1 = @" public interface I1 { internal abstract void M1(); } public class TestHelper { public static void CallM1(I1 x) {x.M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallM1(new Test1()); } void I1.M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersExplicit_10(m, Accessibility.Internal)); ValidateMethodModifiersExplicit_10(compilation1.SourceModule, Accessibility.Internal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.Internal); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation3.VerifyDiagnostics( // (9,13): error CS0122: 'I1.M1()' is inaccessible due to its protection level // void I1.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.M1()").WithLocation(9, 13) ); ValidateMethodModifiersExplicit_10(compilation3.SourceModule, Accessibility.Internal); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation4.VerifyDiagnostics( // (9,13): error CS0122: 'I1.M1()' is inaccessible due to its protection level // void I1.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.M1()").WithLocation(9, 13) ); ValidateMethodModifiersExplicit_10(compilation4.SourceModule, Accessibility.Internal); } [Fact] public void MethodModifiers_10_04() { var source1 = @" public interface I1 { internal abstract void M1(); } public class TestHelper { public static void CallM1(I1 x) {x.M1();} } public class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2.M1""); } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallM1(new Test1()); } public void M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.Internal, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void MethodModifiers_10_05() { var source1 = @" public interface I1 { internal abstract void M1(); } public class TestHelper { public static void CallM1(I1 x) {x.M1();} } public class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2.M1""); } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallM1(new Test1()); } public virtual void M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.Internal, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void MethodModifiers_10_06() { var source1 = @" public interface I1 { internal abstract void M1(); } public class TestHelper { public static void CallM1(I1 x) {x.M1();} } public class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2.M1""); } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallM1(new Test3()); } public abstract void M1(); } class Test3 : Test1 { public override void M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.Internal, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void MethodModifiers_10_07() { var source1 = @" public interface I1 { internal abstract void M1(); } public class TestHelper { public static void CallM1(I1 x) {x.M1();} } public class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2.M1""); } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallM1(new Test1()); } public void M1() { System.Console.WriteLine(""Test1.M1""); } } public interface I2 { void M1(); } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.Internal, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void MethodModifiers_10_08() { var source1 = @" public interface I1 { internal abstract void M1(); } public class TestHelper { public static void CallM1(I1 x) {x.M1();} } public class Test2 : I1 { void I1.M1() { System.Console.WriteLine(""Test2.M1""); } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallM1(new Test1()); } public virtual int M1() { System.Console.WriteLine(""Test1.M1""); return 0; } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: "Test2.M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersExplicitInTest2_10(m, Accessibility.Internal)); ValidateMethodModifiersExplicitInTest2_10(compilation1.SourceModule, Accessibility.Internal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.Internal); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation3, expectedOutput: "Test2.M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersExplicitInTest2_10(m, Accessibility.Internal)); ValidateMethodModifiersExplicitInTest2_10(compilation3.SourceModule, Accessibility.Internal); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation4, expectedOutput: "Test2.M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersExplicitInTest2_10(m, Accessibility.Internal)); ValidateMethodModifiersExplicitInTest2_10(compilation4.SourceModule, Accessibility.Internal); } [Fact] public void MethodModifiers_10_09() { var source1 = @" public interface I1 { internal abstract void M1(); void M2() {M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public virtual int M1() { System.Console.WriteLine(""M1""); return 0; } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (9,15): error CS0738: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implement 'I1.M1()' because it does not have the matching return type of 'void'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "void").WithLocation(9, 15) ); ValidateI1M1NotImplemented(compilation1, "Test1"); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.Internal); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implement 'I1.M1()' because it does not have the matching return type of 'void'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "void").WithLocation(2, 15) ); ValidateI1M1NotImplemented(compilation3, "Test1"); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics( // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implement 'I1.M1()' because it does not have the matching return type of 'void'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "void").WithLocation(2, 15) ); ValidateI1M1NotImplemented(compilation4, "Test1"); } [Fact] public void MethodModifiers_10_10() { var source1 = @" public interface I1 { internal abstract void M1(); void M2() {M1();} } "; var source2 = @" class Test2 : I1 { public void M1() { System.Console.WriteLine(""M1""); } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,15): error CS8704: 'Test2' does not implement interface member 'I1.M1()'. 'Test2.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.M1()", "Test2.M1()", "9.0", "10.0").WithLocation(9, 15) ); ValidateMethodModifiersImplicitInTest2_10(compilation1.SourceModule, Accessibility.Internal); compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicitInTest2_10(m, Accessibility.Internal)).VerifyDiagnostics(); ValidateMethodModifiersImplicitInTest2_10(compilation1.SourceModule, Accessibility.Internal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.Internal); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (2,15): error CS8704: 'Test2' does not implement interface member 'I1.M1()'. 'Test2.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.M1()", "Test2.M1()", "9.0", "10.0").WithLocation(2, 15) ); ValidateMethodModifiersImplicitInTest2_10(compilation3.SourceModule, Accessibility.Internal); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicitInTest2_10(m, Accessibility.Internal)).VerifyDiagnostics(); ValidateMethodModifiersImplicitInTest2_10(compilation3.SourceModule, Accessibility.Internal); } } [Fact] public void MethodModifiers_10_11() { var source1 = @" public interface I1 { internal abstract void M1(); void M2() {M1();} } public class Test2 : I1 { public void M1() { System.Console.WriteLine(""M1""); } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp, assemblyName: "MethodModifiers_10_11"); compilation2.VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicitInTest2_10(m, Accessibility.Internal)).VerifyDiagnostics(); ValidateMethodModifiersImplicitInTest2_10(compilation3.SourceModule, Accessibility.Internal); compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicitInTest2_10(m, Accessibility.Internal)).VerifyDiagnostics(); ValidateMethodModifiersImplicitInTest2_10(compilation3.SourceModule, Accessibility.Internal); } [Fact] public void MethodModifiers_11() { var source1 = @" public interface I1 { internal abstract void M1(); } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M1()").WithLocation(7, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Internal, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); } [Fact] public void MethodModifiers_12() { var source1 = @" public interface I1 { public sealed void M1() { System.Console.WriteLine(""M1""); } } class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M1(); } public void M1() { System.Console.WriteLine(""Test1.M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); } CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); } [Fact] public void MethodModifiers_13() { var source1 = @" public interface I1 { public sealed void M1() { System.Console.WriteLine(""M1""); } abstract sealed void M2(); virtual sealed void M3() { } public sealed void M4(); } class Test1 : I1 { void I1.M1() {} void I1.M2() {} void I1.M3() {} void I1.M4() {} } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (15,24): error CS0501: 'I1.M4()' must declare a body because it is not marked abstract, extern, or partial // public sealed void M4(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M4").WithArguments("I1.M4()").WithLocation(15, 24), // (9,26): error CS0238: 'I1.M2()' cannot be sealed because it is not an override // abstract sealed void M2(); Diagnostic(ErrorCode.ERR_SealedNonOverride, "M2").WithArguments("I1.M2()").WithLocation(9, 26), // (11,25): error CS0238: 'I1.M3()' cannot be sealed because it is not an override // virtual sealed void M3() Diagnostic(ErrorCode.ERR_SealedNonOverride, "M3").WithArguments("I1.M3()").WithLocation(11, 25), // (23,13): error CS0539: 'Test1.M4()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M4() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M4").WithArguments("Test1.M4()").WithLocation(23, 13), // (20,13): error CS0539: 'Test1.M1()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M1() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M1").WithArguments("Test1.M1()").WithLocation(20, 13), // (21,13): error CS0539: 'Test1.M2()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M2() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M2").WithArguments("Test1.M2()").WithLocation(21, 13), // (22,13): error CS0539: 'Test1.M3()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M3() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M3").WithArguments("Test1.M3()").WithLocation(22, 13) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); Assert.Null(test2.FindImplementationForInterfaceMember(m1)); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.True(m2.IsAbstract); Assert.False(m2.IsVirtual); Assert.True(m2.IsMetadataVirtual()); Assert.True(m2.IsSealed); Assert.False(m2.IsStatic); Assert.False(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m2)); Assert.Null(test2.FindImplementationForInterfaceMember(m2)); var m3 = i1.GetMember<MethodSymbol>("M3"); Assert.False(m3.IsAbstract); Assert.True(m3.IsVirtual); Assert.True(m3.IsMetadataVirtual()); Assert.True(m3.IsSealed); Assert.False(m3.IsStatic); Assert.False(m3.IsExtern); Assert.False(m3.IsAsync); Assert.False(m3.IsOverride); Assert.Equal(Accessibility.Public, m3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m3)); Assert.Null(test2.FindImplementationForInterfaceMember(m3)); var m4 = i1.GetMember<MethodSymbol>("M4"); Assert.False(m4.IsAbstract); Assert.False(m4.IsVirtual); Assert.False(m4.IsMetadataVirtual()); Assert.False(m4.IsSealed); Assert.False(m4.IsStatic); Assert.False(m4.IsExtern); Assert.False(m4.IsAsync); Assert.False(m4.IsOverride); Assert.Equal(Accessibility.Public, m4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m4)); Assert.Null(test2.FindImplementationForInterfaceMember(m4)); } [Fact] public void MethodModifiers_14() { var source1 = @" public interface I1 { abstract virtual void M2(); virtual abstract void M3() { } } class Test1 : I1 { void I1.M2() {} void I1.M3() {} } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (6,27): error CS0500: 'I1.M3()' cannot declare a body because it is marked abstract // virtual abstract void M3() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M3").WithArguments("I1.M3()").WithLocation(6, 27), // (6,27): error CS0503: The abstract method 'I1.M3()' cannot be marked virtual // virtual abstract void M3() Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "M3").WithArguments("method", "I1.M3()").WithLocation(6, 27), // (4,27): error CS0503: The abstract method 'I1.M2()' cannot be marked virtual // abstract virtual void M2(); Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "M2").WithArguments("method", "I1.M2()").WithLocation(4, 27), // (17,15): error CS0535: 'Test2' does not implement interface member 'I1.M3()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M3()").WithLocation(17, 15), // (17,15): error CS0535: 'Test2' does not implement interface member 'I1.M2()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M2()").WithLocation(17, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var i1 = compilation1.GetTypeByMetadataName("I1"); foreach (var methodName in new[] { "M2", "M3" }) { var m2 = i1.GetMember<MethodSymbol>(methodName); Assert.True(m2.IsAbstract); Assert.True(m2.IsVirtual); Assert.True(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.False(m2.IsStatic); Assert.False(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility); Assert.Same(test1.GetMember("I1." + methodName), test1.FindImplementationForInterfaceMember(m2)); Assert.Null(test2.FindImplementationForInterfaceMember(m2)); } } [Fact] public void MethodModifiers_15() { var source1 = @" public interface I1 { extern void M1(); virtual extern void M2(); static extern void M3(); private extern void M4(); extern sealed void M5(); } class Test1 : I1 { } class Test2 : I1 { void I1.M1() {} void I1.M2() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test2 = m.GlobalNamespace.GetTypeMember("Test2"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); bool isSource = !(m is PEModuleSymbol); Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.Equal(isSource, m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); Assert.Same(test2.GetMember("I1.M1"), test2.FindImplementationForInterfaceMember(m1)); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.False(m2.IsAbstract); Assert.True(m2.IsVirtual); Assert.True(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.False(m2.IsStatic); Assert.Equal(isSource, m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility); Assert.Same(m2, test1.FindImplementationForInterfaceMember(m2)); Assert.Same(test2.GetMember("I1.M2"), test2.FindImplementationForInterfaceMember(m2)); var m3 = i1.GetMember<MethodSymbol>("M3"); Assert.False(m3.IsAbstract); Assert.False(m3.IsVirtual); Assert.False(m3.IsMetadataVirtual()); Assert.False(m3.IsSealed); Assert.True(m3.IsStatic); Assert.Equal(isSource, m3.IsExtern); Assert.False(m3.IsAsync); Assert.False(m3.IsOverride); Assert.Equal(Accessibility.Public, m3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m3)); Assert.Null(test2.FindImplementationForInterfaceMember(m3)); var m4 = i1.GetMember<MethodSymbol>("M4"); Assert.False(m4.IsAbstract); Assert.False(m4.IsVirtual); Assert.False(m4.IsMetadataVirtual()); Assert.False(m4.IsSealed); Assert.False(m4.IsStatic); Assert.Equal(isSource, m4.IsExtern); Assert.False(m4.IsAsync); Assert.False(m4.IsOverride); Assert.Equal(Accessibility.Private, m4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m4)); Assert.Null(test2.FindImplementationForInterfaceMember(m4)); var m5 = i1.GetMember<MethodSymbol>("M5"); Assert.False(m5.IsAbstract); Assert.False(m5.IsVirtual); Assert.False(m5.IsMetadataVirtual()); Assert.False(m5.IsSealed); Assert.False(m5.IsStatic); Assert.Equal(isSource, m5.IsExtern); Assert.False(m5.IsAsync); Assert.False(m5.IsOverride); Assert.Equal(Accessibility.Public, m5.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m5)); Assert.Null(test2.FindImplementationForInterfaceMember(m5)); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (4,17): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern void M1(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M1").WithArguments("extern", "7.3", "8.0").WithLocation(4, 17), // (5,25): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern void M2(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M2").WithArguments("extern", "7.3", "8.0").WithLocation(5, 25), // (5,25): error CS8503: The modifier 'virtual' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern void M2(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M2").WithArguments("virtual", "7.3", "8.0").WithLocation(5, 25), // (6,24): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static extern void M3(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M3").WithArguments("static", "7.3", "8.0").WithLocation(6, 24), // (6,24): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static extern void M3(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M3").WithArguments("extern", "7.3", "8.0").WithLocation(6, 24), // (7,25): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern void M4(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M4").WithArguments("private", "7.3", "8.0").WithLocation(7, 25), // (7,25): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern void M4(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M4").WithArguments("extern", "7.3", "8.0").WithLocation(7, 25), // (8,24): error CS8503: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed void M5(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M5").WithArguments("sealed", "7.3", "8.0").WithLocation(8, 24), // (8,24): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed void M5(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M5").WithArguments("extern", "7.3", "8.0").WithLocation(8, 24), // (4,17): warning CS0626: Method, operator, or accessor 'I1.M1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void M1(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M1").WithArguments("I1.M1()").WithLocation(4, 17), // (5,25): warning CS0626: Method, operator, or accessor 'I1.M2()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern void M2(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M2").WithArguments("I1.M2()").WithLocation(5, 25), // (6,24): warning CS0626: Method, operator, or accessor 'I1.M3()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern void M3(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M3").WithArguments("I1.M3()").WithLocation(6, 24), // (7,25): warning CS0626: Method, operator, or accessor 'I1.M4()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern void M4(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M4").WithArguments("I1.M4()").WithLocation(7, 25), // (8,24): warning CS0626: Method, operator, or accessor 'I1.M5()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed void M5(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M5").WithArguments("I1.M5()").WithLocation(8, 24) ); Validate(compilation2.SourceModule); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (4,17): error CS8501: Target runtime doesn't support default interface implementation. // extern void M1(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(4, 17), // (5,25): error CS8501: Target runtime doesn't support default interface implementation. // virtual extern void M2(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M2").WithLocation(5, 25), // (6,24): error CS8701: Target runtime doesn't support default interface implementation. // static extern void M3(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M3").WithLocation(6, 24), // (7,25): error CS8501: Target runtime doesn't support default interface implementation. // private extern void M4(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M4").WithLocation(7, 25), // (8,24): error CS8501: Target runtime doesn't support default interface implementation. // extern sealed void M5(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M5").WithLocation(8, 24), // (4,17): warning CS0626: Method, operator, or accessor 'I1.M1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void M1(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M1").WithArguments("I1.M1()").WithLocation(4, 17), // (5,25): warning CS0626: Method, operator, or accessor 'I1.M2()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern void M2(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M2").WithArguments("I1.M2()").WithLocation(5, 25), // (6,24): warning CS0626: Method, operator, or accessor 'I1.M3()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern void M3(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M3").WithArguments("I1.M3()").WithLocation(6, 24), // (7,25): warning CS0626: Method, operator, or accessor 'I1.M4()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern void M4(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M4").WithArguments("I1.M4()").WithLocation(7, 25), // (8,24): warning CS0626: Method, operator, or accessor 'I1.M5()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed void M5(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M5").WithArguments("I1.M5()").WithLocation(8, 24) ); Validate(compilation3.SourceModule); } [Fact] public void MethodModifiers_16() { var source1 = @" public interface I1 { abstract extern void M1(); extern void M2() {} static extern void M3(); private extern void M4(); extern sealed void M5(); } class Test1 : I1 { } class Test2 : I1 { void I1.M1() {} void I1.M2() {} void I1.M3() {} void I1.M4() {} void I1.M5() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,26): error CS0180: 'I1.M1()' cannot be both extern and abstract // abstract extern void M1(); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M1").WithArguments("I1.M1()").WithLocation(4, 26), // (5,17): error CS0179: 'I1.M2()' cannot be extern and declare a body // extern void M2() {} Diagnostic(ErrorCode.ERR_ExternHasBody, "M2").WithArguments("I1.M2()").WithLocation(5, 17), // (11,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M1()").WithLocation(11, 15), // (19,13): error CS0539: 'Test2.M3()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M3() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M3").WithArguments("Test2.M3()").WithLocation(19, 13), // (20,13): error CS0539: 'Test2.M4()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M4() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M4").WithArguments("Test2.M4()").WithLocation(20, 13), // (21,13): error CS0539: 'Test2.M5()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M5() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M5").WithArguments("Test2.M5()").WithLocation(21, 13), // (6,24): warning CS0626: Method, operator, or accessor 'I1.M3()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern void M3(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M3").WithArguments("I1.M3()").WithLocation(6, 24), // (7,25): warning CS0626: Method, operator, or accessor 'I1.M4()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern void M4(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M4").WithArguments("I1.M4()").WithLocation(7, 25), // (8,24): warning CS0626: Method, operator, or accessor 'I1.M5()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed void M5(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M5").WithArguments("I1.M5()").WithLocation(8, 24) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.True(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); Assert.Same(test2.GetMember("I1.M1"), test2.FindImplementationForInterfaceMember(m1)); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.False(m2.IsAbstract); Assert.True(m2.IsVirtual); Assert.True(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.False(m2.IsStatic); Assert.True(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility); Assert.Same(m2, test1.FindImplementationForInterfaceMember(m2)); Assert.Same(test2.GetMember("I1.M2"), test2.FindImplementationForInterfaceMember(m2)); var m3 = i1.GetMember<MethodSymbol>("M3"); Assert.Null(test2.FindImplementationForInterfaceMember(m3)); var m4 = i1.GetMember<MethodSymbol>("M4"); Assert.Null(test2.FindImplementationForInterfaceMember(m4)); var m5 = i1.GetMember<MethodSymbol>("M5"); Assert.Null(test2.FindImplementationForInterfaceMember(m5)); } [Fact] public void MethodModifiers_17() { var source1 = @" public interface I1 { abstract void M1() {} abstract private void M2() {} abstract static void M3() {} static extern void M4() {} override sealed void M5() {} } class Test1 : I1 { } class Test2 : I1 { void I1.M1() {} void I1.M2() {} void I1.M3() {} void I1.M4() {} void I1.M5() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,19): error CS0500: 'I1.M1()' cannot declare a body because it is marked abstract // abstract void M1() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M1").WithArguments("I1.M1()").WithLocation(4, 19), // (5,27): error CS0500: 'I1.M2()' cannot declare a body because it is marked abstract // abstract private void M2() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M2").WithArguments("I1.M2()").WithLocation(5, 27), // (6,26): error CS0500: 'I1.M3()' cannot declare a body because it is marked abstract // abstract static void M3() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M3").WithArguments("I1.M3()").WithLocation(6, 26), // (7,24): error CS0179: 'I1.M4()' cannot be extern and declare a body // static extern void M4() {} Diagnostic(ErrorCode.ERR_ExternHasBody, "M4").WithArguments("I1.M4()").WithLocation(7, 24), // (8,26): error CS0106: The modifier 'override' is not valid for this item // override sealed void M5() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "M5").WithArguments("override").WithLocation(8, 26), // (5,27): error CS0621: 'I1.M2()': virtual or abstract members cannot be private // abstract private void M2() {} Diagnostic(ErrorCode.ERR_VirtualPrivate, "M2").WithArguments("I1.M2()").WithLocation(5, 27), // (6,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M3() {} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M3").WithArguments("abstract", "9.0", "preview").WithLocation(6, 26), // (11,15): error CS0535: 'Test1' does not implement interface member 'I1.M2()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M2()").WithLocation(11, 15), // (11,15): error CS0535: 'Test1' does not implement interface member 'I1.M3()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M3()").WithLocation(11, 15), // (11,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M1()").WithLocation(11, 15), // (18,13): error CS0122: 'I1.M2()' is inaccessible due to its protection level // void I1.M2() {} Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("I1.M2()").WithLocation(18, 13), // (19,13): error CS0539: 'Test2.M3()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M3() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M3").WithArguments("Test2.M3()").WithLocation(19, 13), // (20,13): error CS0539: 'Test2.M4()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M4() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M4").WithArguments("Test2.M4()").WithLocation(20, 13), // (21,13): error CS0539: 'Test2.M5()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M5() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M5").WithArguments("Test2.M5()").WithLocation(21, 13), // (15,15): error CS0535: 'Test2' does not implement interface member 'I1.M3()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M3()").WithLocation(15, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); Assert.Same(test2.GetMember("I1.M1"), test2.FindImplementationForInterfaceMember(m1)); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.True(m2.IsAbstract); Assert.False(m2.IsVirtual); Assert.True(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.False(m2.IsStatic); Assert.False(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m2)); Assert.Same(test2.GetMember("I1.M2"), test2.FindImplementationForInterfaceMember(m2)); var m3 = i1.GetMember<MethodSymbol>("M3"); Assert.True(m3.IsAbstract); Assert.False(m3.IsVirtual); Assert.True(m3.IsMetadataVirtual()); Assert.False(m3.IsSealed); Assert.True(m3.IsStatic); Assert.False(m3.IsExtern); Assert.False(m3.IsAsync); Assert.False(m3.IsOverride); Assert.Equal(Accessibility.Public, m3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m3)); Assert.Null(test2.FindImplementationForInterfaceMember(m3)); var m4 = i1.GetMember<MethodSymbol>("M4"); Assert.False(m4.IsAbstract); Assert.False(m4.IsVirtual); Assert.False(m4.IsMetadataVirtual()); Assert.False(m4.IsSealed); Assert.True(m4.IsStatic); Assert.True(m4.IsExtern); Assert.False(m4.IsAsync); Assert.False(m4.IsOverride); Assert.Equal(Accessibility.Public, m4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m4)); Assert.Null(test2.FindImplementationForInterfaceMember(m4)); var m5 = i1.GetMember<MethodSymbol>("M5"); Assert.False(m5.IsAbstract); Assert.False(m5.IsVirtual); Assert.False(m5.IsMetadataVirtual()); Assert.False(m5.IsSealed); Assert.False(m5.IsStatic); Assert.False(m5.IsExtern); Assert.False(m5.IsAsync); Assert.False(m5.IsOverride); Assert.Equal(Accessibility.Public, m5.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m5)); Assert.Null(test2.FindImplementationForInterfaceMember(m5)); } [Fact] [WorkItem(34658, "https://github.com/dotnet/roslyn/issues/34658")] public void MethodModifiers_18() { var source1 = @" using System.Threading; using System.Threading.Tasks; public interface I1 { public static async Task M1() { await Task.Factory.StartNew(() => System.Console.WriteLine(""M1"")); } } class Test1 : I1 { static void Main() { I1.M1().Wait(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.True(m1.IsStatic); Assert.False(m1.IsExtern); Assert.Equal(!(m is PEModuleSymbol), m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); } } [Fact] public void MethodModifiers_20() { var source1 = @" public interface I1 { internal void M1() { System.Console.WriteLine(""M1""); } void M2() {M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var m1 = i1.GetMember<MethodSymbol>("M1"); ValidateMethod(m1); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); } void ValidateMethod(MethodSymbol m1) { Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Internal, m1.DeclaredAccessibility); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); ValidateMethod(m1); } var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation3.SourceModule); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation4, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation4.SourceModule); } [Fact] public void MethodModifiers_21() { var source1 = @" public interface I1 { private static void M1() {} internal static void M2() {} public static void M3() {} static void M4() {} } class Test1 { static void Main() { I1.M1(); I1.M2(); I1.M3(); I1.M4(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (17,12): error CS0122: 'I1.M1()' is inaccessible due to its protection level // I1.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.M1()").WithLocation(17, 12) ); var source2 = @" class Test2 { static void Main() { I1.M1(); I1.M2(); I1.M3(); I1.M4(); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,12): error CS0122: 'I1.M1()' is inaccessible due to its protection level // I1.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.M1()").WithLocation(6, 12), // (7,12): error CS0122: 'I1.M2()' is inaccessible due to its protection level // I1.M2(); Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("I1.M2()").WithLocation(7, 12) ); } [Fact] public void MethodModifiers_22() { var source1 = @" public partial interface I1 { static partial void M1(); [Test2(1)] static partial void M2(); static partial void Main() { M1(); M2(); new System.Action(M2).Invoke(); } } public partial interface I1 { [Test2(2)] static partial void M2() { System.Console.WriteLine(""M2""); } static partial void Main(); } class Test1 : I1 { } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)] class Test2 : System.Attribute { public Test2(int x) {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M2 M2"); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.True(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); Assert.True(m1.IsPartialMethod()); Assert.Null(m1.PartialImplementationPart); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.False(m2.IsAbstract); Assert.False(m2.IsVirtual); Assert.False(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.True(m2.IsStatic); Assert.False(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility); Assert.True(m2.IsPartialMethod()); Assert.Equal(2, m2.GetAttributes().Length); Assert.Equal("Test2(1)", m2.GetAttributes()[0].ToString()); Assert.Equal("Test2(2)", m2.GetAttributes()[1].ToString()); var m2Impl = m2.PartialImplementationPart; Assert.False(m2Impl.IsAbstract); Assert.False(m2Impl.IsVirtual); Assert.False(m2Impl.IsMetadataVirtual()); Assert.False(m2Impl.IsSealed); Assert.True(m2Impl.IsStatic); Assert.False(m2Impl.IsExtern); Assert.False(m2Impl.IsAsync); Assert.False(m2Impl.IsOverride); Assert.Equal(Accessibility.Private, m2Impl.DeclaredAccessibility); Assert.True(m2Impl.IsPartialMethod()); Assert.Same(m2, m2Impl.PartialDefinitionPart); Assert.Equal(2, m2Impl.GetAttributes().Length); Assert.Equal("Test2(1)", m2Impl.GetAttributes()[0].ToString()); Assert.Equal("Test2(2)", m2Impl.GetAttributes()[1].ToString()); } [Fact] public void MethodModifiers_23() { var source1 = @" public partial interface I1 { partial void M1(); [Test2(1)] partial void M2(); void M3() { M1(); M2(); new System.Action(M2).Invoke(); } } public partial interface I1 { [Test2(2)] partial void M2() { System.Console.WriteLine(""M2""); } } class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M3(); } } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)] class Test2 : System.Attribute { public Test2(int x) {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M2 M2", verify: VerifyOnMonoOrCoreClr); var i1 = compilation1.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); Assert.True(m1.IsPartialMethod()); Assert.Null(m1.PartialImplementationPart); var m2 = i1.GetMember<MethodSymbol>("M2"); Assert.False(m2.IsAbstract); Assert.False(m2.IsVirtual); Assert.False(m2.IsMetadataVirtual()); Assert.False(m2.IsSealed); Assert.False(m2.IsStatic); Assert.False(m2.IsExtern); Assert.False(m2.IsAsync); Assert.False(m2.IsOverride); Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility); Assert.True(m2.IsPartialMethod()); Assert.Equal(2, m2.GetAttributes().Length); Assert.Equal("Test2(1)", m2.GetAttributes()[0].ToString()); Assert.Equal("Test2(2)", m2.GetAttributes()[1].ToString()); var m2Impl = m2.PartialImplementationPart; Assert.False(m2Impl.IsAbstract); Assert.False(m2Impl.IsVirtual); Assert.False(m2Impl.IsMetadataVirtual()); Assert.False(m2Impl.IsSealed); Assert.False(m2Impl.IsStatic); Assert.False(m2Impl.IsExtern); Assert.False(m2Impl.IsAsync); Assert.False(m2Impl.IsOverride); Assert.Equal(Accessibility.Private, m2Impl.DeclaredAccessibility); Assert.True(m2Impl.IsPartialMethod()); Assert.Same(m2, m2Impl.PartialDefinitionPart); Assert.Equal(2, m2Impl.GetAttributes().Length); Assert.Equal("Test2(1)", m2Impl.GetAttributes()[0].ToString()); Assert.Equal("Test2(2)", m2Impl.GetAttributes()[1].ToString()); } [Fact] public void MethodModifiers_24() { var source1 = @" public partial interface I1 { static partial void M1(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3); compilation1.VerifyDiagnostics( // (4,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static partial void M1(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M1").WithArguments("static", "7.3", "8.0").WithLocation(4, 25), // (4,25): error CS8703: The modifier 'partial' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static partial void M1(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M1").WithArguments("partial", "7.3", "8.0").WithLocation(4, 25) ); } [Fact] public void MethodModifiers_25() { var source1 = @" public partial interface I1 { partial void M1(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,18): error CS8703: The modifier 'partial' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // partial void M1(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M1").WithArguments("partial", "7.3", "8.0").WithLocation(4, 18) ); } [Fact] public void MethodModifiers_26() { var source1 = @" public partial interface I1 { static partial int M1(); public static partial void M2(); internal static partial void M3(); private static partial void M4(); static partial void M5(out int x); static partial void M6(); static void M7() {} static partial void M8() {} static partial void M9(); static partial void M10(); } public partial interface I1 { static void M6() {} static partial void M7(); static partial void M8() {} static partial void M9(); static extern partial void M10(); protected static partial void M11(); protected internal static partial void M12(); private protected static partial void M13(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularWithExtendedPartialMethods, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS8794: Partial method 'I1.M1()' must have accessibility modifiers because it has a non-void return type. // static partial int M1(); Diagnostic(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, "M1").WithArguments("I1.M1()").WithLocation(4, 24), // (5,32): error CS8793: Partial method 'I1.M2()' must have an implementation part because it has accessibility modifiers. // public static partial void M2(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M2").WithArguments("I1.M2()").WithLocation(5, 32), // (6,34): error CS8793: Partial method 'I1.M3()' must have an implementation part because it has accessibility modifiers. // internal static partial void M3(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M3").WithArguments("I1.M3()").WithLocation(6, 34), // (7,33): error CS8793: Partial method 'I1.M4()' must have an implementation part because it has accessibility modifiers. // private static partial void M4(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M4").WithArguments("I1.M4()").WithLocation(7, 33), // (8,25): error CS8795: Partial method 'I1.M5(out int)' must have accessibility modifiers because it has 'out' parameters. // static partial void M5(out int x); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M5").WithArguments("I1.M5(out int)").WithLocation(8, 25), // (11,25): error CS0759: No defining declaration found for implementing declaration of partial method 'I1.M8()' // static partial void M8() {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M8").WithArguments("I1.M8()").WithLocation(11, 25), // (18,17): error CS0111: Type 'I1' already defines a member called 'M6' with the same parameter types // static void M6() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M6").WithArguments("M6", "I1").WithLocation(18, 17), // (19,25): error CS0111: Type 'I1' already defines a member called 'M7' with the same parameter types // static partial void M7(); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M7").WithArguments("M7", "I1").WithLocation(19, 25), // (20,25): error CS0757: A partial method may not have multiple implementing declarations // static partial void M8() {} Diagnostic(ErrorCode.ERR_PartialMethodOnlyOneActual, "M8").WithLocation(20, 25), // (20,25): error CS0111: Type 'I1' already defines a member called 'M8' with the same parameter types // static partial void M8() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M8").WithArguments("M8", "I1").WithLocation(20, 25), // (21,25): error CS0756: A partial method may not have multiple defining declarations // static partial void M9(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyOneLatent, "M9").WithLocation(21, 25), // (21,25): error CS0111: Type 'I1' already defines a member called 'M9' with the same parameter types // static partial void M9(); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M9").WithArguments("M9", "I1").WithLocation(21, 25), // (22,32): error CS8796: Partial method 'I1.M10()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // static extern partial void M10(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "M10").WithArguments("I1.M10()").WithLocation(22, 32), // (23,35): error CS8793: Partial method 'I1.M11()' must have an implementation part because it has accessibility modifiers. // protected static partial void M11(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M11").WithArguments("I1.M11()").WithLocation(23, 35), // (24,44): error CS8793: Partial method 'I1.M12()' must have an implementation part because it has accessibility modifiers. // protected internal static partial void M12(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M12").WithArguments("I1.M12()").WithLocation(24, 44), // (25,43): error CS8793: Partial method 'I1.M13()' must have an implementation part because it has accessibility modifiers. // private protected static partial void M13(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M13").WithArguments("I1.M13()").WithLocation(25, 43) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularWithExtendedPartialMethods, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (4,24): error CS8794: Partial method 'I1.M1()' must have accessibility modifiers because it has a non-void return type. // static partial int M1(); Diagnostic(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, "M1").WithArguments("I1.M1()").WithLocation(4, 24), // (5,32): error CS8793: Partial method 'I1.M2()' must have an implementation part because it has accessibility modifiers. // public static partial void M2(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M2").WithArguments("I1.M2()").WithLocation(5, 32), // (6,34): error CS8793: Partial method 'I1.M3()' must have an implementation part because it has accessibility modifiers. // internal static partial void M3(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M3").WithArguments("I1.M3()").WithLocation(6, 34), // (7,33): error CS8793: Partial method 'I1.M4()' must have an implementation part because it has accessibility modifiers. // private static partial void M4(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M4").WithArguments("I1.M4()").WithLocation(7, 33), // (8,25): error CS8795: Partial method 'I1.M5(out int)' must have accessibility modifiers because it has 'out' parameters. // static partial void M5(out int x); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M5").WithArguments("I1.M5(out int)").WithLocation(8, 25), // (10,17): error CS8701: Target runtime doesn't support default interface implementation. // static void M7() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M7").WithLocation(10, 17), // (11,25): error CS8701: Target runtime doesn't support default interface implementation. // static partial void M8() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M8").WithLocation(11, 25), // (11,25): error CS0759: No defining declaration found for implementing declaration of partial method 'I1.M8()' // static partial void M8() {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M8").WithArguments("I1.M8()").WithLocation(11, 25), // (18,17): error CS8701: Target runtime doesn't support default interface implementation. // static void M6() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M6").WithLocation(18, 17), // (18,17): error CS0111: Type 'I1' already defines a member called 'M6' with the same parameter types // static void M6() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M6").WithArguments("M6", "I1").WithLocation(18, 17), // (19,25): error CS0111: Type 'I1' already defines a member called 'M7' with the same parameter types // static partial void M7(); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M7").WithArguments("M7", "I1").WithLocation(19, 25), // (20,25): error CS8701: Target runtime doesn't support default interface implementation. // static partial void M8() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M8").WithLocation(20, 25), // (20,25): error CS0757: A partial method may not have multiple implementing declarations // static partial void M8() {} Diagnostic(ErrorCode.ERR_PartialMethodOnlyOneActual, "M8").WithLocation(20, 25), // (20,25): error CS0111: Type 'I1' already defines a member called 'M8' with the same parameter types // static partial void M8() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M8").WithArguments("M8", "I1").WithLocation(20, 25), // (21,25): error CS0756: A partial method may not have multiple defining declarations // static partial void M9(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyOneLatent, "M9").WithLocation(21, 25), // (21,25): error CS0111: Type 'I1' already defines a member called 'M9' with the same parameter types // static partial void M9(); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M9").WithArguments("M9", "I1").WithLocation(21, 25), // (22,32): error CS8701: Target runtime doesn't support default interface implementation. // static extern partial void M10(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M10").WithLocation(22, 32), // (22,32): error CS8796: Partial method 'I1.M10()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // static extern partial void M10(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "M10").WithArguments("I1.M10()").WithLocation(22, 32), // (23,35): error CS8793: Partial method 'I1.M11()' must have an implementation part because it has accessibility modifiers. // protected static partial void M11(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M11").WithArguments("I1.M11()").WithLocation(23, 35), // (24,44): error CS8793: Partial method 'I1.M12()' must have an implementation part because it has accessibility modifiers. // protected internal static partial void M12(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M12").WithArguments("I1.M12()").WithLocation(24, 44), // (25,43): error CS8793: Partial method 'I1.M13()' must have an implementation part because it has accessibility modifiers. // private protected static partial void M13(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M13").WithArguments("I1.M13()").WithLocation(25, 43) ); } [Fact] public void MethodModifiers_27() { var source1 = @" partial interface I1 : I2 { sealed partial void M1(); abstract partial void M2(); virtual partial void M3(); partial void M4(); partial void M5(); partial void M6(); partial void I2.M7(); } partial interface I1 : I2 { sealed partial void M4() {} abstract partial void M5(); virtual partial void M6() {} partial void I2.M7() {} } interface I2 { void M7(); partial void M8(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularWithExtendedPartialMethods, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,25): error CS8796: Partial method 'I1.M1()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // sealed partial void M1(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "M1").WithArguments("I1.M1()").WithLocation(4, 25), // (5,27): error CS0750: A partial method cannot have the 'abstract' modifier // abstract partial void M2(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M2").WithLocation(5, 27), // (6,26): error CS8796: Partial method 'I1.M3()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // virtual partial void M3(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "M3").WithArguments("I1.M3()").WithLocation(6, 26), // (10,21): error CS0754: A partial method may not explicitly implement an interface method // partial void I2.M7(); Diagnostic(ErrorCode.ERR_PartialMethodNotExplicit, "M7").WithLocation(10, 21), // (15,25): error CS8796: Partial method 'I1.M4()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // sealed partial void M4() {} Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "M4").WithArguments("I1.M4()").WithLocation(15, 25), // (15,25): error CS8798: Both partial method declarations must have identical combinations of 'virtual', 'override', 'sealed', and 'new' modifiers. // sealed partial void M4() {} Diagnostic(ErrorCode.ERR_PartialMethodExtendedModDifference, "M4").WithLocation(15, 25), // (16,27): error CS0750: A partial method cannot have the 'abstract' modifier // abstract partial void M5(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M5").WithLocation(16, 27), // (16,27): error CS0756: A partial method may not have multiple defining declarations // abstract partial void M5(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyOneLatent, "M5").WithLocation(16, 27), // (16,27): error CS0111: Type 'I1' already defines a member called 'M5' with the same parameter types // abstract partial void M5(); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M5").WithArguments("M5", "I1").WithLocation(16, 27), // (17,26): error CS8796: Partial method 'I1.M6()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // virtual partial void M6() {} Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "M6").WithArguments("I1.M6()").WithLocation(17, 26), // (17,26): error CS8798: Both partial method declarations must have identical combinations of 'virtual', 'override', 'sealed', and 'new' modifiers. // virtual partial void M6() {} Diagnostic(ErrorCode.ERR_PartialMethodExtendedModDifference, "M6").WithLocation(17, 26), // (19,21): error CS0754: A partial method may not explicitly implement an interface method // partial void I2.M7() {} Diagnostic(ErrorCode.ERR_PartialMethodNotExplicit, "M7").WithLocation(19, 21), // (25,18): error CS0751: A partial method must be declared within a partial type // partial void M8(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M8").WithLocation(25, 18) ); } [Fact] public void MethodModifiers_28() { var source1 = @" partial interface I1 { partial void M1(); class C : I1 { void I1.M1() {} } } public partial interface I1 { partial void M1() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,17): error CS0539: 'I1.C.M1()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M1() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M1").WithArguments("I1.C.M1()").WithLocation(8, 17) ); } [Fact] public void MethodModifiers_29() { var source1 = @" public partial interface I1 { partial void M1(); static partial void M2(); void M3() { new System.Action(M1).Invoke(); new System.Action(M2).Invoke(); } partial static void M4(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,27): error CS0762: Cannot create delegate from method 'I1.M1()' because it is a partial method without an implementing declaration // new System.Action(M1).Invoke(); Diagnostic(ErrorCode.ERR_PartialMethodToDelegate, "M1").WithArguments("I1.M1()").WithLocation(9, 27), // (10,27): error CS0762: Cannot create delegate from method 'I1.M2()' because it is a partial method without an implementing declaration // new System.Action(M2).Invoke(); Diagnostic(ErrorCode.ERR_PartialMethodToDelegate, "M2").WithArguments("I1.M2()").WithLocation(10, 27), // (13,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static void M4(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(13, 5) ); } [Fact] public void MethodModifiers_30() { var source1 = @" public partial interface I1 { static partial void Main(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1) ); } [Fact] public void MethodModifiers_31() { var source1 = @" public partial interface I1 { static partial void M1<T>() where T : struct; static partial void M1<T>() {} static partial void M2(params int[] x); static partial void M2(int[] x) {} static partial void M3(); partial void M3() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,25): error CS0761: Partial method declarations of 'I1.M1<T>()' have inconsistent constraints for type parameter 'T' // static partial void M1<T>() {} Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "M1").WithArguments("I1.M1<T>()", "T").WithLocation(5, 25), // (8,25): error CS0758: Both partial method declarations must use a params parameter or neither may use a params parameter // static partial void M2(int[] x) {} Diagnostic(ErrorCode.ERR_PartialMethodParamsDifference, "M2").WithLocation(8, 25), // (11,18): error CS0763: Both partial method declarations must be static or neither may be static // partial void M3() {} Diagnostic(ErrorCode.ERR_PartialMethodStaticDifference, "M3").WithLocation(11, 18) ); } [Fact] public void MethodModifiers_32() { var source1 = @" partial interface I1 { partial void M1(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics(); var source2 = @" partial interface I1 { partial void M1() {} } "; var compilation2 = CreateCompilation(source1 + source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,18): error CS8701: Target runtime doesn't support default interface implementation. // partial void M1() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(9, 18) ); } [Fact] public void MethodModifiers_33() { var source0 = @" public interface I1 { protected static void M1() { System.Console.WriteLine(""M1""); } protected internal static void M2() { System.Console.WriteLine(""M2""); } private protected static void M3() { System.Console.WriteLine(""M3""); } } "; var source1 = @" class Test1 : I1 { static void Main() { I1.M1(); I1.M2(); I1.M3(); } } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2 M3", symbolValidator: validate, verify: VerifyOnMonoOrCoreClr); validate(compilation1.SourceModule); var source2 = @" class Test1 { static void Main() { I1.M2(); } } "; var compilation2 = CreateCompilation(source0 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M2", verify: VerifyOnMonoOrCoreClr); var compilation3 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); var source3 = @" class Test1 : I1 { static void Main() { I1.M1(); I1.M2(); } } "; var source4 = @" class Test1 { static void Main() { I1.M1(); I1.M2(); I1.M3(); } } "; foreach (var reference in new[] { compilation3.ToMetadataReference(), compilation3.EmitToImageReference() }) { var compilation4 = CreateCompilation(source3, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2", verify: VerifyOnMonoOrCoreClr); var compilation5 = CreateCompilation(source4, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (6,12): error CS0122: 'I1.M1()' is inaccessible due to its protection level // I1.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.M1()").WithLocation(6, 12), // (7,12): error CS0122: 'I1.M2()' is inaccessible due to its protection level // I1.M2(); Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("I1.M2()").WithLocation(7, 12), // (8,12): error CS0122: 'I1.M3()' is inaccessible due to its protection level // I1.M3(); Diagnostic(ErrorCode.ERR_BadAccess, "M3").WithArguments("I1.M3()").WithLocation(8, 12) ); var compilation6 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (8,12): error CS0122: 'I1.M3()' is inaccessible due to its protection level // I1.M3(); Diagnostic(ErrorCode.ERR_BadAccess, "M3").WithArguments("I1.M3()").WithLocation(8, 12) ); } void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); foreach (var tuple in new[] { (name: "M1", access: Accessibility.Protected), (name: "M2", access: Accessibility.ProtectedOrInternal), (name: "M3", access: Accessibility.ProtectedAndInternal) }) { var m1 = i1.GetMember<MethodSymbol>(tuple.name); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.True(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(tuple.access, m1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(m1)); } } } [Fact] public void MethodModifiers_34() { var source1 = @" public interface I1 { protected abstract void M1(); public void M2() => M1(); } "; var source21 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M1(); } public void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source21 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); var expected = new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 15), // (7,11): error CS1540: Cannot access protected member 'I1.M1()' via a qualifier of type 'I1'; the qualifier must be of type 'Test1' (or derived from it) // x.M1(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M1").WithArguments("I1.M1()", "I1", "Test1").WithLocation(7, 11) }; compilation1.VerifyDiagnostics(expected); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.Protected); var source22 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public void M1() { System.Console.WriteLine(""M1""); } } "; compilation1 = CreateCompilation(source22 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.Protected)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.Protected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.Protected); var source3 = @" class Test2 : I1 { } "; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source21, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.Protected); compilation3 = CreateCompilation(source22, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.Protected)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.Protected); var compilation5 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.M1()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M1()").WithLocation(2, 15) ); ValidateI1M1NotImplemented(compilation5, "Test2"); } } [Fact] public void MethodModifiers_35() { var source1 = @" public interface I1 { protected internal abstract void M1(); public void M2() => M1(); } "; var source21 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M1(); } public virtual void M1() { System.Console.WriteLine(""M1""); } } "; var source22 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public virtual void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source21 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 15) ); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.ProtectedOrInternal); compilation1 = CreateCompilation(source21 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.ProtectedOrInternal)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.ProtectedOrInternal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.ProtectedOrInternal); var source3 = @" class Test2 : I1 { } "; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source21, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 15), // (7,11): error CS1540: Cannot access protected member 'I1.M1()' via a qualifier of type 'I1'; the qualifier must be of type 'Test1' (or derived from it) // x.M1(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M1").WithArguments("I1.M1()", "I1", "Test1").WithLocation(7, 11) ); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.ProtectedOrInternal); compilation3 = CreateCompilation(source22, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.ProtectedOrInternal)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.ProtectedOrInternal); var compilation5 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.M1()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M1()").WithLocation(2, 15) ); ValidateI1M1NotImplemented(compilation5, "Test2"); } } [Fact] public void MethodModifiers_36() { var source1 = @" public interface I1 { private protected abstract void M1(); public void M2() => M1(); } "; var source21 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M1(); } public void M1() { System.Console.WriteLine(""M1""); } } "; var source22 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source21 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 15), // (7,11): error CS1540: Cannot access protected member 'I1.M1()' via a qualifier of type 'I1'; the qualifier must be of type 'Test1' (or derived from it) // x.M1(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M1").WithArguments("I1.M1()", "I1", "Test1").WithLocation(7, 11) ); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.ProtectedAndInternal); compilation1 = CreateCompilation(source22 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.ProtectedAndInternal)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation1.SourceModule, Accessibility.ProtectedAndInternal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.ProtectedAndInternal); var source3 = @" class Test2 : I1 { } "; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source21, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 15), // (7,11): error CS0122: 'I1.M1()' is inaccessible due to its protection level // x.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.M1()").WithLocation(7, 11) ); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.ProtectedAndInternal); compilation3 = CreateCompilation(source22, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersImplicit_10(m, Accessibility.ProtectedAndInternal)).VerifyDiagnostics(); ValidateMethodModifiersImplicit_10(compilation3.SourceModule, Accessibility.ProtectedAndInternal); var compilation5 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.M1()' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.M1()").WithLocation(2, 15) ); ValidateI1M1NotImplemented(compilation5, "Test2"); } } [Fact] public void MethodModifiers_37() { var source1 = @" public interface I1 { protected abstract void M1(); static void M2(I1 x) => x.M1(); } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); I1.M2(x); } void I1.M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersExplicit_10(m, Accessibility.Protected)); ValidateMethodModifiersExplicit_10(compilation1.SourceModule, Accessibility.Protected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.Protected); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.StandardLatest); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: "M1", symbolValidator: (m) => ValidateMethodModifiersExplicit_10(m, Accessibility.Protected)); ValidateMethodModifiersExplicit_10(compilation3.SourceModule, Accessibility.Protected); } } [Fact] public void MethodModifiers_38() { var source1 = @" public interface I1 { protected internal abstract void M1(); static void M2(I1 x) => x.M1(); } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); I1.M2(x); } void I1.M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersExplicit_10(m, Accessibility.ProtectedOrInternal)); ValidateMethodModifiersExplicit_10(compilation1.SourceModule, Accessibility.ProtectedOrInternal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.ProtectedOrInternal); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.StandardLatest); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: "M1", symbolValidator: (m) => ValidateMethodModifiersExplicit_10(m, Accessibility.ProtectedOrInternal)); ValidateMethodModifiersExplicit_10(compilation3.SourceModule, Accessibility.ProtectedOrInternal); } } [Fact] public void MethodModifiers_39() { var source1 = @" public interface I1 { private protected abstract void M1(); static void M2(I1 x) => x.M1(); } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); I1.M2(x); } void I1.M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateMethodModifiersExplicit_10(m, Accessibility.ProtectedAndInternal)); ValidateMethodModifiersExplicit_10(compilation1.SourceModule, Accessibility.ProtectedAndInternal); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); ValidateMethodModifiers_10(compilation2.GetTypeByMetadataName("I1").GetMember<MethodSymbol>("M1"), Accessibility.ProtectedAndInternal); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.StandardLatest); compilation3.VerifyDiagnostics( // (10,13): error CS0122: 'I1.M1()' is inaccessible due to its protection level // void I1.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.M1()").WithLocation(10, 13) ); ValidateMethodModifiersExplicit_10(compilation3.SourceModule, Accessibility.ProtectedAndInternal); } } [Fact] public void MethodModifiers_40() { var source1 = @" public interface I1 { protected abstract void M1(); public void M2() => M1(); } public class Test2 : I1 { void I1.M1() { } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.M2(); } public void M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.Protected, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void MethodModifiers_41() { var source1 = @" public interface I1 { protected internal abstract void M1(); public void M2() => M1(); } public class Test2 : I1 { void I1.M1() { } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.M2(); } public void M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.ProtectedOrInternal, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void MethodModifiers_42() { var source1 = @" public interface I1 { private protected abstract void M1(); public void M2() => M1(); } public class Test2 : I1 { void I1.M1() { } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.M2(); } public virtual void M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodModifiers_10_02(source1, source2, Accessibility.ProtectedAndInternal, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.M1()", "Test1.M1()", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void MethodModifiers_43() { var source1 = @" public interface I1 { protected void M1() { System.Console.WriteLine(""M1""); } void M2() {M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate1); validate1(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); validateMethod(m1); } foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate1); validate1(compilation3.SourceModule); } void validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var m1 = i1.GetMember<MethodSymbol>("M1"); validateMethod(m1); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); } void validateMethod(MethodSymbol m1) { Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Protected, m1.DeclaredAccessibility); } } [Fact] public void MethodModifiers_44() { var source1 = @" public interface I1 { protected internal void M1() { System.Console.WriteLine(""M1""); } void M2() {M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate1); validate1(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); validateMethod(m1); } foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate1); validate1(compilation3.SourceModule); } void validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var m1 = i1.GetMember<MethodSymbol>("M1"); validateMethod(m1); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); } void validateMethod(MethodSymbol m1) { Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, m1.DeclaredAccessibility); } } [Fact] public void MethodModifiers_45() { var source1 = @" public interface I1 { private protected void M1() { System.Console.WriteLine(""M1""); } void M2() {M1();} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate1); validate1(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var m1 = i1.GetMember<MethodSymbol>("M1"); validateMethod(m1); } foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate1); validate1(compilation3.SourceModule); } void validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var m1 = i1.GetMember<MethodSymbol>("M1"); validateMethod(m1); Assert.Same(m1, test1.FindImplementationForInterfaceMember(m1)); } void validateMethod(MethodSymbol m1) { Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, m1.DeclaredAccessibility); } } [Fact] public void ImplicitThisIsAllowed_03() { var source1 = @" public interface I1 { public int F1; void M1() { System.Console.WriteLine(""I1.M1""); } int P1 { get { System.Console.WriteLine(""I1.get_P1""); return 0; } set => System.Console.WriteLine(""I1.set_P1""); } event System.Action E1 { add => System.Console.WriteLine(""I1.add_E1""); remove => System.Console.WriteLine(""I1.remove_E1""); } public interface I2 : I1 { void M2() { M1(); P1 = P1; E1 += null; E1 -= null; F1 = 0; } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,16): error CS0525: Interfaces cannot contain fields // public int F1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F1").WithLocation(4, 16) ); } [Fact] public void ImplicitThisIsAllowed_04() { var source1 = @" public interface I1 { public int F1; void M1() { System.Console.WriteLine(""I1.M1""); } int P1 { get { System.Console.WriteLine(""I1.get_P1""); return 0; } set => System.Console.WriteLine(""I1.set_P1""); } event System.Action E1 { add => System.Console.WriteLine(""I1.add_E1""); remove => System.Console.WriteLine(""I1.remove_E1""); } public interface I2 { void M2() { M1(); P1 = P1; E1 += null; E1 -= null; F1 = 0; } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,16): error CS0525: Interfaces cannot contain fields // public int F1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F1").WithLocation(4, 16), // (31,13): error CS0120: An object reference is required for the non-static field, method, or property 'I1.M1()' // M1(); Diagnostic(ErrorCode.ERR_ObjectRequired, "M1").WithArguments("I1.M1()").WithLocation(31, 13), // (32,13): error CS0120: An object reference is required for the non-static field, method, or property 'I1.P1' // P1 = P1; Diagnostic(ErrorCode.ERR_ObjectRequired, "P1").WithArguments("I1.P1").WithLocation(32, 13), // (32,18): error CS0120: An object reference is required for the non-static field, method, or property 'I1.P1' // P1 = P1; Diagnostic(ErrorCode.ERR_ObjectRequired, "P1").WithArguments("I1.P1").WithLocation(32, 18), // (33,13): error CS0120: An object reference is required for the non-static field, method, or property 'I1.E1' // E1 += null; Diagnostic(ErrorCode.ERR_ObjectRequired, "E1").WithArguments("I1.E1").WithLocation(33, 13), // (34,13): error CS0120: An object reference is required for the non-static field, method, or property 'I1.E1' // E1 -= null; Diagnostic(ErrorCode.ERR_ObjectRequired, "E1").WithArguments("I1.E1").WithLocation(34, 13), // (35,13): error CS0120: An object reference is required for the non-static field, method, or property 'I1.F1' // F1 = 0; Diagnostic(ErrorCode.ERR_ObjectRequired, "F1").WithArguments("I1.F1").WithLocation(35, 13) ); } [Fact] public void ImplicitThisIsAllowed_05() { var source1 = @" public class C1 { public int F1; void M1() { System.Console.WriteLine(""I1.M1""); } int P1 { get { System.Console.WriteLine(""I1.get_P1""); return 0; } set => System.Console.WriteLine(""I1.set_P1""); } event System.Action E1 { add => System.Console.WriteLine(""I1.add_E1""); remove => System.Console.WriteLine(""I1.remove_E1""); } public interface I2 { void M2() { M1(); P1 = P1; E1 += null; E1 -= null; F1 = 0; } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (31,13): error CS0120: An object reference is required for the non-static field, method, or property 'C1.M1()' // M1(); Diagnostic(ErrorCode.ERR_ObjectRequired, "M1").WithArguments("C1.M1()").WithLocation(31, 13), // (32,13): error CS0120: An object reference is required for the non-static field, method, or property 'C1.P1' // P1 = P1; Diagnostic(ErrorCode.ERR_ObjectRequired, "P1").WithArguments("C1.P1").WithLocation(32, 13), // (32,18): error CS0120: An object reference is required for the non-static field, method, or property 'C1.P1' // P1 = P1; Diagnostic(ErrorCode.ERR_ObjectRequired, "P1").WithArguments("C1.P1").WithLocation(32, 18), // (33,13): error CS0120: An object reference is required for the non-static field, method, or property 'C1.E1' // E1 += null; Diagnostic(ErrorCode.ERR_ObjectRequired, "E1").WithArguments("C1.E1").WithLocation(33, 13), // (34,13): error CS0120: An object reference is required for the non-static field, method, or property 'C1.E1' // E1 -= null; Diagnostic(ErrorCode.ERR_ObjectRequired, "E1").WithArguments("C1.E1").WithLocation(34, 13), // (35,13): error CS0120: An object reference is required for the non-static field, method, or property 'C1.F1' // F1 = 0; Diagnostic(ErrorCode.ERR_ObjectRequired, "F1").WithArguments("C1.F1").WithLocation(35, 13) ); } [Fact] public void PropertyModifiers_01() { var source1 = @" public interface I1 { public int P01 {get; set;} protected int P02 {get;} protected internal int P03 {set;} internal int P04 {get;} private int P05 {set;} static int P06 {get;} virtual int P07 {set;} sealed int P08 {get;} override int P09 {set;} abstract int P10 {get;} extern int P11 {get; set;} int P12 { public get; set;} int P13 { get; protected set;} int P14 { protected internal get; set;} int P15 { get; internal set;} int P16 { private get; set;} int P17 { private get;} private protected int P18 {get;} int P19 { get; private protected set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (8,22): error CS0501: 'I1.P05.set' must declare a body because it is not marked abstract, extern, or partial // private int P05 {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.P05.set").WithLocation(8, 22), // (10,22): error CS0501: 'I1.P07.set' must declare a body because it is not marked abstract, extern, or partial // virtual int P07 {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.P07.set").WithLocation(10, 22), // (11,21): error CS0501: 'I1.P08.get' must declare a body because it is not marked abstract, extern, or partial // sealed int P08 {get;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.P08.get").WithLocation(11, 21), // (12,18): error CS0106: The modifier 'override' is not valid for this item // override int P09 {set;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "P09").WithArguments("override").WithLocation(12, 18), // (16,22): error CS0273: The accessibility modifier of the 'I1.P12.get' accessor must be more restrictive than the property or indexer 'I1.P12' // int P12 { public get; set;} Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("I1.P12.get", "I1.P12").WithLocation(16, 22), // (20,23): error CS0442: 'I1.P16.get': abstract properties cannot have private accessors // int P16 { private get; set;} Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I1.P16.get").WithLocation(20, 23), // (21,9): error CS0276: 'I1.P17': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int P17 { private get;} Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P17").WithArguments("I1.P17").WithLocation(21, 9), // (14,21): warning CS0626: Method, operator, or accessor 'I1.P11.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.P11.get").WithLocation(14, 21), // (14,26): warning CS0626: Method, operator, or accessor 'I1.P11.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I1.P11.set").WithLocation(14, 26) ); ValidateSymbolsPropertyModifiers_01(compilation1); } private static void ValidateSymbolsPropertyModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var p01 = i1.GetMember<PropertySymbol>("P01"); Assert.True(p01.IsAbstract); Assert.False(p01.IsVirtual); Assert.False(p01.IsSealed); Assert.False(p01.IsStatic); Assert.False(p01.IsExtern); Assert.False(p01.IsOverride); Assert.Equal(Accessibility.Public, p01.DeclaredAccessibility); ValidateP01Accessor(p01.GetMethod); ValidateP01Accessor(p01.SetMethod); void ValidateP01Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } var p02 = i1.GetMember<PropertySymbol>("P02"); var p02get = p02.GetMethod; Assert.True(p02.IsAbstract); Assert.False(p02.IsVirtual); Assert.False(p02.IsSealed); Assert.False(p02.IsStatic); Assert.False(p02.IsExtern); Assert.False(p02.IsOverride); Assert.Equal(Accessibility.Protected, p02.DeclaredAccessibility); Assert.True(p02get.IsAbstract); Assert.False(p02get.IsVirtual); Assert.True(p02get.IsMetadataVirtual()); Assert.False(p02get.IsSealed); Assert.False(p02get.IsStatic); Assert.False(p02get.IsExtern); Assert.False(p02get.IsAsync); Assert.False(p02get.IsOverride); Assert.Equal(Accessibility.Protected, p02get.DeclaredAccessibility); var p03 = i1.GetMember<PropertySymbol>("P03"); var p03set = p03.SetMethod; Assert.True(p03.IsAbstract); Assert.False(p03.IsVirtual); Assert.False(p03.IsSealed); Assert.False(p03.IsStatic); Assert.False(p03.IsExtern); Assert.False(p03.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, p03.DeclaredAccessibility); Assert.True(p03set.IsAbstract); Assert.False(p03set.IsVirtual); Assert.True(p03set.IsMetadataVirtual()); Assert.False(p03set.IsSealed); Assert.False(p03set.IsStatic); Assert.False(p03set.IsExtern); Assert.False(p03set.IsAsync); Assert.False(p03set.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, p03set.DeclaredAccessibility); var p04 = i1.GetMember<PropertySymbol>("P04"); var p04get = p04.GetMethod; Assert.True(p04.IsAbstract); Assert.False(p04.IsVirtual); Assert.False(p04.IsSealed); Assert.False(p04.IsStatic); Assert.False(p04.IsExtern); Assert.False(p04.IsOverride); Assert.Equal(Accessibility.Internal, p04.DeclaredAccessibility); Assert.True(p04get.IsAbstract); Assert.False(p04get.IsVirtual); Assert.True(p04get.IsMetadataVirtual()); Assert.False(p04get.IsSealed); Assert.False(p04get.IsStatic); Assert.False(p04get.IsExtern); Assert.False(p04get.IsAsync); Assert.False(p04get.IsOverride); Assert.Equal(Accessibility.Internal, p04get.DeclaredAccessibility); var p05 = i1.GetMember<PropertySymbol>("P05"); var p05set = p05.SetMethod; Assert.False(p05.IsAbstract); Assert.False(p05.IsVirtual); Assert.False(p05.IsSealed); Assert.False(p05.IsStatic); Assert.False(p05.IsExtern); Assert.False(p05.IsOverride); Assert.Equal(Accessibility.Private, p05.DeclaredAccessibility); Assert.False(p05set.IsAbstract); Assert.False(p05set.IsVirtual); Assert.False(p05set.IsMetadataVirtual()); Assert.False(p05set.IsSealed); Assert.False(p05set.IsStatic); Assert.False(p05set.IsExtern); Assert.False(p05set.IsAsync); Assert.False(p05set.IsOverride); Assert.Equal(Accessibility.Private, p05set.DeclaredAccessibility); var p06 = i1.GetMember<PropertySymbol>("P06"); var p06get = p06.GetMethod; Assert.False(p06.IsAbstract); Assert.False(p06.IsVirtual); Assert.False(p06.IsSealed); Assert.True(p06.IsStatic); Assert.False(p06.IsExtern); Assert.False(p06.IsOverride); Assert.Equal(Accessibility.Public, p06.DeclaredAccessibility); Assert.False(p06get.IsAbstract); Assert.False(p06get.IsVirtual); Assert.False(p06get.IsMetadataVirtual()); Assert.False(p06get.IsSealed); Assert.True(p06get.IsStatic); Assert.False(p06get.IsExtern); Assert.False(p06get.IsAsync); Assert.False(p06get.IsOverride); Assert.Equal(Accessibility.Public, p06get.DeclaredAccessibility); var p07 = i1.GetMember<PropertySymbol>("P07"); var p07set = p07.SetMethod; Assert.False(p07.IsAbstract); Assert.True(p07.IsVirtual); Assert.False(p07.IsSealed); Assert.False(p07.IsStatic); Assert.False(p07.IsExtern); Assert.False(p07.IsOverride); Assert.Equal(Accessibility.Public, p07.DeclaredAccessibility); Assert.False(p07set.IsAbstract); Assert.True(p07set.IsVirtual); Assert.True(p07set.IsMetadataVirtual()); Assert.False(p07set.IsSealed); Assert.False(p07set.IsStatic); Assert.False(p07set.IsExtern); Assert.False(p07set.IsAsync); Assert.False(p07set.IsOverride); Assert.Equal(Accessibility.Public, p07set.DeclaredAccessibility); var p08 = i1.GetMember<PropertySymbol>("P08"); var p08get = p08.GetMethod; Assert.False(p08.IsAbstract); Assert.False(p08.IsVirtual); Assert.False(p08.IsSealed); Assert.False(p08.IsStatic); Assert.False(p08.IsExtern); Assert.False(p08.IsOverride); Assert.Equal(Accessibility.Public, p08.DeclaredAccessibility); Assert.False(p08get.IsAbstract); Assert.False(p08get.IsVirtual); Assert.False(p08get.IsMetadataVirtual()); Assert.False(p08get.IsSealed); Assert.False(p08get.IsStatic); Assert.False(p08get.IsExtern); Assert.False(p08get.IsAsync); Assert.False(p08get.IsOverride); Assert.Equal(Accessibility.Public, p08get.DeclaredAccessibility); var p09 = i1.GetMember<PropertySymbol>("P09"); var p09set = p09.SetMethod; Assert.True(p09.IsAbstract); Assert.False(p09.IsVirtual); Assert.False(p09.IsSealed); Assert.False(p09.IsStatic); Assert.False(p09.IsExtern); Assert.False(p09.IsOverride); Assert.Equal(Accessibility.Public, p09.DeclaredAccessibility); Assert.True(p09set.IsAbstract); Assert.False(p09set.IsVirtual); Assert.True(p09set.IsMetadataVirtual()); Assert.False(p09set.IsSealed); Assert.False(p09set.IsStatic); Assert.False(p09set.IsExtern); Assert.False(p09set.IsAsync); Assert.False(p09set.IsOverride); Assert.Equal(Accessibility.Public, p09set.DeclaredAccessibility); var p10 = i1.GetMember<PropertySymbol>("P10"); var p10get = p10.GetMethod; Assert.True(p10.IsAbstract); Assert.False(p10.IsVirtual); Assert.False(p10.IsSealed); Assert.False(p10.IsStatic); Assert.False(p10.IsExtern); Assert.False(p10.IsOverride); Assert.Equal(Accessibility.Public, p10.DeclaredAccessibility); Assert.True(p10get.IsAbstract); Assert.False(p10get.IsVirtual); Assert.True(p10get.IsMetadataVirtual()); Assert.False(p10get.IsSealed); Assert.False(p10get.IsStatic); Assert.False(p10get.IsExtern); Assert.False(p10get.IsAsync); Assert.False(p10get.IsOverride); Assert.Equal(Accessibility.Public, p10get.DeclaredAccessibility); var p11 = i1.GetMember<PropertySymbol>("P11"); Assert.False(p11.IsAbstract); Assert.True(p11.IsVirtual); Assert.False(p11.IsSealed); Assert.False(p11.IsStatic); Assert.True(p11.IsExtern); Assert.False(p11.IsOverride); Assert.Equal(Accessibility.Public, p11.DeclaredAccessibility); ValidateP11Accessor(p11.GetMethod); ValidateP11Accessor(p11.SetMethod); void ValidateP11Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } var p12 = i1.GetMember<PropertySymbol>("P12"); Assert.True(p12.IsAbstract); Assert.False(p12.IsVirtual); Assert.False(p12.IsSealed); Assert.False(p12.IsStatic); Assert.False(p12.IsExtern); Assert.False(p12.IsOverride); Assert.Equal(Accessibility.Public, p12.DeclaredAccessibility); ValidateP12Accessor(p12.GetMethod); ValidateP12Accessor(p12.SetMethod); void ValidateP12Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } var p13 = i1.GetMember<PropertySymbol>("P13"); Assert.True(p13.IsAbstract); Assert.False(p13.IsVirtual); Assert.False(p13.IsSealed); Assert.False(p13.IsStatic); Assert.False(p13.IsExtern); Assert.False(p13.IsOverride); Assert.Equal(Accessibility.Public, p13.DeclaredAccessibility); ValidateP13Accessor(p13.GetMethod, Accessibility.Public); ValidateP13Accessor(p13.SetMethod, Accessibility.Protected); void ValidateP13Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p14 = i1.GetMember<PropertySymbol>("P14"); Assert.True(p14.IsAbstract); Assert.False(p14.IsVirtual); Assert.False(p14.IsSealed); Assert.False(p14.IsStatic); Assert.False(p14.IsExtern); Assert.False(p14.IsOverride); Assert.Equal(Accessibility.Public, p14.DeclaredAccessibility); ValidateP14Accessor(p14.GetMethod, Accessibility.ProtectedOrInternal); ValidateP14Accessor(p14.SetMethod, Accessibility.Public); void ValidateP14Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p15 = i1.GetMember<PropertySymbol>("P15"); Assert.True(p15.IsAbstract); Assert.False(p15.IsVirtual); Assert.False(p15.IsSealed); Assert.False(p15.IsStatic); Assert.False(p15.IsExtern); Assert.False(p15.IsOverride); Assert.Equal(Accessibility.Public, p15.DeclaredAccessibility); ValidateP15Accessor(p15.GetMethod, Accessibility.Public); ValidateP15Accessor(p15.SetMethod, Accessibility.Internal); void ValidateP15Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p16 = i1.GetMember<PropertySymbol>("P16"); Assert.True(p16.IsAbstract); Assert.False(p16.IsVirtual); Assert.False(p16.IsSealed); Assert.False(p16.IsStatic); Assert.False(p16.IsExtern); Assert.False(p16.IsOverride); Assert.Equal(Accessibility.Public, p16.DeclaredAccessibility); ValidateP16Accessor(p16.GetMethod, Accessibility.Private); ValidateP16Accessor(p16.SetMethod, Accessibility.Public); void ValidateP16Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p17 = i1.GetMember<PropertySymbol>("P17"); var p17get = p17.GetMethod; Assert.True(p17.IsAbstract); Assert.False(p17.IsVirtual); Assert.False(p17.IsSealed); Assert.False(p17.IsStatic); Assert.False(p17.IsExtern); Assert.False(p17.IsOverride); Assert.Equal(Accessibility.Public, p17.DeclaredAccessibility); Assert.True(p17get.IsAbstract); Assert.False(p17get.IsVirtual); Assert.True(p17get.IsMetadataVirtual()); Assert.False(p17get.IsSealed); Assert.False(p17get.IsStatic); Assert.False(p17get.IsExtern); Assert.False(p17get.IsAsync); Assert.False(p17get.IsOverride); Assert.Equal(Accessibility.Private, p17get.DeclaredAccessibility); var p18 = i1.GetMember<PropertySymbol>("P18"); var p18get = p18.GetMethod; Assert.True(p18.IsAbstract); Assert.False(p18.IsVirtual); Assert.False(p18.IsSealed); Assert.False(p18.IsStatic); Assert.False(p18.IsExtern); Assert.False(p18.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, p18.DeclaredAccessibility); Assert.True(p18get.IsAbstract); Assert.False(p18get.IsVirtual); Assert.True(p18get.IsMetadataVirtual()); Assert.False(p18get.IsSealed); Assert.False(p18get.IsStatic); Assert.False(p18get.IsExtern); Assert.False(p18get.IsAsync); Assert.False(p18get.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, p18get.DeclaredAccessibility); var p19 = i1.GetMember<PropertySymbol>("P19"); Assert.True(p19.IsAbstract); Assert.False(p19.IsVirtual); Assert.False(p19.IsSealed); Assert.False(p19.IsStatic); Assert.False(p19.IsExtern); Assert.False(p19.IsOverride); Assert.Equal(Accessibility.Public, p19.DeclaredAccessibility); ValidateP13Accessor(p19.GetMethod, Accessibility.Public); ValidateP13Accessor(p19.SetMethod, Accessibility.ProtectedAndInternal); } [Fact] public void PropertyModifiers_02() { var source1 = @" public interface I1 { public int P01 {get; set;} protected int P02 {get;} protected internal int P03 {set;} internal int P04 {get;} private int P05 {set;} static int P06 {get;} virtual int P07 {set;} sealed int P08 {get;} override int P09 {set;} abstract int P10 {get;} extern int P11 {get; set;} int P12 { public get; set;} int P13 { get; protected set;} int P14 { protected internal get; set;} int P15 { get; internal set;} int P16 { private get; set;} int P17 { private get;} private protected int P18 {get;} int P19 { get; private protected set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,16): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public int P01 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("public", "7.3", "8.0").WithLocation(4, 16), // (5,19): error CS8703: The modifier 'protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // protected int P02 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P02").WithArguments("protected", "7.3", "8.0").WithLocation(5, 19), // (6,28): error CS8703: The modifier 'protected internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // protected internal int P03 {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P03").WithArguments("protected internal", "7.3", "8.0").WithLocation(6, 28), // (7,18): error CS8503: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal int P04 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P04").WithArguments("internal", "7.3", "8.0").WithLocation(7, 18), // (8,17): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private int P05 {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P05").WithArguments("private", "7.3", "8.0").WithLocation(8, 17), // (8,22): error CS0501: 'I1.P05.set' must declare a body because it is not marked abstract, extern, or partial // private int P05 {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.P05.set").WithLocation(8, 22), // (9,16): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static int P06 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P06").WithArguments("static", "7.3", "8.0").WithLocation(9, 16), // (10,17): error CS8503: The modifier 'virtual' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual int P07 {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P07").WithArguments("virtual", "7.3", "8.0").WithLocation(10, 17), // (10,22): error CS0501: 'I1.P07.set' must declare a body because it is not marked abstract, extern, or partial // virtual int P07 {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.P07.set").WithLocation(10, 22), // (11,16): error CS8503: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // sealed int P08 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P08").WithArguments("sealed", "7.3", "8.0").WithLocation(11, 16), // (11,21): error CS0501: 'I1.P08.get' must declare a body because it is not marked abstract, extern, or partial // sealed int P08 {get;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.P08.get").WithLocation(11, 21), // (12,18): error CS0106: The modifier 'override' is not valid for this item // override int P09 {set;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "P09").WithArguments("override").WithLocation(12, 18), // (13,18): error CS8503: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // abstract int P10 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P10").WithArguments("abstract", "7.3", "8.0").WithLocation(13, 18), // (14,16): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern int P11 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P11").WithArguments("extern", "7.3", "8.0").WithLocation(14, 16), // (16,22): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // int P12 { public get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("public", "7.3", "8.0").WithLocation(16, 22), // (16,22): error CS0273: The accessibility modifier of the 'I1.P12.get' accessor must be more restrictive than the property or indexer 'I1.P12' // int P12 { public get; set;} Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("I1.P12.get", "I1.P12").WithLocation(16, 22), // (17,30): error CS8703: The modifier 'protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // int P13 { get; protected set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("protected", "7.3", "8.0").WithLocation(17, 30), // (18,34): error CS8703: The modifier 'protected internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // int P14 { protected internal get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("protected internal", "7.3", "8.0").WithLocation(18, 34), // (19,29): error CS8503: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // int P15 { get; internal set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("internal", "7.3", "8.0").WithLocation(19, 29), // (20,23): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // int P16 { private get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("private", "7.3", "8.0").WithLocation(20, 23), // (20,23): error CS0442: 'I1.P16.get': abstract properties cannot have private accessors // int P16 { private get; set;} Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I1.P16.get").WithLocation(20, 23), // (21,23): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // int P17 { private get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("private", "7.3", "8.0").WithLocation(21, 23), // (21,9): error CS0276: 'I1.P17': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int P17 { private get;} Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P17").WithArguments("I1.P17").WithLocation(21, 9), // (23,27): error CS8703: The modifier 'private protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private protected int P18 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P18").WithArguments("private protected", "7.3", "8.0").WithLocation(23, 27), // (24,38): error CS8703: The modifier 'private protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // int P19 { get; private protected set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("private protected", "7.3", "8.0").WithLocation(24, 38), // (14,21): warning CS0626: Method, operator, or accessor 'I1.P11.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.P11.get").WithLocation(14, 21), // (14,26): warning CS0626: Method, operator, or accessor 'I1.P11.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I1.P11.set").WithLocation(14, 26) ); ValidateSymbolsPropertyModifiers_01(compilation1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (5,19): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected int P02 {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P02").WithLocation(5, 19), // (6,28): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal int P03 {set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P03").WithLocation(6, 28), // (8,22): error CS0501: 'I1.P05.set' must declare a body because it is not marked abstract, extern, or partial // private int P05 {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.P05.set").WithLocation(8, 22), // (9,21): error CS8701: Target runtime doesn't support default interface implementation. // static int P06 {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(9, 21), // (10,22): error CS0501: 'I1.P07.set' must declare a body because it is not marked abstract, extern, or partial // virtual int P07 {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.P07.set").WithLocation(10, 22), // (11,21): error CS0501: 'I1.P08.get' must declare a body because it is not marked abstract, extern, or partial // sealed int P08 {get;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.P08.get").WithLocation(11, 21), // (12,18): error CS0106: The modifier 'override' is not valid for this item // override int P09 {set;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "P09").WithArguments("override").WithLocation(12, 18), // (14,21): error CS8701: Target runtime doesn't support default interface implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(14, 21), // (14,21): warning CS0626: Method, operator, or accessor 'I1.P11.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.P11.get").WithLocation(14, 21), // (14,26): error CS8701: Target runtime doesn't support default interface implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(14, 26), // (14,26): warning CS0626: Method, operator, or accessor 'I1.P11.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P11 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I1.P11.set").WithLocation(14, 26), // (16,22): error CS0273: The accessibility modifier of the 'I1.P12.get' accessor must be more restrictive than the property or indexer 'I1.P12' // int P12 { public get; set;} Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("I1.P12.get", "I1.P12").WithLocation(16, 22), // (17,30): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // int P13 { get; protected set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "set").WithLocation(17, 30), // (18,34): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // int P14 { protected internal get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "get").WithLocation(18, 34), // (20,23): error CS0442: 'I1.P16.get': abstract properties cannot have private accessors // int P16 { private get; set;} Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I1.P16.get").WithLocation(20, 23), // (21,9): error CS0276: 'I1.P17': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int P17 { private get;} Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P17").WithArguments("I1.P17").WithLocation(21, 9), // (23,27): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected int P18 {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P18").WithLocation(23, 27), // (24,38): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // int P19 { get; private protected set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "set").WithLocation(24, 38) ); ValidateSymbolsPropertyModifiers_01(compilation2); } [Fact] public void PropertyModifiers_03() { ValidatePropertyImplementation_101(@" public interface I1 { public virtual int P1 { get { System.Console.WriteLine(""get P1""); return 0; } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "); ValidatePropertyImplementation_101(@" public interface I1 { public virtual int P1 { get => Test1.GetP1(); } } class Test1 : I1 { public static int GetP1() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "); ValidatePropertyImplementation_101(@" public interface I1 { public virtual int P1 => Test1.GetP1(); } class Test1 : I1 { public static int GetP1() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "); ValidatePropertyImplementation_102(@" public interface I1 { public virtual int P1 { get { System.Console.WriteLine(""get P1""); return 0; } set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.P1 = i1.P1; } } "); ValidatePropertyImplementation_102(@" public interface I1 { public virtual int P1 { get => Test1.GetP1(); set => System.Console.WriteLine(""set P1""); } } class Test1 : I1 { public static int GetP1() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); i1.P1 = i1.P1; } } "); ValidatePropertyImplementation_103(@" public interface I1 { public virtual int P1 { set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } } "); ValidatePropertyImplementation_103(@" public interface I1 { public virtual int P1 { set => System.Console.WriteLine(""set P1""); } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } } "); } [Fact] public void PropertyModifiers_04() { var source1 = @" public interface I1 { public virtual int P1 { get; } = 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics( // (4,24): error CS8053: Instance properties in interfaces cannot have initializers. // public virtual int P1 { get; } = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P1").WithArguments("I1.P1").WithLocation(4, 24), // (4,29): error CS0501: 'I1.P1.get' must declare a body because it is not marked abstract, extern, or partial // public virtual int P1 { get; } = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.P1.get").WithLocation(4, 29) ); ValidatePropertyModifiers_04(compilation1, "P1"); } private static void ValidatePropertyModifiers_04(CSharpCompilation compilation1, string propertyName) { var i1 = compilation1.GlobalNamespace.GetTypeMember("I1"); var p1 = i1.GetMember<PropertySymbol>(propertyName); var p1get = p1.GetMethod; Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.False(p1get.IsAbstract); Assert.True(p1get.IsVirtual); Assert.True(p1get.IsMetadataVirtual()); Assert.False(p1get.IsSealed); Assert.False(p1get.IsStatic); Assert.False(p1get.IsExtern); Assert.False(p1get.IsAsync); Assert.False(p1get.IsOverride); Assert.Equal(Accessibility.Public, p1get.DeclaredAccessibility); } [Fact] public void PropertyModifiers_05() { var source1 = @" public interface I1 { public abstract int P1 {get; set;} } public interface I2 { int P2 {get; set;} } class Test1 : I1 { public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set => System.Console.WriteLine(""set_P1""); } } class Test2 : I2 { public int P2 { get { System.Console.WriteLine(""get_P2""); return 0; } set => System.Console.WriteLine(""set_P2""); } static void Main() { I1 x = new Test1(); x.P1 = x.P1; I2 y = new Test2(); y.P2 = y.P2; } } "; ValidatePropertyModifiers_05(source1); } private void ValidatePropertyModifiers_05(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: @"get_P1 set_P1 get_P2 set_P2", symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { for (int i = 1; i <= 2; i++) { var test1 = m.GlobalNamespace.GetTypeMember("Test" + i); var i1 = m.GlobalNamespace.GetTypeMember("I" + i); var p1 = GetSingleProperty(i1); var test1P1 = GetSingleProperty(test1); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Same(test1P1, test1.FindImplementationForInterfaceMember(p1)); ValidateAccessor(p1.GetMethod, test1P1.GetMethod); ValidateAccessor(p1.SetMethod, test1P1.SetMethod); void ValidateAccessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(implementation, test1.FindImplementationForInterfaceMember(accessor)); } } } } private static PropertySymbol GetSingleProperty(NamedTypeSymbol container) { return container.GetMembers().OfType<PropertySymbol>().Single(); } private static PropertySymbol GetSingleProperty(CSharpCompilation compilation, string containerName) { return GetSingleProperty(compilation.GetTypeByMetadataName(containerName)); } private static PropertySymbol GetSingleProperty(ModuleSymbol m, string containerName) { return GetSingleProperty(m.GlobalNamespace.GetTypeMember(containerName)); } [Fact] public void PropertyModifiers_06() { var source1 = @" public interface I1 { public abstract int P1 {get; set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3); compilation1.VerifyDiagnostics( // (4,25): error CS8503: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract int P1 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("abstract", "7.3", "8.0").WithLocation(4, 25), // (4,25): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract int P1 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("public", "7.3", "8.0").WithLocation(4, 25) ); ValidatePropertyModifiers_06(compilation1, "P1"); } private static void ValidatePropertyModifiers_06(CSharpCompilation compilation1, string propertyName) { var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMember<PropertySymbol>(propertyName); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); ValidateAccessor(p1.GetMethod); ValidateAccessor(p1.SetMethod); void ValidateAccessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } } [Fact] public void PropertyModifiers_07() { var source1 = @" public interface I1 { public static int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } internal static int P2 { get { System.Console.WriteLine(""get_P2""); return P3; } set { System.Console.WriteLine(""set_P2""); P3 = value; } } private static int P3 { get => Test1.GetP3(); set => System.Console.WriteLine(""set_P3""); } internal static int P4 => Test1.GetP4(); internal static int P5 { get { System.Console.WriteLine(""get_P5""); return 0; } } internal static int P6 { get => Test1.GetP6(); } internal static int P7 { set { System.Console.WriteLine(""set_P7""); } } internal static int P8 { set => System.Console.WriteLine(""set_P8""); } } class Test1 : I1 { static void Main() { I1.P1 = I1.P1; I1.P2 = I1.P2; var x = I1.P4; x = I1.P5; x = I1.P6; I1.P7 = x; I1.P8 = x; } public static int GetP3() { System.Console.WriteLine(""get_P3""); return 0; } public static int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } public static int GetP6() { System.Console.WriteLine(""get_P6""); return 0; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 get_P3 set_P2 set_P3 get_P4 get_P5 get_P6 set_P7 set_P8", symbolValidator: Validate); Validate(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (6,9): error CS8701: Target runtime doesn't support default interface implementation. // get Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(6, 9), // (11,9): error CS8701: Target runtime doesn't support default interface implementation. // set Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(11, 9), // (19,9): error CS8701: Target runtime doesn't support default interface implementation. // get Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(19, 9), // (24,9): error CS8701: Target runtime doesn't support default interface implementation. // set Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(24, 9), // (33,9): error CS8701: Target runtime doesn't support default interface implementation. // get => Test1.GetP3(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(33, 9), // (34,9): error CS8701: Target runtime doesn't support default interface implementation. // set => System.Console.WriteLine("set_P3"); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(34, 9), // (37,31): error CS8701: Target runtime doesn't support default interface implementation. // internal static int P4 => Test1.GetP4(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "Test1.GetP4()").WithLocation(37, 31), // (41,9): error CS8701: Target runtime doesn't support default interface implementation. // get Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(41, 9), // (50,9): error CS8701: Target runtime doesn't support default interface implementation. // get => Test1.GetP6(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(50, 9), // (55,9): error CS8701: Target runtime doesn't support default interface implementation. // set Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(55, 9), // (63,9): error CS8701: Target runtime doesn't support default interface implementation. // set => System.Console.WriteLine("set_P8"); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(63, 9) ); Validate(compilation2.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); foreach (var tuple in new[] { (name: "P1", access: Accessibility.Public), (name: "P2", access: Accessibility.Internal), (name: "P3", access: Accessibility.Private), (name: "P4", access: Accessibility.Internal), (name: "P5", access: Accessibility.Internal), (name: "P6", access: Accessibility.Internal), (name: "P7", access: Accessibility.Internal), (name: "P8", access: Accessibility.Internal)}) { var p1 = i1.GetMember<PropertySymbol>(tuple.name); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.True(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(tuple.access, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); switch (tuple.name) { case "P7": case "P8": Assert.Null(p1.GetMethod); ValidateAccessor(p1.SetMethod); break; case "P4": case "P5": case "P6": Assert.Null(p1.SetMethod); ValidateAccessor(p1.GetMethod); break; default: ValidateAccessor(p1.GetMethod); ValidateAccessor(p1.SetMethod); break; } void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(tuple.access, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } } [Fact] public void PropertyModifiers_08() { var source1 = @" public interface I1 { abstract static int P1 {get;} virtual static int P2 {set {}} sealed static int P3 => 0; static int P4 {get;} = 0; } class Test1 : I1 { int I1.P1 => 0; int I1.P2 {set {}} int I1.P3 => 0; int I1.P4 {set {}} } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.Net60); compilation1.VerifyDiagnostics( // (4,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P1 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("abstract", "9.0", "preview").WithLocation(4, 25), // (6,24): error CS0112: A static member cannot be marked as 'virtual' // virtual static int P2 {set {}} Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P2").WithArguments("virtual").WithLocation(6, 24), // (8,23): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static int P3 => 0; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P3").WithArguments("sealed", "9.0", "preview").WithLocation(8, 23), // (13,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(13, 15), // (15,12): error CS0539: 'Test1.P1' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.P1 => 0; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("Test1.P1").WithLocation(15, 12), // (16,12): error CS0539: 'Test1.P2' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.P2 {set {}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P2").WithArguments("Test1.P2").WithLocation(16, 12), // (17,12): error CS0539: 'Test1.P3' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.P3 => 0; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test1.P3").WithLocation(17, 12), // (18,12): error CS0539: 'Test1.P4' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.P4 {set {}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P4").WithArguments("Test1.P4").WithLocation(18, 12), // (21,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(21, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMember<PropertySymbol>("P1"); var p1get = p1.GetMethod; Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.True(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.True(p1get.IsAbstract); Assert.False(p1get.IsVirtual); Assert.True(p1get.IsMetadataVirtual()); Assert.False(p1get.IsSealed); Assert.True(p1get.IsStatic); Assert.False(p1get.IsExtern); Assert.False(p1get.IsAsync); Assert.False(p1get.IsOverride); Assert.Equal(Accessibility.Public, p1get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1get)); var p2 = i1.GetMember<PropertySymbol>("P2"); var p2set = p2.SetMethod; Assert.False(p2.IsAbstract); Assert.False(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.True(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2)); Assert.False(p2set.IsAbstract); Assert.False(p2set.IsVirtual); Assert.False(p2set.IsMetadataVirtual()); Assert.False(p2set.IsSealed); Assert.True(p2set.IsStatic); Assert.False(p2set.IsExtern); Assert.False(p2set.IsAsync); Assert.False(p2set.IsOverride); Assert.Equal(Accessibility.Public, p2set.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2set)); var p3 = i1.GetMember<PropertySymbol>("P3"); var p3get = p3.GetMethod; Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.False(p3.IsSealed); Assert.True(p3.IsStatic); Assert.False(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); Assert.False(p3get.IsAbstract); Assert.False(p3get.IsVirtual); Assert.False(p3get.IsMetadataVirtual()); Assert.False(p3get.IsSealed); Assert.True(p3get.IsStatic); Assert.False(p3get.IsExtern); Assert.False(p3get.IsAsync); Assert.False(p3get.IsOverride); Assert.Equal(Accessibility.Public, p3get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3get)); } [Fact] public void PropertyModifiers_09() { var source1 = @" public interface I1 { private int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } } sealed void M() { var x = P1; } } public interface I2 { private int P2 { get { System.Console.WriteLine(""get_P2""); return 0; } set { System.Console.WriteLine(""set_P2""); } } sealed void M() { P2 = P2; } } public interface I3 { private int P3 { set { System.Console.WriteLine(""set_P3""); } } sealed void M() { P3 = 0; } } public interface I4 { private int P4 { get => GetP4(); } private int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } sealed void M() { var x = P4; } } public interface I5 { private int P5 { get => GetP5(); set => System.Console.WriteLine(""set_P5""); } private int GetP5() { System.Console.WriteLine(""get_P5""); return 0; } sealed void M() { P5 = P5; } } public interface I6 { private int P6 { set => System.Console.WriteLine(""set_P6""); } sealed void M() { P6 = 0; } } public interface I7 { private int P7 => GetP7(); private int GetP7() { System.Console.WriteLine(""get_P7""); return 0; } sealed void M() { var x = P7; } } class Test1 : I1, I2, I3, I4, I5, I6, I7 { static void Main() { I1 x1 = new Test1(); x1.M(); I2 x2 = new Test1(); x2.M(); I3 x3 = new Test1(); x3.M(); I4 x4 = new Test1(); x4.M(); I5 x5 = new Test1(); x5.M(); I6 x6 = new Test1(); x6.M(); I7 x7 = new Test1(); x7.M(); } } "; ValidatePropertyModifiers_09(source1); } private void ValidatePropertyModifiers_09(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 get_P2 set_P2 set_P3 get_P4 get_P5 set_P5 set_P6 get_P7 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); for (int i = 1; i <= 7; i++) { var i1 = m.GlobalNamespace.GetTypeMember("I" + i); var p1 = GetSingleProperty(i1); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Private, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); switch (i) { case 3: case 6: Assert.Null(p1.GetMethod); ValidateAccessor(p1.SetMethod); break; case 1: case 4: case 7: Assert.Null(p1.SetMethod); ValidateAccessor(p1.GetMethod); break; default: ValidateAccessor(p1.GetMethod); ValidateAccessor(p1.SetMethod); break; } void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } } [Fact] public void PropertyModifiers_10() { var source1 = @" public interface I1 { abstract private int P1 { get; } virtual private int P2 => 0; sealed private int P3 { get => 0; set {} } private int P4 {get;} = 0; } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics( // (4,26): error CS0621: 'I1.P1': virtual or abstract members cannot be private // abstract private int P1 { get; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "P1").WithArguments("I1.P1").WithLocation(4, 26), // (6,25): error CS0621: 'I1.P2': virtual or abstract members cannot be private // virtual private int P2 => 0; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P2").WithArguments("I1.P2").WithLocation(6, 25), // (8,24): error CS0238: 'I1.P3' cannot be sealed because it is not an override // sealed private int P3 Diagnostic(ErrorCode.ERR_SealedNonOverride, "P3").WithArguments("I1.P3").WithLocation(8, 24), // (14,17): error CS8053: Instance properties in interfaces cannot have initializers. // private int P4 {get;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P4").WithArguments("I1.P4").WithLocation(14, 17), // (14,21): error CS0501: 'I1.P4.get' must declare a body because it is not marked abstract, extern, or partial // private int P4 {get;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.P4.get").WithLocation(14, 21), // (17,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(17, 15) ); ValidatePropertyModifiers_10(compilation1); } private static void ValidatePropertyModifiers_10(CSharpCompilation compilation1) { var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMembers().OfType<PropertySymbol>().ElementAt(0); var p1get = p1.GetMethod; Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Private, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.True(p1get.IsAbstract); Assert.False(p1get.IsVirtual); Assert.True(p1get.IsMetadataVirtual()); Assert.False(p1get.IsSealed); Assert.False(p1get.IsStatic); Assert.False(p1get.IsExtern); Assert.False(p1get.IsAsync); Assert.False(p1get.IsOverride); Assert.Equal(Accessibility.Private, p1get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1get)); var p2 = i1.GetMembers().OfType<PropertySymbol>().ElementAt(1); var p2get = p2.GetMethod; Assert.False(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Private, p2.DeclaredAccessibility); Assert.Same(p2, test1.FindImplementationForInterfaceMember(p2)); Assert.False(p2get.IsAbstract); Assert.True(p2get.IsVirtual); Assert.True(p2get.IsMetadataVirtual()); Assert.False(p2get.IsSealed); Assert.False(p2get.IsStatic); Assert.False(p2get.IsExtern); Assert.False(p2get.IsAsync); Assert.False(p2get.IsOverride); Assert.Equal(Accessibility.Private, p2get.DeclaredAccessibility); Assert.Same(p2get, test1.FindImplementationForInterfaceMember(p2get)); var p3 = i1.GetMembers().OfType<PropertySymbol>().ElementAt(2); Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.True(p3.IsSealed); Assert.False(p3.IsStatic); Assert.False(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Private, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.GetMethod); ValidateP3Accessor(p3.SetMethod); void ValidateP3Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.True(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } var p4 = i1.GetMembers().OfType<PropertySymbol>().ElementAt(3); var p4get = p4.GetMethod; Assert.False(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.False(p4.IsStatic); Assert.False(p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Private, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); Assert.False(p4get.IsAbstract); Assert.False(p4get.IsVirtual); Assert.False(p4get.IsMetadataVirtual()); Assert.False(p4get.IsSealed); Assert.False(p4get.IsStatic); Assert.False(p4get.IsExtern); Assert.False(p4get.IsAsync); Assert.False(p4get.IsOverride); Assert.Equal(Accessibility.Private, p4get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4get)); } [Fact] public void PropertyModifiers_11_01() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} sealed void Test() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_01(source1, source2, Accessibility.Internal, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } private void ValidatePropertyModifiers_11_01(string source1, string source2, Accessibility accessibility, DiagnosticDescription[] expected1, params DiagnosticDescription[] expected2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected1); ValidatePropertyModifiers_11(compilation1.SourceModule, accessibility); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidatePropertyModifiers_11(m, accessibility)).VerifyDiagnostics(); ValidatePropertyModifiers_11(compilation1.SourceModule, accessibility); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var p1 = GetSingleProperty(i1); var p1get = p1.GetMethod; var p1set = p1.SetMethod; ValidatePropertyModifiers_11(p1, accessibility); ValidatePropertyAccessorModifiers_11(p1get, accessibility); ValidatePropertyAccessorModifiers_11(p1set, accessibility); } var source3 = @" class Test2 : I1 { } "; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected1); ValidatePropertyModifiers_11(compilation3.SourceModule, accessibility); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidatePropertyModifiers_11(m, accessibility)).VerifyDiagnostics(); ValidatePropertyModifiers_11(compilation3.SourceModule, accessibility); var compilation5 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics(expected2); ValidatePropertyNotImplemented_11(compilation5, "Test2"); } } private static void ValidatePropertyModifiers_11(ModuleSymbol m, Accessibility accessibility) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var p1 = GetSingleProperty(i1); var test1P1 = GetSingleProperty(test1); var p1get = p1.GetMethod; var p1set = p1.SetMethod; ValidatePropertyModifiers_11(p1, accessibility); ValidatePropertyAccessorModifiers_11(p1get, accessibility); ValidatePropertyAccessorModifiers_11(p1set, accessibility); Assert.Same(test1P1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test1P1.GetMethod, test1.FindImplementationForInterfaceMember(p1get)); Assert.Same(test1P1.SetMethod, test1.FindImplementationForInterfaceMember(p1set)); } private static void ValidatePropertyModifiers_11(PropertySymbol p1, Accessibility accessibility) { Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(accessibility, p1.DeclaredAccessibility); } private static void ValidatePropertyAccessorModifiers_11(MethodSymbol m1, Accessibility accessibility) { Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(accessibility, m1.DeclaredAccessibility); } private static void ValidatePropertyNotImplemented_11(CSharpCompilation compilation, string className) { var test2 = compilation.GetTypeByMetadataName(className); var i1 = compilation.GetTypeByMetadataName("I1"); var p1 = GetSingleProperty(i1); Assert.Null(test2.FindImplementationForInterfaceMember(p1)); Assert.Null(test2.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p1.SetMethod)); } [Fact] public void PropertyModifiers_11_02() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) ); } private void ValidatePropertyModifiers_11_02(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); ValidatePropertyImplementation_11(compilation1.SourceModule); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidatePropertyImplementation_11(m)).VerifyDiagnostics(); ValidatePropertyImplementation_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected); ValidatePropertyImplementation_11(compilation3.SourceModule); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidatePropertyImplementation_11(m)).VerifyDiagnostics(); ValidatePropertyImplementation_11(compilation3.SourceModule); } } private static void ValidatePropertyImplementation_11(ModuleSymbol m) { ValidatePropertyImplementation_11(m, implementedByBase: false); } private static void ValidatePropertyImplementationByBase_11(ModuleSymbol m) { ValidatePropertyImplementation_11(m, implementedByBase: true); } private static void ValidatePropertyImplementation_11(ModuleSymbol m, bool implementedByBase) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var p1 = GetSingleProperty(i1); var test1P1 = GetSingleProperty(implementedByBase ? test1.BaseTypeNoUseSiteDiagnostics : test1); var p1get = p1.GetMethod; var p1set = p1.SetMethod; Assert.Same(test1P1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test1P1.GetMethod, test1.FindImplementationForInterfaceMember(p1get)); Assert.Same(test1P1.SetMethod, test1.FindImplementationForInterfaceMember(p1set)); var i2 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I2").SingleOrDefault(); Assert.True(test1P1.GetMethod.IsMetadataVirtual()); Assert.True(test1P1.SetMethod.IsMetadataVirtual()); } [Fact] public void PropertyModifiers_11_03() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.Standard, // (9,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // int I1.P1 Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(9, 12) ); } private void ValidatePropertyModifiers_11_03(string source1, string source2, TargetFramework targetFramework, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, targetFramework: targetFramework, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: !(targetFramework == TargetFramework.Standard || ExecutionConditionUtil.IsMonoOrCoreClr) ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementation_11); ValidatePropertyImplementation_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: targetFramework, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, targetFramework: targetFramework, parseOptions: TestOptions.Regular); compilation3.VerifyDiagnostics(expected); if (expected.Length == 0) { CompileAndVerify(compilation3, expectedOutput: !(targetFramework == TargetFramework.Standard || ExecutionConditionUtil.IsMonoOrCoreClr) ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementation_11); } ValidatePropertyImplementation_11(compilation3.SourceModule); } } [Fact] public void PropertyModifiers_11_04() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_11_05() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_11_06() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test3()); } public abstract int P1 {get; set;} } class Test3 : Test1 { public override int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_11_07() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallP1(new Test1()); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int P1 {get; set;} } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_11_08() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_08(source1, source2); } private void ValidatePropertyModifiers_11_08(string source1, string source2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: @"Test2.get_P1 Test2.set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationByBase_11); ValidatePropertyImplementationByBase_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation3, expectedOutput: @"Test2.get_P1 Test2.set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationByBase_11); ValidatePropertyImplementationByBase_11(compilation3.SourceModule); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation4, expectedOutput: @"Test2.get_P1 Test2.set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationByBase_11); ValidatePropertyImplementationByBase_11(compilation4.SourceModule); } [Fact] public void PropertyModifiers_11_09() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_09(source1, source2, // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.P1'. 'Test1.P1' cannot implement 'I1.P1' because it does not have the matching return type of 'int'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.P1", "Test1.P1", "int").WithLocation(2, 15) ); } private void ValidatePropertyModifiers_11_09(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics(expected); ValidatePropertyNotImplemented_11(compilation1, "Test1"); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation3.VerifyDiagnostics(expected); ValidatePropertyNotImplemented_11(compilation3, "Test1"); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation4.VerifyDiagnostics(expected); ValidatePropertyNotImplemented_11(compilation4, "Test1"); } [Fact] public void PropertyModifiers_11_10() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} sealed void Test() { P1 = P1; } } "; var source2 = @" public class Test2 : I1 { public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_10(source1, source2, // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.set'. 'Test2.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.set", "Test2.P1.set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.get'. 'Test2.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.get", "Test2.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } private void ValidatePropertyModifiers_11_10(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(expected); ValidatePropertyImplementationByBase_11(compilation1.SourceModule); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidatePropertyImplementationByBase_11(m)).VerifyDiagnostics(); ValidatePropertyImplementationByBase_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(expected); ValidatePropertyImplementationByBase_11(compilation3.SourceModule); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidatePropertyImplementationByBase_11(m)).VerifyDiagnostics(); ValidatePropertyImplementationByBase_11(compilation3.SourceModule); } } [Fact] public void PropertyModifiers_11_11() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} sealed void Test() { P1 = P1; } } public class Test2 : I1 { public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_11(source1, source2, // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.get'. 'Test2.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.get", "Test2.P1.get", "9.0", "10.0").WithLocation(11, 22), // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.set'. 'Test2.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.set", "Test2.P1.set", "9.0", "10.0").WithLocation(11, 22) ); } private void ValidatePropertyModifiers_11_11(string source1, string source2, params DiagnosticDescription[] expected) { var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, assemblyName: "PropertyModifiers_11_11"); compilation2.VerifyDiagnostics(expected); compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp, assemblyName: "PropertyModifiers_11_11"); compilation2.VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidatePropertyImplementationByBase_11(m)).VerifyDiagnostics(); ValidatePropertyImplementationByBase_11(compilation3.SourceModule); } [Fact] public void PropertyModifiers_12() { var source1 = @" public interface I1 { internal abstract int P1 {get; set;} } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMember<PropertySymbol>("P1"); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Null(test1.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(p1.SetMethod)); } [Fact] public void PropertyModifiers_13() { var source1 = @" public interface I1 { public sealed int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } } } public interface I2 { public sealed int P2 { get { System.Console.WriteLine(""get_P2""); return 0; } set { System.Console.WriteLine(""set_P2""); } } } public interface I3 { public sealed int P3 { set { System.Console.WriteLine(""set_P3""); } } } public interface I4 { public sealed int P4 { get => GetP4(); } private int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } } public interface I5 { public sealed int P5 { get => GetP5(); set => System.Console.WriteLine(""set_P5""); } private int GetP5() { System.Console.WriteLine(""get_P5""); return 0; } } public interface I6 { public sealed int P6 { set => System.Console.WriteLine(""set_P6""); } } public interface I7 { public sealed int P7 => GetP7(); private int GetP7() { System.Console.WriteLine(""get_P7""); return 0; } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); var x = i1.P1; I2 i2 = new Test2(); i2.P2 = i2.P2; I3 i3 = new Test3(); i3.P3 = x; I4 i4 = new Test4(); x = i4.P4; I5 i5 = new Test5(); i5.P5 = i5.P5; I6 i6 = new Test6(); i6.P6 = x; I7 i7 = new Test7(); x = i7.P7; } public int P1 => throw null; } class Test2 : I2 { public int P2 { get => throw null; set => throw null; } } class Test3 : I3 { public int P3 { set => throw null; } } class Test4 : I4 { public int P4 { get => throw null; } } class Test5 : I5 { public int P5 { get => throw null; set => throw null; } } class Test6 : I6 { public int P6 { set => throw null; } } class Test7 : I7 { public int P7 => throw null; } "; ValidatePropertyModifiers_13(source1); } private void ValidatePropertyModifiers_13(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate(ModuleSymbol m) { for (int i = 1; i <= 7; i++) { var test1 = m.GlobalNamespace.GetTypeMember("Test" + i); var i1 = m.GlobalNamespace.GetTypeMember("I" + i); var p1 = GetSingleProperty(i1); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); switch (i) { case 3: case 6: Assert.Null(p1.GetMethod); ValidateAccessor(p1.SetMethod); break; case 1: case 4: case 7: Assert.Null(p1.SetMethod); ValidateAccessor(p1.GetMethod); break; default: ValidateAccessor(p1.GetMethod); ValidateAccessor(p1.SetMethod); break; } void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 get_P2 set_P2 set_P3 get_P4 get_P5 set_P5 set_P6 get_P7 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); } [Fact] public void PropertyModifiers_14() { var source1 = @" public interface I1 { public sealed int P1 {get;} = 0; } public interface I2 { abstract sealed int P2 {get;} } public interface I3 { virtual sealed int P3 { set {} } } class Test1 : I1, I2, I3 { int I1.P1 { get => throw null; } int I2.P2 { get => throw null; } int I3.P3 { set => throw null; } } class Test2 : I1, I2, I3 {} "; ValidatePropertyModifiers_14(source1, // (4,23): error CS8053: Instance properties in interfaces cannot have initializers. // public sealed int P1 {get;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P1").WithArguments("I1.P1").WithLocation(4, 23), // (4,27): error CS0501: 'I1.P1.get' must declare a body because it is not marked abstract, extern, or partial // public sealed int P1 {get;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.P1.get").WithLocation(4, 27), // (8,25): error CS0238: 'I2.P2' cannot be sealed because it is not an override // abstract sealed int P2 {get;} Diagnostic(ErrorCode.ERR_SealedNonOverride, "P2").WithArguments("I2.P2").WithLocation(8, 25), // (12,24): error CS0238: 'I3.P3' cannot be sealed because it is not an override // virtual sealed int P3 Diagnostic(ErrorCode.ERR_SealedNonOverride, "P3").WithArguments("I3.P3").WithLocation(12, 24), // (20,12): error CS0539: 'Test1.P1' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.P1 { get => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("Test1.P1").WithLocation(20, 12), // (21,12): error CS0539: 'Test1.P2' in explicit interface declaration is not found among members of the interface that can be implemented // int I2.P2 { get => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P2").WithArguments("Test1.P2").WithLocation(21, 12), // (22,12): error CS0539: 'Test1.P3' in explicit interface declaration is not found among members of the interface that can be implemented // int I3.P3 { set => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test1.P3").WithLocation(22, 12) ); } private void ValidatePropertyModifiers_14(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var p1 = GetSingleProperty(compilation1, "I1"); var p1get = p1.GetMethod; Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Null(test2.FindImplementationForInterfaceMember(p1)); Assert.False(p1get.IsAbstract); Assert.False(p1get.IsVirtual); Assert.False(p1get.IsMetadataVirtual()); Assert.False(p1get.IsSealed); Assert.False(p1get.IsStatic); Assert.False(p1get.IsExtern); Assert.False(p1get.IsAsync); Assert.False(p1get.IsOverride); Assert.Equal(Accessibility.Public, p1get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1get)); Assert.Null(test2.FindImplementationForInterfaceMember(p1get)); var p2 = GetSingleProperty(compilation1, "I2"); var test1P2 = test1.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); var p2get = p2.GetMethod; Assert.True(p2.IsAbstract); Assert.False(p2.IsVirtual); Assert.True(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2)); Assert.Null(test2.FindImplementationForInterfaceMember(p2)); Assert.True(p2get.IsAbstract); Assert.False(p2get.IsVirtual); Assert.True(p2get.IsMetadataVirtual()); Assert.True(p2get.IsSealed); Assert.False(p2get.IsStatic); Assert.False(p2get.IsExtern); Assert.False(p2get.IsAsync); Assert.False(p2get.IsOverride); Assert.Equal(Accessibility.Public, p2get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2get)); Assert.Null(test2.FindImplementationForInterfaceMember(p2get)); var p3 = GetSingleProperty(compilation1, "I3"); var test1P3 = test1.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I3.")).Single(); var p3set = p3.SetMethod; Assert.False(p3.IsAbstract); Assert.True(p3.IsVirtual); Assert.True(p3.IsSealed); Assert.False(p3.IsStatic); Assert.False(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); Assert.False(p3set.IsAbstract); Assert.True(p3set.IsVirtual); Assert.True(p3set.IsMetadataVirtual()); Assert.True(p3set.IsSealed); Assert.False(p3set.IsStatic); Assert.False(p3set.IsExtern); Assert.False(p3set.IsAsync); Assert.False(p3set.IsOverride); Assert.Equal(Accessibility.Public, p3set.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3set)); Assert.Null(test2.FindImplementationForInterfaceMember(p3set)); } [Fact] public void PropertyModifiers_15() { var source1 = @" public interface I0 { abstract virtual int P0 { get; set; } } public interface I1 { abstract virtual int P1 { get { throw null; } } } public interface I2 { virtual abstract int P2 { get { throw null; } set { throw null; } } } public interface I3 { abstract virtual int P3 { set { throw null; } } } public interface I4 { abstract virtual int P4 { get => throw null; } } public interface I5 { abstract virtual int P5 { get => throw null; set => throw null; } } public interface I6 { abstract virtual int P6 { set => throw null; } } public interface I7 { abstract virtual int P7 => throw null; } public interface I8 { abstract virtual int P8 {get;} = 0; } class Test1 : I0, I1, I2, I3, I4, I5, I6, I7, I8 { int I0.P0 { get { throw null; } set { throw null; } } int I1.P1 { get { throw null; } } int I2.P2 { get { throw null; } set { throw null; } } int I3.P3 { set { throw null; } } int I4.P4 { get { throw null; } } int I5.P5 { get { throw null; } set { throw null; } } int I6.P6 { set { throw null; } } int I7.P7 { get { throw null; } } int I8.P8 { get { throw null; } } } class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 {} "; ValidatePropertyModifiers_15(source1, // (4,26): error CS0503: The abstract property 'I0.P0' cannot be marked virtual // abstract virtual int P0 { get; set; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P0").WithArguments("property", "I0.P0").WithLocation(4, 26), // (8,26): error CS0503: The abstract property 'I1.P1' cannot be marked virtual // abstract virtual int P1 { get { throw null; } } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P1").WithArguments("property", "I1.P1").WithLocation(8, 26), // (8,31): error CS0500: 'I1.P1.get' cannot declare a body because it is marked abstract // abstract virtual int P1 { get { throw null; } } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.P1.get").WithLocation(8, 31), // (12,26): error CS0503: The abstract property 'I2.P2' cannot be marked virtual // virtual abstract int P2 Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P2").WithArguments("property", "I2.P2").WithLocation(12, 26), // (14,9): error CS0500: 'I2.P2.get' cannot declare a body because it is marked abstract // get { throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.P2.get").WithLocation(14, 9), // (15,9): error CS0500: 'I2.P2.set' cannot declare a body because it is marked abstract // set { throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.P2.set").WithLocation(15, 9), // (20,26): error CS0503: The abstract property 'I3.P3' cannot be marked virtual // abstract virtual int P3 { set { throw null; } } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P3").WithArguments("property", "I3.P3").WithLocation(20, 26), // (20,31): error CS0500: 'I3.P3.set' cannot declare a body because it is marked abstract // abstract virtual int P3 { set { throw null; } } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I3.P3.set").WithLocation(20, 31), // (24,26): error CS0503: The abstract property 'I4.P4' cannot be marked virtual // abstract virtual int P4 { get => throw null; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P4").WithArguments("property", "I4.P4").WithLocation(24, 26), // (24,31): error CS0500: 'I4.P4.get' cannot declare a body because it is marked abstract // abstract virtual int P4 { get => throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I4.P4.get").WithLocation(24, 31), // (28,26): error CS0503: The abstract property 'I5.P5' cannot be marked virtual // abstract virtual int P5 Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P5").WithArguments("property", "I5.P5").WithLocation(28, 26), // (30,9): error CS0500: 'I5.P5.get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I5.P5.get").WithLocation(30, 9), // (31,9): error CS0500: 'I5.P5.set' cannot declare a body because it is marked abstract // set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I5.P5.set").WithLocation(31, 9), // (36,26): error CS0503: The abstract property 'I6.P6' cannot be marked virtual // abstract virtual int P6 { set => throw null; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P6").WithArguments("property", "I6.P6").WithLocation(36, 26), // (36,31): error CS0500: 'I6.P6.set' cannot declare a body because it is marked abstract // abstract virtual int P6 { set => throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I6.P6.set").WithLocation(36, 31), // (40,26): error CS0503: The abstract property 'I7.P7' cannot be marked virtual // abstract virtual int P7 => throw null; Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P7").WithArguments("property", "I7.P7").WithLocation(40, 26), // (40,32): error CS0500: 'I7.P7.get' cannot declare a body because it is marked abstract // abstract virtual int P7 => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "throw null").WithArguments("I7.P7.get").WithLocation(40, 32), // (44,26): error CS0503: The abstract property 'I8.P8' cannot be marked virtual // abstract virtual int P8 {get;} = 0; Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P8").WithArguments("property", "I8.P8").WithLocation(44, 26), // (44,26): error CS8053: Instance properties in interfaces cannot have initializers. // abstract virtual int P8 {get;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P8").WithArguments("I8.P8").WithLocation(44, 26), // (90,15): error CS0535: 'Test2' does not implement interface member 'I0.P0' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I0").WithArguments("Test2", "I0.P0").WithLocation(90, 15), // (90,19): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(90, 19), // (90,23): error CS0535: 'Test2' does not implement interface member 'I2.P2' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I2.P2").WithLocation(90, 23), // (90,27): error CS0535: 'Test2' does not implement interface member 'I3.P3' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test2", "I3.P3").WithLocation(90, 27), // (90,31): error CS0535: 'Test2' does not implement interface member 'I4.P4' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test2", "I4.P4").WithLocation(90, 31), // (90,35): error CS0535: 'Test2' does not implement interface member 'I5.P5' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I5").WithArguments("Test2", "I5.P5").WithLocation(90, 35), // (90,39): error CS0535: 'Test2' does not implement interface member 'I6.P6' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I6").WithArguments("Test2", "I6.P6").WithLocation(90, 39), // (90,43): error CS0535: 'Test2' does not implement interface member 'I7.P7' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I7").WithArguments("Test2", "I7.P7").WithLocation(90, 43), // (90,47): error CS0535: 'Test2' does not implement interface member 'I8.P8' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I8").WithArguments("Test2", "I8.P8").WithLocation(90, 47) ); } private void ValidatePropertyModifiers_15(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); for (int i = 0; i <= 8; i++) { var i1 = compilation1.GetTypeByMetadataName("I" + i); var p2 = GetSingleProperty(i1); var test1P2 = test1.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith(i1.Name)).Single(); Assert.True(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Same(test1P2, test1.FindImplementationForInterfaceMember(p2)); Assert.Null(test2.FindImplementationForInterfaceMember(p2)); switch (i) { case 3: case 6: Assert.Null(p2.GetMethod); ValidateAccessor(p2.SetMethod, test1P2.SetMethod); break; case 1: case 4: case 7: case 8: Assert.Null(p2.SetMethod); ValidateAccessor(p2.GetMethod, test1P2.GetMethod); break; default: ValidateAccessor(p2.GetMethod, test1P2.GetMethod); ValidateAccessor(p2.SetMethod, test1P2.SetMethod); break; } void ValidateAccessor(MethodSymbol accessor, MethodSymbol implementedBy) { Assert.True(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(implementedBy, test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } } } [Fact] public void PropertyModifiers_16() { var source1 = @" public interface I1 { extern int P1 {get;} } public interface I2 { virtual extern int P2 {set;} } public interface I3 { static extern int P3 {get; set;} } public interface I4 { private extern int P4 {get;} } public interface I5 { extern sealed int P5 {set;} } class Test1 : I1, I2, I3, I4, I5 { } class Test2 : I1, I2, I3, I4, I5 { int I1.P1 => 0; int I2.P2 { set {} } } "; ValidatePropertyModifiers_16(source1, new DiagnosticDescription[] { // (4,16): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern int P1 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("extern", "7.3", "8.0").WithLocation(4, 16), // (8,24): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern int P2 {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P2").WithArguments("extern", "7.3", "8.0").WithLocation(8, 24), // (8,24): error CS8503: The modifier 'virtual' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern int P2 {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P2").WithArguments("virtual", "7.3", "8.0").WithLocation(8, 24), // (12,23): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static extern int P3 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P3").WithArguments("static", "7.3", "8.0").WithLocation(12, 23), // (12,23): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static extern int P3 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P3").WithArguments("extern", "7.3", "8.0").WithLocation(12, 23), // (16,24): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern int P4 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P4").WithArguments("private", "7.3", "8.0").WithLocation(16, 24), // (16,24): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern int P4 {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P4").WithArguments("extern", "7.3", "8.0").WithLocation(16, 24), // (20,23): error CS8503: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed int P5 {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P5").WithArguments("sealed", "7.3", "8.0").WithLocation(20, 23), // (20,23): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed int P5 {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P5").WithArguments("extern", "7.3", "8.0").WithLocation(20, 23), // (8,28): warning CS0626: Method, operator, or accessor 'I2.P2.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern int P2 {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I2.P2.set").WithLocation(8, 28), // (12,27): warning CS0626: Method, operator, or accessor 'I3.P3.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I3.P3.get").WithLocation(12, 27), // (12,32): warning CS0626: Method, operator, or accessor 'I3.P3.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I3.P3.set").WithLocation(12, 32), // (16,28): warning CS0626: Method, operator, or accessor 'I4.P4.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern int P4 {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I4.P4.get").WithLocation(16, 28), // (20,27): warning CS0626: Method, operator, or accessor 'I5.P5.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed int P5 {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I5.P5.set").WithLocation(20, 27), // (4,20): warning CS0626: Method, operator, or accessor 'I1.P1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P1 {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.P1.get").WithLocation(4, 20) }, // (4,20): error CS8501: Target runtime doesn't support default interface implementation. // extern int P1 {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(4, 20), // (8,28): error CS8501: Target runtime doesn't support default interface implementation. // virtual extern int P2 {set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(8, 28), // (16,28): error CS8501: Target runtime doesn't support default interface implementation. // private extern int P4 {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(16, 28), // (20,27): error CS8501: Target runtime doesn't support default interface implementation. // extern sealed int P5 {set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(20, 27), // (8,28): warning CS0626: Method, operator, or accessor 'I2.P2.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern int P2 {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I2.P2.set").WithLocation(8, 28), // (12,27): error CS8701: Target runtime doesn't support default interface implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(12, 27), // (12,27): warning CS0626: Method, operator, or accessor 'I3.P3.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I3.P3.get").WithLocation(12, 27), // (12,32): error CS8701: Target runtime doesn't support default interface implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(12, 32), // (12,32): warning CS0626: Method, operator, or accessor 'I3.P3.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I3.P3.set").WithLocation(12, 32), // (16,28): warning CS0626: Method, operator, or accessor 'I4.P4.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern int P4 {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I4.P4.get").WithLocation(16, 28), // (20,27): warning CS0626: Method, operator, or accessor 'I5.P5.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed int P5 {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I5.P5.set").WithLocation(20, 27), // (4,20): warning CS0626: Method, operator, or accessor 'I1.P1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int P1 {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.P1.get").WithLocation(4, 20) ); } private void ValidatePropertyModifiers_16(string source1, DiagnosticDescription[] expected1, params DiagnosticDescription[] expected2) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test2 = m.GlobalNamespace.GetTypeMember("Test2"); bool isSource = !(m is PEModuleSymbol); var p1 = GetSingleProperty(m, "I1"); var test2P1 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I1.")).Single(); var p1get = p1.GetMethod; Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.Equal(isSource, p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test2P1, test2.FindImplementationForInterfaceMember(p1)); Assert.False(p1get.IsAbstract); Assert.True(p1get.IsVirtual); Assert.True(p1get.IsMetadataVirtual()); Assert.False(p1get.IsSealed); Assert.False(p1get.IsStatic); Assert.Equal(isSource, p1get.IsExtern); Assert.False(p1get.IsAsync); Assert.False(p1get.IsOverride); Assert.Equal(Accessibility.Public, p1get.DeclaredAccessibility); Assert.Same(p1get, test1.FindImplementationForInterfaceMember(p1get)); Assert.Same(test2P1.GetMethod, test2.FindImplementationForInterfaceMember(p1get)); var p2 = GetSingleProperty(m, "I2"); var test2P2 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); var p2set = p2.SetMethod; Assert.False(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.Equal(isSource, p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Same(p2, test1.FindImplementationForInterfaceMember(p2)); Assert.Same(test2P2, test2.FindImplementationForInterfaceMember(p2)); Assert.False(p2set.IsAbstract); Assert.True(p2set.IsVirtual); Assert.True(p2set.IsMetadataVirtual()); Assert.False(p2set.IsSealed); Assert.False(p2set.IsStatic); Assert.Equal(isSource, p2set.IsExtern); Assert.False(p2set.IsAsync); Assert.False(p2set.IsOverride); Assert.Equal(Accessibility.Public, p2set.DeclaredAccessibility); Assert.Same(p2set, test1.FindImplementationForInterfaceMember(p2set)); Assert.Same(test2P2.SetMethod, test2.FindImplementationForInterfaceMember(p2set)); var i3 = m.ContainingAssembly.GetTypeByMetadataName("I3"); if ((object)i3 != null) { var p3 = GetSingleProperty(i3); Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.False(p3.IsSealed); Assert.True(p3.IsStatic); Assert.Equal(isSource, p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.GetMethod); ValidateP3Accessor(p3.SetMethod); void ValidateP3Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.Equal(isSource, accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } } var p4 = GetSingleProperty(m, "I4"); var p4get = p4.GetMethod; Assert.False(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.False(p4.IsStatic); Assert.Equal(isSource, p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Private, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); Assert.Null(test2.FindImplementationForInterfaceMember(p4)); Assert.False(p4get.IsAbstract); Assert.False(p4get.IsVirtual); Assert.False(p4get.IsMetadataVirtual()); Assert.False(p4get.IsSealed); Assert.False(p4get.IsStatic); Assert.Equal(isSource, p4get.IsExtern); Assert.False(p4get.IsAsync); Assert.False(p4get.IsOverride); Assert.Equal(Accessibility.Private, p4get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4get)); Assert.Null(test2.FindImplementationForInterfaceMember(p4get)); var p5 = GetSingleProperty(m, "I5"); var p5set = p5.SetMethod; Assert.False(p5.IsAbstract); Assert.False(p5.IsVirtual); Assert.False(p5.IsSealed); Assert.False(p5.IsStatic); Assert.Equal(isSource, p5.IsExtern); Assert.False(p5.IsOverride); Assert.Equal(Accessibility.Public, p5.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5)); Assert.Null(test2.FindImplementationForInterfaceMember(p5)); Assert.False(p5set.IsAbstract); Assert.False(p5set.IsVirtual); Assert.False(p5set.IsMetadataVirtual()); Assert.False(p5set.IsSealed); Assert.False(p5set.IsStatic); Assert.Equal(isSource, p5set.IsExtern); Assert.False(p5set.IsAsync); Assert.False(p5set.IsOverride); Assert.Equal(Accessibility.Public, p5set.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5set)); Assert.Null(test2.FindImplementationForInterfaceMember(p5set)); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(expected1); Validate(compilation2.SourceModule); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected2); Validate(compilation3.SourceModule); } [Fact] public void PropertyModifiers_17() { var source1 = @" public interface I1 { abstract extern int P1 {get;} } public interface I2 { extern int P2 => 0; } public interface I3 { static extern int P3 {get => 0; set => throw null;} } public interface I4 { private extern int P4 { get {throw null;} set {throw null;}} } public interface I5 { extern sealed int P5 {get;} = 0; } class Test1 : I1, I2, I3, I4, I5 { } class Test2 : I1, I2, I3, I4, I5 { int I1.P1 => 0; int I2.P2 => 0; int I3.P3 { get => 0; set => throw null;} int I4.P4 { get => 0; set => throw null;} int I5.P5 => 0; } "; ValidatePropertyModifiers_17(source1, // (4,25): error CS0180: 'I1.P1' cannot be both extern and abstract // abstract extern int P1 {get;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P1").WithArguments("I1.P1").WithLocation(4, 25), // (8,22): error CS0179: 'I2.P2.get' cannot be extern and declare a body // extern int P2 => 0; Diagnostic(ErrorCode.ERR_ExternHasBody, "0").WithArguments("I2.P2.get").WithLocation(8, 22), // (12,27): error CS0179: 'I3.P3.get' cannot be extern and declare a body // static extern int P3 {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("I3.P3.get").WithLocation(12, 27), // (12,37): error CS0179: 'I3.P3.set' cannot be extern and declare a body // static extern int P3 {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("I3.P3.set").WithLocation(12, 37), // (16,29): error CS0179: 'I4.P4.get' cannot be extern and declare a body // private extern int P4 { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("I4.P4.get").WithLocation(16, 29), // (16,47): error CS0179: 'I4.P4.set' cannot be extern and declare a body // private extern int P4 { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("I4.P4.set").WithLocation(16, 47), // (20,23): error CS8053: Instance properties in interfaces cannot have initializers. // extern sealed int P5 {get;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P5").WithArguments("I5.P5").WithLocation(20, 23), // (23,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(23, 15), // (31,12): error CS0539: 'Test2.P3' in explicit interface declaration is not found among members of the interface that can be implemented // int I3.P3 { get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test2.P3").WithLocation(31, 12), // (32,12): error CS0539: 'Test2.P4' in explicit interface declaration is not found among members of the interface that can be implemented // int I4.P4 { get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P4").WithArguments("Test2.P4").WithLocation(32, 12), // (33,12): error CS0539: 'Test2.P5' in explicit interface declaration is not found among members of the interface that can be implemented // int I5.P5 => 0; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P5").WithArguments("Test2.P5").WithLocation(33, 12), // (20,27): warning CS0626: Method, operator, or accessor 'I5.P5.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed int P5 {get;} = 0; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I5.P5.get").WithLocation(20, 27) ); } private void ValidatePropertyModifiers_17(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var p1 = GetSingleProperty(compilation1, "I1"); var test2P1 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I1.")).Single(); var p1get = p1.GetMethod; Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.True(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test2P1, test2.FindImplementationForInterfaceMember(p1)); Assert.True(p1get.IsAbstract); Assert.False(p1get.IsVirtual); Assert.True(p1get.IsMetadataVirtual()); Assert.False(p1get.IsSealed); Assert.False(p1get.IsStatic); Assert.True(p1get.IsExtern); Assert.False(p1get.IsAsync); Assert.False(p1get.IsOverride); Assert.Equal(Accessibility.Public, p1get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1get)); Assert.Same(test2P1.GetMethod, test2.FindImplementationForInterfaceMember(p1get)); var p2 = GetSingleProperty(compilation1, "I2"); var test2P2 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); var p2get = p2.GetMethod; Assert.False(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.True(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Same(p2, test1.FindImplementationForInterfaceMember(p2)); Assert.Same(test2P2, test2.FindImplementationForInterfaceMember(p2)); Assert.False(p2get.IsAbstract); Assert.True(p2get.IsVirtual); Assert.True(p2get.IsMetadataVirtual()); Assert.False(p2get.IsSealed); Assert.False(p2get.IsStatic); Assert.True(p2get.IsExtern); Assert.False(p2get.IsAsync); Assert.False(p2get.IsOverride); Assert.Equal(Accessibility.Public, p2get.DeclaredAccessibility); Assert.Same(p2get, test1.FindImplementationForInterfaceMember(p2get)); Assert.Same(test2P2.GetMethod, test2.FindImplementationForInterfaceMember(p2get)); var p3 = GetSingleProperty(compilation1, "I3"); var test2P3 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I3.")).Single(); Assert.False(p3.IsAbstract); Assert.Equal(p3.IsIndexer, p3.IsVirtual); Assert.False(p3.IsSealed); Assert.Equal(!p3.IsIndexer, p3.IsStatic); Assert.True(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Same(p3.IsIndexer ? p3 : null, test1.FindImplementationForInterfaceMember(p3)); Assert.Same(p3.IsIndexer ? test2P3 : null, test2.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.GetMethod, p3.IsIndexer ? test2P3.GetMethod : null); ValidateP3Accessor(p3.SetMethod, p3.IsIndexer ? test2P3.SetMethod : null); void ValidateP3Accessor(MethodSymbol accessor, MethodSymbol test2Implementation) { Assert.False(accessor.IsAbstract); Assert.Equal(p3.IsIndexer, accessor.IsVirtual); Assert.Equal(p3.IsIndexer, accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.Equal(!p3.IsIndexer, accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(p3.IsIndexer ? accessor : null, test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(test2Implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p4 = GetSingleProperty(compilation1, "I4"); Assert.False(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.False(p4.IsStatic); Assert.True(p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Private, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); Assert.Null(test2.FindImplementationForInterfaceMember(p4)); ValidateP4Accessor(p4.GetMethod); ValidateP4Accessor(p4.SetMethod); void ValidateP4Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p5 = GetSingleProperty(compilation1, "I5"); var p5get = p5.GetMethod; Assert.False(p5.IsAbstract); Assert.False(p5.IsVirtual); Assert.False(p5.IsSealed); Assert.False(p5.IsStatic); Assert.True(p5.IsExtern); Assert.False(p5.IsOverride); Assert.Equal(Accessibility.Public, p5.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5)); Assert.Null(test2.FindImplementationForInterfaceMember(p5)); Assert.False(p5get.IsAbstract); Assert.False(p5get.IsVirtual); Assert.False(p5get.IsMetadataVirtual()); Assert.False(p5get.IsSealed); Assert.False(p5get.IsStatic); Assert.True(p5get.IsExtern); Assert.False(p5get.IsAsync); Assert.False(p5get.IsOverride); Assert.Equal(Accessibility.Public, p5get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5get)); Assert.Null(test2.FindImplementationForInterfaceMember(p5get)); } [Fact] public void PropertyModifiers_18() { var source1 = @" public interface I1 { abstract int P1 {get => 0; set => throw null;} } public interface I2 { abstract private int P2 => 0; } public interface I3 { static extern int P3 {get; set;} } public interface I4 { abstract static int P4 { get {throw null;} set {throw null;}} } public interface I5 { override sealed int P5 {get;} = 0; } class Test1 : I1, I2, I3, I4, I5 { } class Test2 : I1, I2, I3, I4, I5 { int I1.P1 { get => 0; set => throw null;} int I2.P2 => 0; int I3.P3 { get => 0; set => throw null;} int I4.P4 { get => 0; set => throw null;} int I5.P5 => 0; } "; ValidatePropertyModifiers_18(source1, // (4,22): error CS0500: 'I1.P1.get' cannot declare a body because it is marked abstract // abstract int P1 {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.P1.get").WithLocation(4, 22), // (4,32): error CS0500: 'I1.P1.set' cannot declare a body because it is marked abstract // abstract int P1 {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I1.P1.set").WithLocation(4, 32), // (8,26): error CS0621: 'I2.P2': virtual or abstract members cannot be private // abstract private int P2 => 0; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P2").WithArguments("I2.P2").WithLocation(8, 26), // (8,32): error CS0500: 'I2.P2.get' cannot declare a body because it is marked abstract // abstract private int P2 => 0; Diagnostic(ErrorCode.ERR_AbstractHasBody, "0").WithArguments("I2.P2.get").WithLocation(8, 32), // (16,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P4 { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P4").WithArguments("abstract", "9.0", "preview").WithLocation(16, 25), // (16,30): error CS0500: 'I4.P4.get' cannot declare a body because it is marked abstract // abstract static int P4 { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I4.P4.get").WithLocation(16, 30), // (16,48): error CS0500: 'I4.P4.set' cannot declare a body because it is marked abstract // abstract static int P4 { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I4.P4.set").WithLocation(16, 48), // (20,25): error CS0106: The modifier 'override' is not valid for this item // override sealed int P5 {get;} = 0; Diagnostic(ErrorCode.ERR_BadMemberFlag, "P5").WithArguments("override").WithLocation(20, 25), // (20,25): error CS8053: Instance properties in interfaces cannot have initializers. // override sealed int P5 {get;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P5").WithArguments("I5.P5").WithLocation(20, 25), // (20,29): error CS0501: 'I5.P5.get' must declare a body because it is not marked abstract, extern, or partial // override sealed int P5 {get;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I5.P5.get").WithLocation(20, 29), // (23,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(23, 15), // (23,19): error CS0535: 'Test1' does not implement interface member 'I2.P2' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I2.P2").WithLocation(23, 19), // (30,12): error CS0122: 'I2.P2' is inaccessible due to its protection level // int I2.P2 => 0; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I2.P2").WithLocation(30, 12), // (31,12): error CS0539: 'Test2.P3' in explicit interface declaration is not found among members of the interface that can be implemented // int I3.P3 { get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test2.P3").WithLocation(31, 12), // (32,12): error CS0539: 'Test2.P4' in explicit interface declaration is not found among members of the interface that can be implemented // int I4.P4 { get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P4").WithArguments("Test2.P4").WithLocation(32, 12), // (33,12): error CS0539: 'Test2.P5' in explicit interface declaration is not found among members of the interface that can be implemented // int I5.P5 => 0; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P5").WithArguments("Test2.P5").WithLocation(33, 12), // (12,27): warning CS0626: Method, operator, or accessor 'I3.P3.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I3.P3.get").WithLocation(12, 27), // (12,32): warning CS0626: Method, operator, or accessor 'I3.P3.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int P3 {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I3.P3.set").WithLocation(12, 32), // (23,27): error CS0535: 'Test1' does not implement interface member 'I4.P4' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test1", "I4.P4").WithLocation(23, 27), // (27,27): error CS0535: 'Test2' does not implement interface member 'I4.P4' // class Test2 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test2", "I4.P4").WithLocation(27, 27) ); } private void ValidatePropertyModifiers_18(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var p1 = GetSingleProperty(compilation1, "I1"); var test2P1 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I1.")).Single(); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test2P1, test2.FindImplementationForInterfaceMember(p1)); ValidateP1Accessor(p1.GetMethod, test2P1.GetMethod); ValidateP1Accessor(p1.SetMethod, test2P1.SetMethod); void ValidateP1Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p2 = GetSingleProperty(compilation1, "I2"); var test2P2 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); var p2get = p2.GetMethod; Assert.True(p2.IsAbstract); Assert.False(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Private, p2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2)); Assert.Same(test2P2, test2.FindImplementationForInterfaceMember(p2)); Assert.True(p2get.IsAbstract); Assert.False(p2get.IsVirtual); Assert.True(p2get.IsMetadataVirtual()); Assert.False(p2get.IsSealed); Assert.False(p2get.IsStatic); Assert.False(p2get.IsExtern); Assert.False(p2get.IsAsync); Assert.False(p2get.IsOverride); Assert.Equal(Accessibility.Private, p2get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2get)); Assert.Same(test2P2.GetMethod, test2.FindImplementationForInterfaceMember(p2get)); var p3 = GetSingleProperty(compilation1, "I3"); var test2P3 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I3.")).Single(); Assert.False(p3.IsAbstract); Assert.Equal(p3.IsIndexer, p3.IsVirtual); Assert.False(p3.IsSealed); Assert.Equal(!p3.IsIndexer, p3.IsStatic); Assert.True(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Same(p3.IsIndexer ? p3 : null, test1.FindImplementationForInterfaceMember(p3)); Assert.Same(p3.IsIndexer ? test2P3 : null, test2.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.GetMethod, p3.IsIndexer ? test2P3.GetMethod : null); ValidateP3Accessor(p3.SetMethod, p3.IsIndexer ? test2P3.SetMethod : null); void ValidateP3Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.False(accessor.IsAbstract); Assert.Equal(p3.IsIndexer, accessor.IsVirtual); Assert.Equal(p3.IsIndexer, accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.Equal(!p3.IsIndexer, accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(p3.IsIndexer ? accessor : null, test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p4 = GetSingleProperty(compilation1, "I4"); var test2P4 = test2.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I4.")).Single(); Assert.True(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.Equal(!p4.IsIndexer, p4.IsStatic); Assert.False(p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Public, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); Assert.Same(p4.IsIndexer ? test2P4 : null, test2.FindImplementationForInterfaceMember(p4)); ValidateP4Accessor(p4.GetMethod, p4.IsIndexer ? test2P4.GetMethod : null); ValidateP4Accessor(p4.SetMethod, p4.IsIndexer ? test2P4.SetMethod : null); void ValidateP4Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.Equal(!p4.IsIndexer, accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p5 = GetSingleProperty(compilation1, "I5"); var p5get = p5.GetMethod; Assert.False(p5.IsAbstract); Assert.False(p5.IsVirtual); Assert.False(p5.IsSealed); Assert.False(p5.IsStatic); Assert.False(p5.IsExtern); Assert.False(p5.IsOverride); Assert.Equal(Accessibility.Public, p5.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5)); Assert.Null(test2.FindImplementationForInterfaceMember(p5)); Assert.False(p5get.IsAbstract); Assert.False(p5get.IsVirtual); Assert.False(p5get.IsMetadataVirtual()); Assert.False(p5get.IsSealed); Assert.False(p5get.IsStatic); Assert.False(p5get.IsExtern); Assert.False(p5get.IsAsync); Assert.False(p5get.IsOverride); Assert.Equal(Accessibility.Public, p5get.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5get)); Assert.Null(test2.FindImplementationForInterfaceMember(p5get)); } [Fact] public void PropertyModifiers_20() { var source1 = @" public interface I1 { internal int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } void M2() {P1 = P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidatePropertyModifiers_20(source1, source2, Accessibility.Internal); } private void ValidatePropertyModifiers_20(string source1, string source2, Accessibility accessibility) { var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var p1 = GetSingleProperty(i1); var p1get = p1.GetMethod; var p1set = p1.SetMethod; ValidateProperty(p1); ValidateMethod(p1get); ValidateMethod(p1set); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(p1get, test1.FindImplementationForInterfaceMember(p1get)); Assert.Same(p1set, test1.FindImplementationForInterfaceMember(p1set)); } void ValidateProperty(PropertySymbol p1) { Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(accessibility, p1.DeclaredAccessibility); } void ValidateMethod(MethodSymbol m1) { Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(accessibility, m1.DeclaredAccessibility); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var p1 = GetSingleProperty(i1); var p1get = p1.GetMethod; var p1set = p1.SetMethod; ValidateProperty(p1); ValidateMethod(p1get); ValidateMethod(p1set); } var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation3.SourceModule); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation4.SourceModule); } [Fact] public void PropertyModifiers_21() { var source1 = @" public interface I1 { private static int P1 { get => throw null; set => throw null; } internal static int P2 { get => throw null; set => throw null; } public static int P3 { get => throw null; set => throw null; } static int P4 { get => throw null; set => throw null; } } class Test1 { static void Main() { int x; x = I1.P1; I1.P1 = x; x = I1.P2; I1.P2 = x; x = I1.P3; I1.P3 = x; x = I1.P4; I1.P4 = x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (18,16): error CS0122: 'I1.P1' is inaccessible due to its protection level // x = I1.P1; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(18, 16), // (19,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 = x; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(19, 12) ); var source2 = @" class Test2 { static void Main() { int x; x = I1.P1; I1.P1 = x; x = I1.P2; I1.P2 = x; x = I1.P3; I1.P3 = x; x = I1.P4; I1.P4 = x; } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (7,16): error CS0122: 'I1.P1' is inaccessible due to its protection level // x = I1.P1; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(7, 16), // (8,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 = x; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(8, 12), // (9,16): error CS0122: 'I1.P2' is inaccessible due to its protection level // x = I1.P2; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(9, 16), // (10,12): error CS0122: 'I1.P2' is inaccessible due to its protection level // I1.P2 = x; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(10, 12) ); } [Fact] public void PropertyModifiers_22() { var source1 = @" public interface I1 { public int P1 { internal get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int P2 { get { System.Console.WriteLine(""get_P2""); return 0; } internal set { System.Console.WriteLine(""set_P2""); } } } public interface I3 { int P3 { internal get => Test1.GetP3(); set => System.Console.WriteLine(""set_P3""); } } public interface I4 { int P4 { get => Test1.GetP4(); internal set => System.Console.WriteLine(""set_P4""); } } class Test1 : I1, I2, I3, I4 { static void Main() { I1 i1 = new Test1(); I2 i2 = new Test1(); I3 i3 = new Test1(); I4 i4 = new Test1(); i1.P1 = i1.P1; i2.P2 = i2.P2; i3.P3 = i3.P3; i4.P4 = i4.P4; } public static int GetP3() { System.Console.WriteLine(""get_P3""); return 0; } public static int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } } "; ValidatePropertyModifiers_22(source1, Accessibility.Internal); } private void ValidatePropertyModifiers_22(string source1, Accessibility accessibility) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 set_P2 get_P3 set_P3 get_P4 set_P4 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); for (int i = 1; i <= 4; i++) { var i1 = m.GlobalNamespace.GetTypeMember("I" + i); var p1 = GetSingleProperty(i1); Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); switch (i) { case 1: case 3: ValidateAccessor(p1.GetMethod, accessibility); ValidateAccessor(p1.SetMethod, Accessibility.Public); break; case 2: case 4: ValidateAccessor(p1.GetMethod, Accessibility.Public); ValidateAccessor(p1.SetMethod, accessibility); break; default: Assert.False(true); break; } void ValidateAccessor(MethodSymbol accessor, Accessibility access) { Assert.False(accessor.IsAbstract); Assert.Equal(accessor.DeclaredAccessibility != Accessibility.Private, accessor.IsVirtual); Assert.Equal(accessor.DeclaredAccessibility != Accessibility.Private, accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(access, accessor.DeclaredAccessibility); Assert.Same(accessor.DeclaredAccessibility == Accessibility.Private ? null : accessor, test1.FindImplementationForInterfaceMember(accessor)); } } } } [Fact] public void PropertyModifiers_23_00() { var source1 = @" public interface I1 {} public interface I3 { int P3 { private get { System.Console.WriteLine(""get_P3""); return 0; } set {System.Console.WriteLine(""set_P3"");} } void M2() { P3 = P3; } } public interface I4 { int P4 { get {System.Console.WriteLine(""get_P4""); return 0;} private set {System.Console.WriteLine(""set_P4"");} } void M2() { P4 = P4; } } public interface I5 { int P5 { private get => GetP5(); set => System.Console.WriteLine(""set_P5""); } private int GetP5() { System.Console.WriteLine(""get_P5""); return 0; } void M2() { P5 = P5; } } public interface I6 { int P6 { get => GetP6(); private set => System.Console.WriteLine(""set_P6""); } private int GetP6() { System.Console.WriteLine(""get_P6""); return 0; } void M2() { P6 = P6; } } "; var source2 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public int P3 { get { throw null; } set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public int P4 { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } set { throw null; } } } class Test5 : I5 { public int P5 { get { throw null; } set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public int P6 { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } set { throw null; } } } "; ValidatePropertyModifiers_23(source1, source2); var source3 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public int P3 { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public int P4 { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test5 : I5 { public int P5 { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public int P6 { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } "; ValidatePropertyModifiers_23(source1, source3); var source4 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public virtual int P3 { get { throw null; } set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public virtual int P4 { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } set { throw null; } } } class Test5 : I5 { public virtual int P5 { get { throw null; } set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public virtual int P6 { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } set { throw null; } } } "; ValidatePropertyModifiers_23(source1, source4); var source5 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public virtual int P3 { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public virtual int P4 { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test5 : I5 { public virtual int P5 { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public virtual int P6 { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } "; ValidatePropertyModifiers_23(source1, source5); var source6 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { int I3.P3 { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { int I4.P4 { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test5 : I5 { int I5.P5 { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { int I6.P6 { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } "; ValidatePropertyModifiers_23(source1, source6); var source7 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test33(); I4 i4 = new Test44(); I5 i5 = new Test55(); I6 i6 = new Test66(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } interface Test3 : I3 { int I3.P3 { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test33 : Test3 {} interface Test4 : I4 { int I4.P4 { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test44 : Test4 {} interface Test5 : I5 { int I5.P5 { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test55 : Test5 {} interface Test6 : I6 { int I6.P6 { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } class Test66 : Test6 {} "; ValidatePropertyModifiers_23(source1, source7); } private void ValidatePropertyModifiers_23(string source1, string source2) { foreach (var metadataImportOptions in new[] { MetadataImportOptions.All, MetadataImportOptions.Public }) { var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe.WithMetadataImportOptions(metadataImportOptions), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var im = test1.InterfacesNoUseSiteDiagnostics().Single().ContainingModule; ValidateProperty23(GetSingleProperty(im, "I3"), false, Accessibility.Private, Accessibility.Public, m.GlobalNamespace.GetTypeMember("Test3")); ValidateProperty23(GetSingleProperty(im, "I4"), false, Accessibility.Public, Accessibility.Private, m.GlobalNamespace.GetTypeMember("Test4")); ValidateProperty23(GetSingleProperty(im, "I5"), false, Accessibility.Private, Accessibility.Public, m.GlobalNamespace.GetTypeMember("Test5")); ValidateProperty23(GetSingleProperty(im, "I6"), false, Accessibility.Public, Accessibility.Private, m.GlobalNamespace.GetTypeMember("Test6")); } var expectedOutput = @" get_P3 Test3.set_P3 Test4.get_P4 set_P4 get_P5 Test5.set_P5 Test6.get_P6 set_P6 "; CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(metadataImportOptions), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateProperty23(GetSingleProperty(compilation2, "I3"), false, Accessibility.Private, Accessibility.Public); ValidateProperty23(GetSingleProperty(compilation2, "I4"), false, Accessibility.Public, Accessibility.Private); ValidateProperty23(GetSingleProperty(compilation2, "I5"), false, Accessibility.Private, Accessibility.Public); ValidateProperty23(GetSingleProperty(compilation2, "I6"), false, Accessibility.Public, Accessibility.Private); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe.WithMetadataImportOptions(metadataImportOptions), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(); Validate1(compilation3.SourceModule); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); } } } private static void ValidateProperty23(PropertySymbol p1, bool isAbstract, Accessibility getAccess, Accessibility setAccess, NamedTypeSymbol test1 = null) { Assert.Equal(isAbstract, p1.IsAbstract); Assert.NotEqual(isAbstract, p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); PropertySymbol implementingProperty = null; if ((object)test1 != null) { implementingProperty = GetSingleProperty(test1); Assert.Same(implementingProperty, test1.FindImplementationForInterfaceMember(p1)); if (implementingProperty.GetMethod?.ExplicitInterfaceImplementations.Length > 0 || implementingProperty.SetMethod?.ExplicitInterfaceImplementations.Length > 0) { Assert.Same(p1, implementingProperty.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(implementingProperty.ExplicitInterfaceImplementations); } } ValidateMethod23(p1, p1.GetMethod, isAbstract, getAccess, test1, implementingProperty?.GetMethod); ValidateMethod23(p1, p1.SetMethod, isAbstract, setAccess, test1, implementingProperty?.SetMethod); } private static void ValidateMethod23(PropertySymbol p1, MethodSymbol m1, bool isAbstract, Accessibility access, NamedTypeSymbol test1, MethodSymbol implementingMethod) { if (m1 is null) { Assert.Equal(Accessibility.Private, access); Assert.Equal(MetadataImportOptions.Public, ((PEModuleSymbol)p1.ContainingModule).ImportOptions); return; } Assert.Equal(isAbstract, m1.IsAbstract); Assert.NotEqual(isAbstract || access == Accessibility.Private, m1.IsVirtual); Assert.Equal(isAbstract || access != Accessibility.Private, m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(access, m1.DeclaredAccessibility); if ((object)test1 != null) { Assert.Same(access != Accessibility.Private ? implementingMethod : null, test1.FindImplementationForInterfaceMember(m1)); } } [Fact] public void PropertyModifiers_23_01() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} void M2() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_23(source1, source2, Accessibility.Internal, Accessibility.Public, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) ); } private void ValidatePropertyModifiers_23(string source1, string source2, Accessibility getAccess, Accessibility setAccess, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); Validate1(compilation1.SourceModule); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => Validate1(m)).VerifyDiagnostics(); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var im = test1.InterfacesNoUseSiteDiagnostics().Single().ContainingModule; ValidateProperty23(GetSingleProperty(im, "I1"), true, getAccess, setAccess, test1); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); ValidateProperty23(GetSingleProperty(compilation2, "I1"), true, getAccess, setAccess); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected); Validate1(compilation3.SourceModule); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => Validate1(m)).VerifyDiagnostics(); Validate1(compilation3.SourceModule); } } [Fact] public void PropertyModifiers_23_02() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_23_03() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.Standard, // (9,12): error CS0122: 'I1.P1.get' is inaccessible due to its protection level // int I1.P1 Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1.get").WithLocation(9, 12) ); } [Fact] public void PropertyModifiers_23_04() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_05() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_06() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test3()); } public abstract int P1 {get; set;} } class Test3 : Test1 { public override int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_07() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallP1(new Test1()); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int P1 {get; set;} } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_08() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_08(source1, source2); } [Fact] public void PropertyModifiers_23_09() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_09(source1, source2, // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.P1'. 'Test1.P1' cannot implement 'I1.P1' because it does not have the matching return type of 'int'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.P1", "Test1.P1", "int").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_23_10() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} sealed void Test() { P1 = P1; } } "; var source2 = @" public class Test2 : I1 { public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_10(source1, source2, // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.get'. 'Test2.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.get", "Test2.P1.get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_11() { var source1 = @" public interface I1 { abstract int P1 {internal get; set;} sealed void Test() { P1 = P1; } } public class Test2 : I1 { public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_11(source1, source2, // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.get'. 'Test2.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.get", "Test2.P1.get", "9.0", "10.0").WithLocation(11, 22) ); } [Fact] public void PropertyModifiers_23_51() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} void M2() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_23(source1, source2, Accessibility.Public, Accessibility.Internal, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_23_52() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_23_53() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.Standard, // (9,12): error CS0122: 'I1.P1.set' is inaccessible due to its protection level // int I1.P1 Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1.set").WithLocation(9, 12) ); } [Fact] public void PropertyModifiers_23_54() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_55() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_56() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test3()); } public abstract int P1 {get; set;} } class Test3 : Test1 { public override int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_57() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallP1(new Test1()); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int P1 {get; set;} } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_58() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } public class Test2 : I1 { int I1.P1 { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_08(source1, source2); } [Fact] public void PropertyModifiers_23_59() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_09(source1, source2, // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.P1'. 'Test1.P1' cannot implement 'I1.P1' because it does not have the matching return type of 'int'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.P1", "Test1.P1", "int").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_23_60() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} sealed void Test() { P1 = P1; } } "; var source2 = @" public class Test2 : I1 { public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_10(source1, source2, // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.set'. 'Test2.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.set", "Test2.P1.set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void PropertyModifiers_23_61() { var source1 = @" public interface I1 { abstract int P1 {get; internal set;} sealed void Test() { P1 = P1; } } public class Test2 : I1 { public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_11(source1, source2, // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.set'. 'Test2.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.set", "Test2.P1.set", "9.0", "10.0").WithLocation(11, 22) ); } [Fact] public void PropertyModifiers_24() { var source1 = @" public interface I1 { int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } internal set { System.Console.WriteLine(""set_P1""); } } void M2() {P1 = P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidatePropertyModifiers_24(source1, source2); } private void ValidatePropertyModifiers_24(string source1, string source2) { var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var p1 = GetSingleProperty(i1); var p1get = p1.GetMethod; var p1set = p1.SetMethod; ValidateProperty(p1); ValidateMethod(p1get, Accessibility.Public); ValidateMethod(p1set, Accessibility.Internal); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(p1get, test1.FindImplementationForInterfaceMember(p1get)); Assert.Same(p1set, test1.FindImplementationForInterfaceMember(p1set)); } void ValidateProperty(PropertySymbol p1) { Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); } void ValidateMethod(MethodSymbol m1, Accessibility access) { Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(access, m1.DeclaredAccessibility); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var p1 = GetSingleProperty(i1); var p1get = p1.GetMethod; var p1set = p1.SetMethod; ValidateProperty(p1); ValidateMethod(p1get, Accessibility.Public); ValidateMethod(p1set, Accessibility.Internal); } var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation3.SourceModule); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation4.SourceModule); } [Fact] public void PropertyModifiers_25() { var source1 = @" public interface I1 { static int P1 { private get => throw null; set => throw null; } static int P2 { internal get => throw null; set => throw null; } public static int P3 { get => throw null; private set => throw null; } static int P4 { get => throw null; internal set => throw null; } } class Test1 { static void Main() { int x; x = I1.P1; I1.P1 = x; x = I1.P2; I1.P2 = x; x = I1.P3; I1.P3 = x; x = I1.P4; I1.P4 = x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (18,13): error CS0271: The property or indexer 'I1.P1' cannot be used in this context because the get accessor is inaccessible // x = I1.P1; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "I1.P1").WithArguments("I1.P1").WithLocation(18, 13), // (23,9): error CS0272: The property or indexer 'I1.P3' cannot be used in this context because the set accessor is inaccessible // I1.P3 = x; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "I1.P3").WithArguments("I1.P3").WithLocation(23, 9) ); var source2 = @" class Test2 { static void Main() { int x; x = I1.P1; I1.P1 = x; x = I1.P2; I1.P2 = x; x = I1.P3; I1.P3 = x; x = I1.P4; I1.P4 = x; } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (7,13): error CS0271: The property or indexer 'I1.P1' cannot be used in this context because the get accessor is inaccessible // x = I1.P1; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "I1.P1").WithArguments("I1.P1").WithLocation(7, 13), // (9,13): error CS0271: The property or indexer 'I1.P2' cannot be used in this context because the get accessor is inaccessible // x = I1.P2; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "I1.P2").WithArguments("I1.P2").WithLocation(9, 13), // (12,9): error CS0272: The property or indexer 'I1.P3' cannot be used in this context because the set accessor is inaccessible // I1.P3 = x; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "I1.P3").WithArguments("I1.P3").WithLocation(12, 9), // (14,9): error CS0272: The property or indexer 'I1.P4' cannot be used in this context because the set accessor is inaccessible // I1.P4 = x; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "I1.P4").WithArguments("I1.P4").WithLocation(14, 9) ); } [Fact] public void PropertyModifiers_26() { var source1 = @" public interface I1 { abstract int P1 { private get; set; } abstract int P2 { get; private set; } abstract int P3 { internal get; } static int P4 {internal get;} = 0; static int P5 { internal get {throw null;} } static int P6 { internal set {throw null;} } static int P7 { internal get => throw null; } static int P8 { internal set => throw null; } static int P9 { internal get {throw null;} private set {throw null;}} static int P10 { internal get => throw null; private set => throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,31): error CS0442: 'I1.P1.get': abstract properties cannot have private accessors // abstract int P1 { private get; set; } Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I1.P1.get").WithLocation(4, 31), // (5,36): error CS0442: 'I1.P2.set': abstract properties cannot have private accessors // abstract int P2 { get; private set; } Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "set").WithArguments("I1.P2.set").WithLocation(5, 36), // (6,18): error CS0276: 'I1.P3': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // abstract int P3 { internal get; } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P3").WithArguments("I1.P3").WithLocation(6, 18), // (7,16): error CS0276: 'I1.P4': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // static int P4 {internal get;} = 0; Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P4").WithArguments("I1.P4").WithLocation(7, 16), // (8,16): error CS0276: 'I1.P5': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // static int P5 { internal get {throw null;} } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P5").WithArguments("I1.P5").WithLocation(8, 16), // (9,16): error CS0276: 'I1.P6': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // static int P6 { internal set {throw null;} } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P6").WithArguments("I1.P6").WithLocation(9, 16), // (10,16): error CS0276: 'I1.P7': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // static int P7 { internal get => throw null; } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P7").WithArguments("I1.P7").WithLocation(10, 16), // (11,16): error CS0276: 'I1.P8': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // static int P8 { internal set => throw null; } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "P8").WithArguments("I1.P8").WithLocation(11, 16), // (12,16): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'I1.P9' // static int P9 { internal get {throw null;} private set {throw null;}} Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "P9").WithArguments("I1.P9").WithLocation(12, 16), // (13,16): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'I1.P10' // static int P10 { internal get => throw null; private set => throw null;} Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "P10").WithArguments("I1.P10").WithLocation(13, 16) ); } [Fact] public void PropertyModifiers_27() { var source1 = @" public interface I1 { int P3 { private get {throw null;} set {} } int P4 { get {throw null;} private set {} } } class Test1 : I1 { int I1.P3 { get {throw null;} set {} } int I1.P4 { get {throw null;} set {} } } interface ITest1 : I1 { int I1.P3 { get {throw null;} set {} } int I1.P4 { get {throw null;} set {} } } public interface I2 { int P5 { private get {throw null;} set {} } int P6 { get {throw null;} private set {} } class Test3 : I2 { int I2.P5 { get {throw null;} set {} } int I2.P6 { get {throw null;} set {} } } interface ITest3 : I2 { int I2.P5 { get {throw null;} set {} } int I2.P6 { get {throw null;} set {} } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // https://github.com/dotnet/roslyn/issues/34455: The wording "accessor not found in interface member" is somewhat misleading // in this scenario. The accessor is there, but cannot be implemented. Perhaps // the message should be adjusted. Should also check diagnostics for an attempt // to implement other sealed members. compilation1.VerifyDiagnostics( // (21,9): error CS0550: 'Test1.I1.P3.get' adds an accessor not found in interface member 'I1.P3' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("Test1.I1.P3.get", "I1.P3").WithLocation(21, 9), // (28,9): error CS0550: 'Test1.I1.P4.set' adds an accessor not found in interface member 'I1.P4' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("Test1.I1.P4.set", "I1.P4").WithLocation(28, 9), // (36,9): error CS0550: 'ITest1.I1.P3.get' adds an accessor not found in interface member 'I1.P3' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("ITest1.I1.P3.get", "I1.P3").WithLocation(36, 9), // (43,9): error CS0550: 'ITest1.I1.P4.set' adds an accessor not found in interface member 'I1.P4' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("ITest1.I1.P4.set", "I1.P4").WithLocation(43, 9), // (65,13): error CS0550: 'I2.Test3.I2.P5.get' adds an accessor not found in interface member 'I2.P5' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.Test3.I2.P5.get", "I2.P5").WithLocation(65, 13), // (72,13): error CS0550: 'I2.Test3.I2.P6.set' adds an accessor not found in interface member 'I2.P6' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.Test3.I2.P6.set", "I2.P6").WithLocation(72, 13), // (80,13): error CS0550: 'I2.ITest3.I2.P5.get' adds an accessor not found in interface member 'I2.P5' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.ITest3.I2.P5.get", "I2.P5").WithLocation(80, 13), // (87,13): error CS0550: 'I2.ITest3.I2.P6.set' adds an accessor not found in interface member 'I2.P6' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.ITest3.I2.P6.set", "I2.P6").WithLocation(87, 13) ); } [Fact] public void PropertyModifiers_28() { var source0 = @" public interface I1 { protected static int P1 { get { System.Console.WriteLine(""get_P1""); return 1; } set { System.Console.WriteLine(""set_P1""); } } protected internal static int P2 { get { System.Console.WriteLine(""get_P2""); return 2; } set { System.Console.WriteLine(""set_P2""); } } private protected static int P3 { get { System.Console.WriteLine(""get_P3""); return 3; } set { System.Console.WriteLine(""set_P3""); } } static int P4 { protected get { System.Console.WriteLine(""get_P4""); return 4; } set { System.Console.WriteLine(""set_P4""); } } static int P5 { get { System.Console.WriteLine(""get_P5""); return 5; } protected internal set { System.Console.WriteLine(""set_P5""); } } static int P6 { private protected get { System.Console.WriteLine(""get_P6""); return 6; } set { System.Console.WriteLine(""set_P6""); } } } "; var source1 = @" class Test1 : I1 { static void Main() { _ = I1.P1; I1.P1 = 11; _ = I1.P2; I1.P2 = 11; _ = I1.P3; I1.P3 = 11; _ = I1.P4; I1.P4 = 11; _ = I1.P5; I1.P5 = 11; _ = I1.P6; I1.P6 = 11; } } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 set_P2 get_P3 set_P3 get_P4 set_P4 get_P5 set_P5 get_P6 set_P6", symbolValidator: validate, verify: VerifyOnMonoOrCoreClr); validate(compilation1.SourceModule); var source2 = @" class Test1 { static void Main() { _ = I1.P2; I1.P2 = 11; I1.P4 = 11; _ = I1.P5; I1.P5 = 11; I1.P6 = 11; } } "; var compilation2 = CreateCompilation(source0 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P2 set_P2 set_P4 get_P5 set_P5 set_P6 ", verify: VerifyOnMonoOrCoreClr); var compilation3 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); var source3 = @" class Test1 : I1 { static void Main() { _ = I1.P1; I1.P1 = 11; _ = I1.P2; I1.P2 = 11; _ = I1.P4; I1.P4 = 11; _ = I1.P5; I1.P5 = 11; I1.P6 = 11; } } "; var source4 = @" class Test1 { static void Main() { I1.P4 = 11; _ = I1.P5; I1.P6 = 11; } } "; var source5 = @" class Test1 { static void Main() { _ = I1.P1; I1.P1 = 11; _ = I1.P2; I1.P2 = 11; _ = I1.P3; I1.P3 = 11; _ = I1.P4; I1.P5 = 11; _ = I1.P6; } } "; foreach (var reference in new[] { compilation3.ToMetadataReference(), compilation3.EmitToImageReference() }) { var compilation4 = CreateCompilation(source3, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 set_P2 get_P4 set_P4 get_P5 set_P5 set_P6 ", verify: VerifyOnMonoOrCoreClr); var compilation5 = CreateCompilation(source4, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"set_P4 get_P5 set_P6 ", verify: VerifyOnMonoOrCoreClr); var compilation6 = CreateCompilation(source5, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (6,16): error CS0122: 'I1.P1' is inaccessible due to its protection level // _ = I1.P1; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(6, 16), // (7,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 = 11; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(7, 12), // (8,16): error CS0122: 'I1.P2' is inaccessible due to its protection level // _ = I1.P2; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(8, 16), // (9,12): error CS0122: 'I1.P2' is inaccessible due to its protection level // I1.P2 = 11; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(9, 12), // (10,16): error CS0122: 'I1.P3' is inaccessible due to its protection level // _ = I1.P3; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(10, 16), // (11,12): error CS0122: 'I1.P3' is inaccessible due to its protection level // I1.P3 = 11; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(11, 12), // (12,13): error CS0271: The property or indexer 'I1.P4' cannot be used in this context because the get accessor is inaccessible // _ = I1.P4; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "I1.P4").WithArguments("I1.P4").WithLocation(12, 13), // (13,9): error CS0272: The property or indexer 'I1.P5' cannot be used in this context because the set accessor is inaccessible // I1.P5 = 11; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "I1.P5").WithArguments("I1.P5").WithLocation(13, 9), // (14,13): error CS0271: The property or indexer 'I1.P6' cannot be used in this context because the get accessor is inaccessible // _ = I1.P6; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "I1.P6").WithArguments("I1.P6").WithLocation(14, 13) ); var compilation7 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (10,16): error CS0122: 'I1.P3' is inaccessible due to its protection level // _ = I1.P3; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(10, 16), // (11,12): error CS0122: 'I1.P3' is inaccessible due to its protection level // I1.P3 = 11; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(11, 12), // (16,13): error CS0271: The property or indexer 'I1.P6' cannot be used in this context because the get accessor is inaccessible // _ = I1.P6; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "I1.P6").WithArguments("I1.P6").WithLocation(16, 13) ); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); foreach (var tuple in new[] { (name: "P1", access: Accessibility.Protected, getAccess: Accessibility.Protected, setAccess: Accessibility.Protected), (name: "P2", access: Accessibility.ProtectedOrInternal, getAccess: Accessibility.ProtectedOrInternal, setAccess: Accessibility.ProtectedOrInternal), (name: "P3", access: Accessibility.ProtectedAndInternal, getAccess: Accessibility.ProtectedAndInternal, setAccess: Accessibility.ProtectedAndInternal), (name: "P4", access: Accessibility.Public, getAccess: Accessibility.Protected, setAccess: Accessibility.Public), (name: "P5", access: Accessibility.Public, getAccess: Accessibility.Public, setAccess: Accessibility.ProtectedOrInternal), (name: "P6", access: Accessibility.Public, getAccess: Accessibility.ProtectedAndInternal, setAccess: Accessibility.Public)}) { var p1 = i1.GetMember<PropertySymbol>(tuple.name); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.True(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(tuple.access, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); validateAccessor(p1.GetMethod, tuple.getAccess); validateAccessor(p1.SetMethod, tuple.setAccess); } void validateAccessor(MethodSymbol accessor, Accessibility accessibility) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } [Fact] public void PropertyModifiers_29() { var source1 = @" public interface I1 { protected abstract int P1 {get; set;} sealed void Test() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_01(source1, source2, Accessibility.Protected, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_30() { var source1 = @" public interface I1 { protected internal abstract int P1 {get; set;} sealed void Test() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_01(source1, source2, Accessibility.ProtectedOrInternal, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_31() { var source1 = @" public interface I1 { private protected abstract int P1 {get; set;} sealed void Test() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_01(source1, source2, Accessibility.ProtectedAndInternal, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_32() { var source1 = @" public interface I1 { abstract int P1 {protected get; set;} void M2() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_23(source1, source2, Accessibility.Protected, Accessibility.Public, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_33() { var source1 = @" public interface I1 { abstract int P1 {protected internal get; set;} void M2() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_23(source1, source2, Accessibility.ProtectedOrInternal, Accessibility.Public, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.get'. 'Test1.P1.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.get", "Test1.P1.get", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_34() { var source1 = @" public interface I1 { abstract int P1 {get; private protected set;} void M2() { P1 = P1; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_23(source1, source2, Accessibility.Public, Accessibility.ProtectedAndInternal, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.set'. 'Test1.P1.set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.set", "Test1.P1.set", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void PropertyModifiers_35() { var source1 = @" public interface I1 { protected abstract int P1 {get; set;} public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.NetCoreApp); } [Fact] public void PropertyModifiers_36() { var source1 = @" public interface I1 { protected internal abstract int P1 {get; set;} public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.NetCoreApp); } [Fact] public void PropertyModifiers_37() { var source1 = @" public interface I1 { private protected abstract int P1 {get; set;} public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.NetCoreApp, // (9,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // int I1.P1 Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(9, 12) ); } [Fact] public void PropertyModifiers_38() { var source1 = @" public interface I1 { abstract int P1 {protected get; set;} public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.NetCoreApp); } [Fact] public void PropertyModifiers_39() { var source1 = @" public interface I1 { abstract int P1 {get; protected internal set;} public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.NetCoreApp); } [Fact] public void PropertyModifiers_40() { var source1 = @" public interface I1 { abstract int P1 { private protected get; set;} public static void CallP1(I1 x) {x.P1 = x.P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } int I1.P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.NetCoreApp, // (9,12): error CS0122: 'I1.P1.get' is inaccessible due to its protection level // int I1.P1 Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1.get").WithLocation(9, 12) ); } [Fact] public void PropertyModifiers_41() { var source1 = @" public interface I1 { protected int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } void M2() {P1 = P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidatePropertyModifiers_20(source1, source2, Accessibility.Protected); } [Fact] public void PropertyModifiers_42() { var source1 = @" public interface I1 { protected internal int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } void M2() {P1 = P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidatePropertyModifiers_20(source1, source2, Accessibility.ProtectedOrInternal); } [Fact] public void PropertyModifiers_43() { var source1 = @" public interface I1 { private protected int P1 { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } void M2() {P1 = P1;} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidatePropertyModifiers_20(source1, source2, Accessibility.ProtectedAndInternal); } [Fact] public void PropertyModifiers_44() { var source1 = @" public interface I1 { public int P1 { protected get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } static void Test(I1 i1) { i1.P1 = i1.P1; } } public interface I2 { int P2 { get { System.Console.WriteLine(""get_P2""); return 0; } protected set { System.Console.WriteLine(""set_P2""); } } static void Test(I2 i2) { i2.P2 = i2.P2; } } public interface I3 { int P3 { protected get => Test1.GetP3(); set => System.Console.WriteLine(""set_P3""); } static void Test(I3 i3) { i3.P3 = i3.P3; } } public interface I4 { int P4 { get => Test1.GetP4(); protected set => System.Console.WriteLine(""set_P4""); } static void Test(I4 i4) { i4.P4 = i4.P4; } } class Test1 : I1, I2, I3, I4 { static void Main() { I1.Test(new Test1()); I2.Test(new Test1()); I3.Test(new Test1()); I4.Test(new Test1()); } public static int GetP3() { System.Console.WriteLine(""get_P3""); return 0; } public static int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } } "; ValidatePropertyModifiers_22(source1, Accessibility.Protected); } [Fact] public void PropertyModifiers_45() { var source1 = @" public interface I1 { public int P1 { protected internal get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int P2 { get { System.Console.WriteLine(""get_P2""); return 0; } protected internal set { System.Console.WriteLine(""set_P2""); } } } public interface I3 { int P3 { protected internal get => Test1.GetP3(); set => System.Console.WriteLine(""set_P3""); } } public interface I4 { int P4 { get => Test1.GetP4(); protected internal set => System.Console.WriteLine(""set_P4""); } } class Test1 : I1, I2, I3, I4 { static void Main() { I1 i1 = new Test1(); I2 i2 = new Test1(); I3 i3 = new Test1(); I4 i4 = new Test1(); i1.P1 = i1.P1; i2.P2 = i2.P2; i3.P3 = i3.P3; i4.P4 = i4.P4; } public static int GetP3() { System.Console.WriteLine(""get_P3""); return 0; } public static int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } } "; ValidatePropertyModifiers_22(source1, Accessibility.ProtectedOrInternal); } [Fact] public void PropertyModifiers_46() { var source1 = @" public interface I1 { public int P1 { private protected get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } static void Test(I1 i1) { i1.P1 = i1.P1; } } public interface I2 { int P2 { get { System.Console.WriteLine(""get_P2""); return 0; } private protected set { System.Console.WriteLine(""set_P2""); } } static void Test(I2 i2) { i2.P2 = i2.P2; } } public interface I3 { int P3 { private protected get => Test1.GetP3(); set => System.Console.WriteLine(""set_P3""); } static void Test(I3 i3) { i3.P3 = i3.P3; } } public interface I4 { int P4 { get => Test1.GetP4(); private protected set => System.Console.WriteLine(""set_P4""); } static void Test(I4 i4) { i4.P4 = i4.P4; } } class Test1 : I1, I2, I3, I4 { static void Main() { I1.Test(new Test1()); I2.Test(new Test1()); I3.Test(new Test1()); I4.Test(new Test1()); } public static int GetP3() { System.Console.WriteLine(""get_P3""); return 0; } public static int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } } "; ValidatePropertyModifiers_22(source1, Accessibility.ProtectedAndInternal); } [Fact] public void IndexerModifiers_01() { var source1 = @" public interface I01{ public int this[int x] {get; set;} } public interface I02{ protected int this[int x] {get;} } public interface I03{ protected internal int this[int x] {set;} } public interface I04{ internal int this[int x] {get;} } public interface I05{ private int this[int x] {set;} } public interface I06{ static int this[int x] {get;} } public interface I07{ virtual int this[int x] {set;} } public interface I08{ sealed int this[int x] {get;} } public interface I09{ override int this[int x] {set;} } public interface I10{ abstract int this[int x] {get;} } public interface I11{ extern int this[int x] {get; set;} } public interface I12{ int this[int x] { public get; set;} } public interface I13{ int this[int x] { get; protected set;} } public interface I14{ int this[int x] { protected internal get; set;} } public interface I15{ int this[int x] { get; internal set;} } public interface I16{ int this[int x] { private get; set;} } public interface I17{ int this[int x] { private get;} } public interface I18{ private protected int this[int x] { get; } } public interface I19{ int this[int x] { get; private protected set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (6,48): error CS0501: 'I05.this[int].set' must declare a body because it is not marked abstract, extern, or partial // public interface I05{ private int this[int x] {set;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I05.this[int].set").WithLocation(6, 48), // (7,34): error CS0106: The modifier 'static' is not valid for this item // public interface I06{ static int this[int x] {get;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(7, 34), // (8,48): error CS0501: 'I07.this[int].set' must declare a body because it is not marked abstract, extern, or partial // public interface I07{ virtual int this[int x] {set;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I07.this[int].set").WithLocation(8, 48), // (9,47): error CS0501: 'I08.this[int].get' must declare a body because it is not marked abstract, extern, or partial // public interface I08{ sealed int this[int x] {get;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I08.this[int].get").WithLocation(9, 47), // (10,36): error CS0106: The modifier 'override' is not valid for this item // public interface I09{ override int this[int x] {set;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("override").WithLocation(10, 36), // (14,48): error CS0273: The accessibility modifier of the 'I12.this[int].get' accessor must be more restrictive than the property or indexer 'I12.this[int]' // public interface I12{ int this[int x] { public get; set;} } Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("I12.this[int].get", "I12.this[int]").WithLocation(14, 48), // (18,49): error CS0442: 'I16.this[int].get': abstract properties cannot have private accessors // public interface I16{ int this[int x] { private get; set;} } Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I16.this[int].get").WithLocation(18, 49), // (19,27): error CS0276: 'I17.this[int]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // public interface I17{ int this[int x] { private get;} } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I17.this[int]").WithLocation(19, 27), // (12,47): warning CS0626: Method, operator, or accessor 'I11.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I11.this[int].get").WithLocation(12, 47), // (12,52): warning CS0626: Method, operator, or accessor 'I11.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I11.this[int].set").WithLocation(12, 52) ); ValidateSymbolsIndexerModifiers_01(compilation1); } private static void ValidateSymbolsIndexerModifiers_01(CSharpCompilation compilation1) { var p01 = compilation1.GetMember<PropertySymbol>("I01.this[]"); Assert.True(p01.IsAbstract); Assert.False(p01.IsVirtual); Assert.False(p01.IsSealed); Assert.False(p01.IsStatic); Assert.False(p01.IsExtern); Assert.False(p01.IsOverride); Assert.Equal(Accessibility.Public, p01.DeclaredAccessibility); ValidateP01Accessor(p01.GetMethod); ValidateP01Accessor(p01.SetMethod); void ValidateP01Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } var p02 = compilation1.GetMember<PropertySymbol>("I02.this[]"); var p02get = p02.GetMethod; Assert.True(p02.IsAbstract); Assert.False(p02.IsVirtual); Assert.False(p02.IsSealed); Assert.False(p02.IsStatic); Assert.False(p02.IsExtern); Assert.False(p02.IsOverride); Assert.Equal(Accessibility.Protected, p02.DeclaredAccessibility); Assert.True(p02get.IsAbstract); Assert.False(p02get.IsVirtual); Assert.True(p02get.IsMetadataVirtual()); Assert.False(p02get.IsSealed); Assert.False(p02get.IsStatic); Assert.False(p02get.IsExtern); Assert.False(p02get.IsAsync); Assert.False(p02get.IsOverride); Assert.Equal(Accessibility.Protected, p02get.DeclaredAccessibility); var p03 = compilation1.GetMember<PropertySymbol>("I03.this[]"); var p03set = p03.SetMethod; Assert.True(p03.IsAbstract); Assert.False(p03.IsVirtual); Assert.False(p03.IsSealed); Assert.False(p03.IsStatic); Assert.False(p03.IsExtern); Assert.False(p03.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, p03.DeclaredAccessibility); Assert.True(p03set.IsAbstract); Assert.False(p03set.IsVirtual); Assert.True(p03set.IsMetadataVirtual()); Assert.False(p03set.IsSealed); Assert.False(p03set.IsStatic); Assert.False(p03set.IsExtern); Assert.False(p03set.IsAsync); Assert.False(p03set.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, p03set.DeclaredAccessibility); var p04 = compilation1.GetMember<PropertySymbol>("I04.this[]"); var p04get = p04.GetMethod; Assert.True(p04.IsAbstract); Assert.False(p04.IsVirtual); Assert.False(p04.IsSealed); Assert.False(p04.IsStatic); Assert.False(p04.IsExtern); Assert.False(p04.IsOverride); Assert.Equal(Accessibility.Internal, p04.DeclaredAccessibility); Assert.True(p04get.IsAbstract); Assert.False(p04get.IsVirtual); Assert.True(p04get.IsMetadataVirtual()); Assert.False(p04get.IsSealed); Assert.False(p04get.IsStatic); Assert.False(p04get.IsExtern); Assert.False(p04get.IsAsync); Assert.False(p04get.IsOverride); Assert.Equal(Accessibility.Internal, p04get.DeclaredAccessibility); var p05 = compilation1.GetMember<PropertySymbol>("I05.this[]"); var p05set = p05.SetMethod; Assert.False(p05.IsAbstract); Assert.False(p05.IsVirtual); Assert.False(p05.IsSealed); Assert.False(p05.IsStatic); Assert.False(p05.IsExtern); Assert.False(p05.IsOverride); Assert.Equal(Accessibility.Private, p05.DeclaredAccessibility); Assert.False(p05set.IsAbstract); Assert.False(p05set.IsVirtual); Assert.False(p05set.IsMetadataVirtual()); Assert.False(p05set.IsSealed); Assert.False(p05set.IsStatic); Assert.False(p05set.IsExtern); Assert.False(p05set.IsAsync); Assert.False(p05set.IsOverride); Assert.Equal(Accessibility.Private, p05set.DeclaredAccessibility); var p06 = compilation1.GetMember<PropertySymbol>("I06.this[]"); var p06get = p06.GetMethod; Assert.True(p06.IsAbstract); Assert.False(p06.IsVirtual); Assert.False(p06.IsSealed); Assert.False(p06.IsStatic); Assert.False(p06.IsExtern); Assert.False(p06.IsOverride); Assert.Equal(Accessibility.Public, p06.DeclaredAccessibility); Assert.True(p06get.IsAbstract); Assert.False(p06get.IsVirtual); Assert.True(p06get.IsMetadataVirtual()); Assert.False(p06get.IsSealed); Assert.False(p06get.IsStatic); Assert.False(p06get.IsExtern); Assert.False(p06get.IsAsync); Assert.False(p06get.IsOverride); Assert.Equal(Accessibility.Public, p06get.DeclaredAccessibility); var p07 = compilation1.GetMember<PropertySymbol>("I07.this[]"); var p07set = p07.SetMethod; Assert.False(p07.IsAbstract); Assert.True(p07.IsVirtual); Assert.False(p07.IsSealed); Assert.False(p07.IsStatic); Assert.False(p07.IsExtern); Assert.False(p07.IsOverride); Assert.Equal(Accessibility.Public, p07.DeclaredAccessibility); Assert.False(p07set.IsAbstract); Assert.True(p07set.IsVirtual); Assert.True(p07set.IsMetadataVirtual()); Assert.False(p07set.IsSealed); Assert.False(p07set.IsStatic); Assert.False(p07set.IsExtern); Assert.False(p07set.IsAsync); Assert.False(p07set.IsOverride); Assert.Equal(Accessibility.Public, p07set.DeclaredAccessibility); var p08 = compilation1.GetMember<PropertySymbol>("I08.this[]"); var p08get = p08.GetMethod; Assert.False(p08.IsAbstract); Assert.False(p08.IsVirtual); Assert.False(p08.IsSealed); Assert.False(p08.IsStatic); Assert.False(p08.IsExtern); Assert.False(p08.IsOverride); Assert.Equal(Accessibility.Public, p08.DeclaredAccessibility); Assert.False(p08get.IsAbstract); Assert.False(p08get.IsVirtual); Assert.False(p08get.IsMetadataVirtual()); Assert.False(p08get.IsSealed); Assert.False(p08get.IsStatic); Assert.False(p08get.IsExtern); Assert.False(p08get.IsAsync); Assert.False(p08get.IsOverride); Assert.Equal(Accessibility.Public, p08get.DeclaredAccessibility); var p09 = compilation1.GetMember<PropertySymbol>("I09.this[]"); var p09set = p09.SetMethod; Assert.True(p09.IsAbstract); Assert.False(p09.IsVirtual); Assert.False(p09.IsSealed); Assert.False(p09.IsStatic); Assert.False(p09.IsExtern); Assert.False(p09.IsOverride); Assert.Equal(Accessibility.Public, p09.DeclaredAccessibility); Assert.True(p09set.IsAbstract); Assert.False(p09set.IsVirtual); Assert.True(p09set.IsMetadataVirtual()); Assert.False(p09set.IsSealed); Assert.False(p09set.IsStatic); Assert.False(p09set.IsExtern); Assert.False(p09set.IsAsync); Assert.False(p09set.IsOverride); Assert.Equal(Accessibility.Public, p09set.DeclaredAccessibility); var p10 = compilation1.GetMember<PropertySymbol>("I10.this[]"); var p10get = p10.GetMethod; Assert.True(p10.IsAbstract); Assert.False(p10.IsVirtual); Assert.False(p10.IsSealed); Assert.False(p10.IsStatic); Assert.False(p10.IsExtern); Assert.False(p10.IsOverride); Assert.Equal(Accessibility.Public, p10.DeclaredAccessibility); Assert.True(p10get.IsAbstract); Assert.False(p10get.IsVirtual); Assert.True(p10get.IsMetadataVirtual()); Assert.False(p10get.IsSealed); Assert.False(p10get.IsStatic); Assert.False(p10get.IsExtern); Assert.False(p10get.IsAsync); Assert.False(p10get.IsOverride); Assert.Equal(Accessibility.Public, p10get.DeclaredAccessibility); var p11 = compilation1.GetMember<PropertySymbol>("I11.this[]"); Assert.False(p11.IsAbstract); Assert.True(p11.IsVirtual); Assert.False(p11.IsSealed); Assert.False(p11.IsStatic); Assert.True(p11.IsExtern); Assert.False(p11.IsOverride); Assert.Equal(Accessibility.Public, p11.DeclaredAccessibility); ValidateP11Accessor(p11.GetMethod); ValidateP11Accessor(p11.SetMethod); void ValidateP11Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } var p12 = compilation1.GetMember<PropertySymbol>("I12.this[]"); Assert.True(p12.IsAbstract); Assert.False(p12.IsVirtual); Assert.False(p12.IsSealed); Assert.False(p12.IsStatic); Assert.False(p12.IsExtern); Assert.False(p12.IsOverride); Assert.Equal(Accessibility.Public, p12.DeclaredAccessibility); ValidateP12Accessor(p12.GetMethod); ValidateP12Accessor(p12.SetMethod); void ValidateP12Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } var p13 = compilation1.GetMember<PropertySymbol>("I13.this[]"); Assert.True(p13.IsAbstract); Assert.False(p13.IsVirtual); Assert.False(p13.IsSealed); Assert.False(p13.IsStatic); Assert.False(p13.IsExtern); Assert.False(p13.IsOverride); Assert.Equal(Accessibility.Public, p13.DeclaredAccessibility); ValidateP13Accessor(p13.GetMethod, Accessibility.Public); ValidateP13Accessor(p13.SetMethod, Accessibility.Protected); void ValidateP13Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p14 = compilation1.GetMember<PropertySymbol>("I14.this[]"); Assert.True(p14.IsAbstract); Assert.False(p14.IsVirtual); Assert.False(p14.IsSealed); Assert.False(p14.IsStatic); Assert.False(p14.IsExtern); Assert.False(p14.IsOverride); Assert.Equal(Accessibility.Public, p14.DeclaredAccessibility); ValidateP14Accessor(p14.GetMethod, Accessibility.ProtectedOrInternal); ValidateP14Accessor(p14.SetMethod, Accessibility.Public); void ValidateP14Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p15 = compilation1.GetMember<PropertySymbol>("I15.this[]"); Assert.True(p15.IsAbstract); Assert.False(p15.IsVirtual); Assert.False(p15.IsSealed); Assert.False(p15.IsStatic); Assert.False(p15.IsExtern); Assert.False(p15.IsOverride); Assert.Equal(Accessibility.Public, p15.DeclaredAccessibility); ValidateP15Accessor(p15.GetMethod, Accessibility.Public); ValidateP15Accessor(p15.SetMethod, Accessibility.Internal); void ValidateP15Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p16 = compilation1.GetMember<PropertySymbol>("I16.this[]"); Assert.True(p16.IsAbstract); Assert.False(p16.IsVirtual); Assert.False(p16.IsSealed); Assert.False(p16.IsStatic); Assert.False(p16.IsExtern); Assert.False(p16.IsOverride); Assert.Equal(Accessibility.Public, p16.DeclaredAccessibility); ValidateP16Accessor(p16.GetMethod, Accessibility.Private); ValidateP16Accessor(p16.SetMethod, Accessibility.Public); void ValidateP16Accessor(MethodSymbol accessor, Accessibility accessibility) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(accessibility, accessor.DeclaredAccessibility); } var p17 = compilation1.GetMember<PropertySymbol>("I17.this[]"); var p17get = p17.GetMethod; Assert.True(p17.IsAbstract); Assert.False(p17.IsVirtual); Assert.False(p17.IsSealed); Assert.False(p17.IsStatic); Assert.False(p17.IsExtern); Assert.False(p17.IsOverride); Assert.Equal(Accessibility.Public, p17.DeclaredAccessibility); Assert.True(p17get.IsAbstract); Assert.False(p17get.IsVirtual); Assert.True(p17get.IsMetadataVirtual()); Assert.False(p17get.IsSealed); Assert.False(p17get.IsStatic); Assert.False(p17get.IsExtern); Assert.False(p17get.IsAsync); Assert.False(p17get.IsOverride); Assert.Equal(Accessibility.Private, p17get.DeclaredAccessibility); var p18 = compilation1.GetMember<PropertySymbol>("I18.this[]"); var p18get = p18.GetMethod; Assert.True(p18.IsAbstract); Assert.False(p18.IsVirtual); Assert.False(p18.IsSealed); Assert.False(p18.IsStatic); Assert.False(p18.IsExtern); Assert.False(p18.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, p18.DeclaredAccessibility); Assert.True(p18get.IsAbstract); Assert.False(p18get.IsVirtual); Assert.True(p18get.IsMetadataVirtual()); Assert.False(p18get.IsSealed); Assert.False(p18get.IsStatic); Assert.False(p18get.IsExtern); Assert.False(p18get.IsAsync); Assert.False(p18get.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, p18get.DeclaredAccessibility); var p19 = compilation1.GetMember<PropertySymbol>("I19.this[]"); Assert.True(p19.IsAbstract); Assert.False(p19.IsVirtual); Assert.False(p19.IsSealed); Assert.False(p19.IsStatic); Assert.False(p19.IsExtern); Assert.False(p19.IsOverride); Assert.Equal(Accessibility.Public, p19.DeclaredAccessibility); ValidateP13Accessor(p19.GetMethod, Accessibility.Public); ValidateP13Accessor(p19.SetMethod, Accessibility.ProtectedAndInternal); } [Fact] public void IndexerModifiers_02() { var source1 = @" public interface I01{ public int this[int x] {get; set;} } public interface I02{ protected int this[int x] {get;} } public interface I03{ protected internal int this[int x] {set;} } public interface I04{ internal int this[int x] {get;} } public interface I05{ private int this[int x] {set;} } public interface I06{ static int this[int x] {get;} } public interface I07{ virtual int this[int x] {set;} } public interface I08{ sealed int this[int x] {get;} } public interface I09{ override int this[int x] {set;} } public interface I10{ abstract int this[int x] {get;} } public interface I11{ extern int this[int x] {get; set;} } public interface I12{ int this[int x] { public get; set;} } public interface I13{ int this[int x] { get; protected set;} } public interface I14{ int this[int x] { protected internal get; set;} } public interface I15{ int this[int x] { get; internal set;} } public interface I16{ int this[int x] { private get; set;} } public interface I17{ int this[int x] { private get;} } public interface I18{ private protected int this[int x] { get; } } public interface I19{ int this[int x] { get; private protected set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (2,34): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I01{ public int this[int x] {get; set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("public", "7.3", "8.0").WithLocation(2, 34), // (3,37): error CS8703: The modifier 'protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I02{ protected int this[int x] {get;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("protected", "7.3", "8.0").WithLocation(3, 37), // (4,46): error CS8703: The modifier 'protected internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I03{ protected internal int this[int x] {set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("protected internal", "7.3", "8.0").WithLocation(4, 46), // (5,36): error CS8503: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I04{ internal int this[int x] {get;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("internal", "7.3", "8.0").WithLocation(5, 36), // (6,35): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I05{ private int this[int x] {set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("private", "7.3", "8.0").WithLocation(6, 35), // (6,48): error CS0501: 'I05.this[int].set' must declare a body because it is not marked abstract, extern, or partial // public interface I05{ private int this[int x] {set;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I05.this[int].set").WithLocation(6, 48), // (7,34): error CS0106: The modifier 'static' is not valid for this item // public interface I06{ static int this[int x] {get;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(7, 34), // (8,35): error CS8503: The modifier 'virtual' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I07{ virtual int this[int x] {set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("virtual", "7.3", "8.0").WithLocation(8, 35), // (8,48): error CS0501: 'I07.this[int].set' must declare a body because it is not marked abstract, extern, or partial // public interface I07{ virtual int this[int x] {set;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I07.this[int].set").WithLocation(8, 48), // (9,34): error CS8503: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I08{ sealed int this[int x] {get;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("sealed", "7.3", "8.0").WithLocation(9, 34), // (9,47): error CS0501: 'I08.this[int].get' must declare a body because it is not marked abstract, extern, or partial // public interface I08{ sealed int this[int x] {get;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I08.this[int].get").WithLocation(9, 47), // (10,36): error CS0106: The modifier 'override' is not valid for this item // public interface I09{ override int this[int x] {set;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("override").WithLocation(10, 36), // (11,36): error CS8503: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I10{ abstract int this[int x] {get;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("abstract", "7.3", "8.0").WithLocation(11, 36), // (12,34): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("extern", "7.3", "8.0").WithLocation(12, 34), // (14,48): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I12{ int this[int x] { public get; set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("public", "7.3", "8.0").WithLocation(14, 48), // (14,48): error CS0273: The accessibility modifier of the 'I12.this[int].get' accessor must be more restrictive than the property or indexer 'I12.this[int]' // public interface I12{ int this[int x] { public get; set;} } Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("I12.this[int].get", "I12.this[int]").WithLocation(14, 48), // (15,56): error CS8703: The modifier 'protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I13{ int this[int x] { get; protected set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("protected", "7.3", "8.0").WithLocation(15, 56), // (16,60): error CS8703: The modifier 'protected internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I14{ int this[int x] { protected internal get; set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("protected internal", "7.3", "8.0").WithLocation(16, 60), // (17,55): error CS8503: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I15{ int this[int x] { get; internal set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("internal", "7.3", "8.0").WithLocation(17, 55), // (18,49): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I16{ int this[int x] { private get; set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("private", "7.3", "8.0").WithLocation(18, 49), // (18,49): error CS0442: 'I16.this[int].get': abstract properties cannot have private accessors // public interface I16{ int this[int x] { private get; set;} } Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I16.this[int].get").WithLocation(18, 49), // (19,49): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I17{ int this[int x] { private get;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("private", "7.3", "8.0").WithLocation(19, 49), // (19,27): error CS0276: 'I17.this[int]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // public interface I17{ int this[int x] { private get;} } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I17.this[int]").WithLocation(19, 27), // (21,45): error CS8703: The modifier 'private protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I18{ private protected int this[int x] { get; } } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("private protected", "7.3", "8.0").WithLocation(21, 45), // (22,64): error CS8703: The modifier 'private protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public interface I19{ int this[int x] { get; private protected set;} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("private protected", "7.3", "8.0").WithLocation(22, 64), // (12,47): warning CS0626: Method, operator, or accessor 'I11.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I11.this[int].get").WithLocation(12, 47), // (12,52): warning CS0626: Method, operator, or accessor 'I11.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I11.this[int].set").WithLocation(12, 52) ); ValidateSymbolsIndexerModifiers_01(compilation1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (3,37): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // public interface I02{ protected int this[int x] {get;} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "this").WithLocation(3, 37), // (4,46): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // public interface I03{ protected internal int this[int x] {set;} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "this").WithLocation(4, 46), // (6,48): error CS0501: 'I05.this[int].set' must declare a body because it is not marked abstract, extern, or partial // public interface I05{ private int this[int x] {set;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I05.this[int].set").WithLocation(6, 48), // (7,34): error CS0106: The modifier 'static' is not valid for this item // public interface I06{ static int this[int x] {get;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(7, 34), // (8,48): error CS0501: 'I07.this[int].set' must declare a body because it is not marked abstract, extern, or partial // public interface I07{ virtual int this[int x] {set;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I07.this[int].set").WithLocation(8, 48), // (9,47): error CS0501: 'I08.this[int].get' must declare a body because it is not marked abstract, extern, or partial // public interface I08{ sealed int this[int x] {get;} } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I08.this[int].get").WithLocation(9, 47), // (10,36): error CS0106: The modifier 'override' is not valid for this item // public interface I09{ override int this[int x] {set;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("override").WithLocation(10, 36), // (12,47): error CS8701: Target runtime doesn't support default interface implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(12, 47), // (12,47): warning CS0626: Method, operator, or accessor 'I11.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I11.this[int].get").WithLocation(12, 47), // (12,52): error CS8701: Target runtime doesn't support default interface implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(12, 52), // (12,52): warning CS0626: Method, operator, or accessor 'I11.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public interface I11{ extern int this[int x] {get; set;} } Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I11.this[int].set").WithLocation(12, 52), // (14,48): error CS0273: The accessibility modifier of the 'I12.this[int].get' accessor must be more restrictive than the property or indexer 'I12.this[int]' // public interface I12{ int this[int x] { public get; set;} } Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("I12.this[int].get", "I12.this[int]").WithLocation(14, 48), // (15,56): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // public interface I13{ int this[int x] { get; protected set;} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "set").WithLocation(15, 56), // (16,60): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // public interface I14{ int this[int x] { protected internal get; set;} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "get").WithLocation(16, 60), // (18,49): error CS0442: 'I16.this[int].get': abstract properties cannot have private accessors // public interface I16{ int this[int x] { private get; set;} } Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I16.this[int].get").WithLocation(18, 49), // (19,27): error CS0276: 'I17.this[int]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // public interface I17{ int this[int x] { private get;} } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I17.this[int]").WithLocation(19, 27), // (21,45): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // public interface I18{ private protected int this[int x] { get; } } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "this").WithLocation(21, 45), // (22,64): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // public interface I19{ int this[int x] { get; private protected set;} } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "set").WithLocation(22, 64) ); ValidateSymbolsIndexerModifiers_01(compilation2); } [Fact] public void IndexerModifiers_03() { ValidateIndexerImplementation_101(@" public interface I1 { public virtual int this[int i] { get { System.Console.WriteLine(""get P1""); return 0; } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "); ValidateIndexerImplementation_101(@" public interface I1 { public virtual int this[int i] { get => Test1.GetP1(); } } class Test1 : I1 { public static int GetP1() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "); ValidateIndexerImplementation_101(@" public interface I1 { public virtual int this[int i] => Test1.GetP1(); } class Test1 : I1 { public static int GetP1() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "); ValidateIndexerImplementation_102(@" public interface I1 { public virtual int this[int i] { get { System.Console.WriteLine(""get P1""); return 0; } set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1[0] = i1[0]; } } "); ValidateIndexerImplementation_102(@" public interface I1 { public virtual int this[int i] { get => Test1.GetP1(); set => System.Console.WriteLine(""set P1""); } } class Test1 : I1 { public static int GetP1() { System.Console.WriteLine(""get P1""); return 0; } static void Main() { I1 i1 = new Test1(); i1[0] = i1[0]; } } "); ValidateIndexerImplementation_103(@" public interface I1 { public virtual int this[int i] { set { System.Console.WriteLine(""set P1""); } } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } } "); ValidateIndexerImplementation_103(@" public interface I1 { public virtual int this[int i] { set => System.Console.WriteLine(""set P1""); } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } } "); } [Fact] public void IndexerModifiers_04() { var source1 = @" public interface I1 { public virtual int this[int x] { get; } = 0; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (4,45): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // public virtual int this[int x] { get; } = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(4, 45), // (4,38): error CS0501: 'I1.this[int].get' must declare a body because it is not marked abstract, extern, or partial // public virtual int this[int x] { get; } = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.this[int].get").WithLocation(4, 38) ); ValidatePropertyModifiers_04(compilation1, "this[]"); } [Fact] public void IndexerModifiers_05() { var source1 = @" public interface I1 { public abstract int this[int x] {get; set;} } public interface I2 { int this[int x] {get; set;} } class Test1 : I1 { public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set => System.Console.WriteLine(""set_P1""); } } class Test2 : I2 { public int this[int x] { get { System.Console.WriteLine(""get_P2""); return 0; } set => System.Console.WriteLine(""set_P2""); } static void Main() { I1 x = new Test1(); x[0] = x[0]; I2 y = new Test2(); y[0] = y[0]; } } "; ValidatePropertyModifiers_05(source1); } [Fact] public void IndexerModifiers_06() { var source1 = @" public interface I1 { public abstract int this[int x] {get; set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3); compilation1.VerifyDiagnostics( // (4,25): error CS8503: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract int this[int x] {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("abstract", "7.3", "8.0").WithLocation(4, 25), // (4,25): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract int this[int x] {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("public", "7.3", "8.0").WithLocation(4, 25) ); ValidatePropertyModifiers_06(compilation1, "this[]"); } [Fact] public void IndexerModifiers_09() { var source1 = @" public interface I1 { private int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } } sealed void M() { var x = this[0]; } } public interface I2 { private int this[int x] { get { System.Console.WriteLine(""get_P2""); return 0; } set { System.Console.WriteLine(""set_P2""); } } sealed void M() { this[0] = this[0]; } } public interface I3 { private int this[int x] { set { System.Console.WriteLine(""set_P3""); } } sealed void M() { this[0] = 0; } } public interface I4 { private int this[int x] { get => GetP4(); } private int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } sealed void M() { var x = this[0]; } } public interface I5 { private int this[int x] { get => GetP5(); set => System.Console.WriteLine(""set_P5""); } private int GetP5() { System.Console.WriteLine(""get_P5""); return 0; } sealed void M() { this[0] = this[0]; } } public interface I6 { private int this[int x] { set => System.Console.WriteLine(""set_P6""); } sealed void M() { this[0] = 0; } } public interface I7 { private int this[int x] => GetP7(); private int GetP7() { System.Console.WriteLine(""get_P7""); return 0; } sealed void M() { var x = this[0]; } } class Test1 : I1, I2, I3, I4, I5, I6, I7 { static void Main() { I1 x1 = new Test1(); x1.M(); I2 x2 = new Test1(); x2.M(); I3 x3 = new Test1(); x3.M(); I4 x4 = new Test1(); x4.M(); I5 x5 = new Test1(); x5.M(); I6 x6 = new Test1(); x6.M(); I7 x7 = new Test1(); x7.M(); } } "; ValidatePropertyModifiers_09(source1); } [Fact] public void IndexerModifiers_10() { var source1 = @" public interface I1 { abstract private int this[byte x] { get; } virtual private int this[int x] => 0; sealed private int this[short x] { get => 0; set {} } private int this[long x] {get;} = 0; } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,37): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // private int this[long x] {get;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(14, 37), // (4,26): error CS0621: 'I1.this[byte]': virtual or abstract members cannot be private // abstract private int this[byte x] { get; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "this").WithArguments("I1.this[byte]").WithLocation(4, 26), // (6,25): error CS0621: 'I1.this[int]': virtual or abstract members cannot be private // virtual private int this[int x] => 0; Diagnostic(ErrorCode.ERR_VirtualPrivate, "this").WithArguments("I1.this[int]").WithLocation(6, 25), // (8,24): error CS0238: 'I1.this[short]' cannot be sealed because it is not an override // sealed private int this[short x] Diagnostic(ErrorCode.ERR_SealedNonOverride, "this").WithArguments("I1.this[short]").WithLocation(8, 24), // (14,31): error CS0501: 'I1.this[long].get' must declare a body because it is not marked abstract, extern, or partial // private int this[long x] {get;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.this[long].get").WithLocation(14, 31), // (17,15): error CS0535: 'Test1' does not implement interface member 'I1.this[byte]' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.this[byte]") ); ValidatePropertyModifiers_10(compilation1); } [Fact] public void IndexerModifiers_11_01() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} sealed void Test() { this[0] = this[0]; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_01(source1, source2, Accessibility.Internal, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.this[int]' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.this[int]") ); } [Fact] public void IndexerModifiers_11_02() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_11_03() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } int I1.this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.Standard, // (9,12): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // int I1.this[int x] Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int]").WithLocation(9, 12) ); } [Fact] public void IndexerModifiers_11_04() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_11_05() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_11_06() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test3()); } public abstract int this[int x] {get; set;} } class Test3 : Test1 { public override int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_11_07() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallP1(new Test1()); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int this[int x] {get; set;} } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_11_08() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long this[int x] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_08(source1, source2); } [Fact] public void IndexerModifiers_11_09() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long this[int x] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_09(source1, source2, // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.this[int]'. 'Test1.this[int]' cannot implement 'I1.this[int]' because it does not have the matching return type of 'int'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.this[int]", "Test1.this[int]", "int").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_11_10() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} sealed void Test() { this[0] = this[0]; } } "; var source2 = @" public class Test2 : I1 { public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_10(source1, source2, // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].set'. 'Test2.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].set", "Test2.this[int].set", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].get'. 'Test2.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].get", "Test2.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_11_11() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} sealed void Test() { this[0] = this[0]; } } public class Test2 : I1 { public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_11(source1, source2, // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].get'. 'Test2.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].get", "Test2.this[int].get", "9.0", "10.0").WithLocation(11, 22), // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].set'. 'Test2.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].set", "Test2.this[int].set", "9.0", "10.0").WithLocation(11, 22) ); } [Fact] public void IndexerModifiers_12() { var source1 = @" public interface I1 { internal abstract int this[int x] {get; set;} } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.this[int]") ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMember<PropertySymbol>("this[]"); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Null(test1.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(p1.SetMethod)); } [Fact] public void IndexerModifiers_13() { var source1 = @" public interface I1 { public sealed int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } } } public interface I2 { public sealed int this[int x] { get { System.Console.WriteLine(""get_P2""); return 0; } set { System.Console.WriteLine(""set_P2""); } } } public interface I3 { public sealed int this[int x] { set { System.Console.WriteLine(""set_P3""); } } } public interface I4 { public sealed int this[int x] { get => GetP4(); } private int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } } public interface I5 { public sealed int this[int x] { get => GetP5(); set => System.Console.WriteLine(""set_P5""); } private int GetP5() { System.Console.WriteLine(""get_P5""); return 0; } } public interface I6 { public sealed int this[int x] { set => System.Console.WriteLine(""set_P6""); } } public interface I7 { public sealed int this[int x] => GetP7(); private int GetP7() { System.Console.WriteLine(""get_P7""); return 0; } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); var x = i1[0]; I2 i2 = new Test2(); i2[0] = i2[0]; I3 i3 = new Test3(); i3[0] = x; I4 i4 = new Test4(); x = i4[0]; I5 i5 = new Test5(); i5[0] = i5[0]; I6 i6 = new Test6(); i6[0] = x; I7 i7 = new Test7(); x = i7[0]; } public int this[int x] => throw null; } class Test2 : I2 { public int this[int x] { get => throw null; set => throw null; } } class Test3 : I3 { public int this[int x] { set => throw null; } } class Test4 : I4 { public int this[int x] { get => throw null; } } class Test5 : I5 { public int this[int x] { get => throw null; set => throw null; } } class Test6 : I6 { public int this[int x] { set => throw null; } } class Test7 : I7 { public int this[int x] => throw null; } "; ValidatePropertyModifiers_13(source1); } [Fact] public void AccessModifiers_14() { var source1 = @" public interface I1 { public sealed int this[int x] {get;} = 0; } public interface I2 { abstract sealed int this[int x] {get;} } public interface I3 { virtual sealed int this[int x] { set {} } } class Test1 : I1, I2, I3 { int I1.this[int x] { get => throw null; } int I2.this[int x] { get => throw null; } int I3.this[int x] { set => throw null; } } class Test2 : I1, I2, I3 {} "; ValidatePropertyModifiers_14(source1, // (4,42): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // public sealed int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(4, 42), // (4,36): error CS0501: 'I1.this[int].get' must declare a body because it is not marked abstract, extern, or partial // public sealed int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.this[int].get").WithLocation(4, 36), // (8,25): error CS0238: 'I2.this[int]' cannot be sealed because it is not an override // abstract sealed int this[int x] {get;} Diagnostic(ErrorCode.ERR_SealedNonOverride, "this").WithArguments("I2.this[int]").WithLocation(8, 25), // (12,24): error CS0238: 'I3.this[int]' cannot be sealed because it is not an override // virtual sealed int this[int x] Diagnostic(ErrorCode.ERR_SealedNonOverride, "this").WithArguments("I3.this[int]").WithLocation(12, 24), // (20,12): error CS0539: 'Test1.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.this[int x] { get => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Test1.this[int]").WithLocation(20, 12), // (21,12): error CS0539: 'Test1.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // int I2.this[int x] { get => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Test1.this[int]").WithLocation(21, 12), // (22,12): error CS0539: 'Test1.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // int I3.this[int x] { set => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Test1.this[int]").WithLocation(22, 12) ); } [Fact] [WorkItem(38398, "https://github.com/dotnet/roslyn/issues/38398")] public void InconsistentAccessibility_01() { var source1 = @" interface I1 { protected interface I2 { } } class C1 { protected interface I2 { } } interface I3 : I1 { protected I1.I2 M1(); protected interface I5 { I1.I2 M5(); } } class CI3 : I3 { I1.I2 I3.M1() => null; class CI5 : I3.I5 { I1.I2 I3.I5.M5() => null; } } class C3 : I1 { protected virtual void M1(I1.I2 x) { } protected interface I7 { I1.I2 M7(); } } class CC3 : C3 { protected override void M1(I1.I2 x) { } class CI7 : C3.I7 { I1.I2 C3.I7.M7() => null; } } class C33 : C1 { protected virtual void M1(C1.I2 x) { } protected class C55 { public virtual C1.I2 M55() => null; } } class CC33 : C33 { protected override void M1(C1.I2 x) { } class CC55 : C33.C55 { public override C1.I2 M55() => null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(38398, "https://github.com/dotnet/roslyn/issues/38398")] public void InconsistentAccessibility_02() { var source1 = @" interface I1 { protected interface I2 { } } class C1 { protected interface I2 { } } interface I3 : I1 { interface I4 { protected I1.I2 M4(); } } class CI4 : I3.I4 { I1.I2 I3.I4.M4() => null; } class C3 : I1 { public interface I6 { protected I1.I2 M6(); } } class CI6 : C3.I6 { I1.I2 C3.I6.M6() => null; } class C33 : C1 { public class C44 { protected virtual C1.I2 M44() => null; } } class CC44 : C33.C44 { protected override C1.I2 M44() => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (20,29): error CS0050: Inconsistent accessibility: return type 'I1.I2' is less accessible than method 'I3.I4.M4()' // protected I1.I2 M4(); Diagnostic(ErrorCode.ERR_BadVisReturnType, "M4").WithArguments("I3.I4.M4()", "I1.I2").WithLocation(20, 29), // (24,17): error CS0535: 'CI4' does not implement interface member 'I3.I4.M4()' // class CI4 : I3.I4 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3.I4").WithArguments("CI4", "I3.I4.M4()").WithLocation(24, 17), // (26,12): error CS0122: 'I1.I2' is inaccessible due to its protection level // I1.I2 I3.I4.M4() => null; Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1.I2").WithLocation(26, 12), // (26,21): error CS0539: 'CI4.M4()' in explicit interface declaration is not found among members of the interface that can be implemented // I1.I2 I3.I4.M4() => null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M4").WithArguments("CI4.M4()").WithLocation(26, 21), // (33,29): error CS0050: Inconsistent accessibility: return type 'I1.I2' is less accessible than method 'C3.I6.M6()' // protected I1.I2 M6(); Diagnostic(ErrorCode.ERR_BadVisReturnType, "M6").WithArguments("C3.I6.M6()", "I1.I2").WithLocation(33, 29), // (37,17): error CS0535: 'CI6' does not implement interface member 'C3.I6.M6()' // class CI6 : C3.I6 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "C3.I6").WithArguments("CI6", "C3.I6.M6()").WithLocation(37, 17), // (39,12): error CS0122: 'I1.I2' is inaccessible due to its protection level // I1.I2 C3.I6.M6() => null; Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1.I2").WithLocation(39, 12), // (39,21): error CS0539: 'CI6.M6()' in explicit interface declaration is not found among members of the interface that can be implemented // I1.I2 C3.I6.M6() => null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M6").WithArguments("CI6.M6()").WithLocation(39, 21), // (46,37): error CS0050: Inconsistent accessibility: return type 'C1.I2' is less accessible than method 'C33.C44.M44()' // protected virtual C1.I2 M44() => null; Diagnostic(ErrorCode.ERR_BadVisReturnType, "M44").WithArguments("C33.C44.M44()", "C1.I2").WithLocation(46, 37), // (52,31): error CS0122: 'C1.I2' is inaccessible due to its protection level // protected override C1.I2 M44() => null; Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("C1.I2").WithLocation(52, 31) ); } [Fact] [WorkItem(38398, "https://github.com/dotnet/roslyn/issues/38398")] public void InconsistentAccessibility_03() { var source1 = @" interface I1<T> { protected interface I2 { } } class C1<T> { protected interface I2 { } } interface I3 : I1<int> { protected I1<string>.I2 M1(); protected interface I5 { I1<string>.I2 M5(); } } class CI3 : I3 { I1<string>.I2 I3.M1() => null; class CI5 : I3.I5 { I1<string>.I2 I3.I5.M5() => null; } } class C3 : I1<int> { protected virtual void M1(I1<string>.I2 x) { } protected interface I7 { I1<string>.I2 M7(); } } class CC3 : C3 { protected override void M1(I1<string>.I2 x) { } class CI7 : C3.I7 { I1<string>.I2 C3.I7.M7() => null; } } class C33 : C1<int> { protected virtual void M1(C1<string>.I2 x) { } protected class C55 { public virtual C1<string>.I2 M55() => null; } } class CC33 : C33 { protected override void M1(C1<string>.I2 x) { } class CC55 : C33.C55 { public override C1<string>.I2 M55() => null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(38398, "https://github.com/dotnet/roslyn/issues/38398")] public void InconsistentAccessibility_04() { var source1 = @" interface I1<T> { protected interface I2 { } } class C1<T> { protected interface I2 { } } interface I3 : I1<int> { interface I4 { protected I1<string>.I2 M4(); } } class CI4 : I3.I4 { I1<string>.I2 I3.I4.M4() => null; } class C3 : I1<int> { public interface I6 { protected I1<string>.I2 M6(); } } class CI6 : C3.I6 { I1<string>.I2 C3.I6.M6() => null; } class C33 : C1<int> { public class C44 { protected virtual C1<string>.I2 M44() => null; } } class CC44 : C33.C44 { protected override C1<string>.I2 M44() => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (20,37): error CS0050: Inconsistent accessibility: return type 'I1<string>.I2' is less accessible than method 'I3.I4.M4()' // protected I1<string>.I2 M4(); Diagnostic(ErrorCode.ERR_BadVisReturnType, "M4").WithArguments("I3.I4.M4()", "I1<string>.I2").WithLocation(20, 37), // (24,17): error CS0535: 'CI4' does not implement interface member 'I3.I4.M4()' // class CI4 : I3.I4 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3.I4").WithArguments("CI4", "I3.I4.M4()").WithLocation(24, 17), // (26,20): error CS0122: 'I1<string>.I2' is inaccessible due to its protection level // I1<string>.I2 I3.I4.M4() => null; Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1<string>.I2").WithLocation(26, 20), // (26,29): error CS0539: 'CI4.M4()' in explicit interface declaration is not found among members of the interface that can be implemented // I1<string>.I2 I3.I4.M4() => null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M4").WithArguments("CI4.M4()").WithLocation(26, 29), // (33,37): error CS0050: Inconsistent accessibility: return type 'I1<string>.I2' is less accessible than method 'C3.I6.M6()' // protected I1<string>.I2 M6(); Diagnostic(ErrorCode.ERR_BadVisReturnType, "M6").WithArguments("C3.I6.M6()", "I1<string>.I2").WithLocation(33, 37), // (37,17): error CS0535: 'CI6' does not implement interface member 'C3.I6.M6()' // class CI6 : C3.I6 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "C3.I6").WithArguments("CI6", "C3.I6.M6()").WithLocation(37, 17), // (39,20): error CS0122: 'I1<string>.I2' is inaccessible due to its protection level // I1<string>.I2 C3.I6.M6() => null; Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1<string>.I2").WithLocation(39, 20), // (39,29): error CS0539: 'CI6.M6()' in explicit interface declaration is not found among members of the interface that can be implemented // I1<string>.I2 C3.I6.M6() => null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M6").WithArguments("CI6.M6()").WithLocation(39, 29), // (46,45): error CS0050: Inconsistent accessibility: return type 'C1<string>.I2' is less accessible than method 'C33.C44.M44()' // protected virtual C1<string>.I2 M44() => null; Diagnostic(ErrorCode.ERR_BadVisReturnType, "M44").WithArguments("C33.C44.M44()", "C1<string>.I2").WithLocation(46, 45), // (52,39): error CS0122: 'C1<string>.I2' is inaccessible due to its protection level // protected override C1<string>.I2 M44() => null; Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("C1<string>.I2").WithLocation(52, 39) ); } [Fact] public void IndexerModifiers_15() { var source1 = @" public interface I0 { abstract virtual int this[int x] { get; set; } } public interface I1 { abstract virtual int this[int x] { get { throw null; } } } public interface I2 { virtual abstract int this[int x] { get { throw null; } set { throw null; } } } public interface I3 { abstract virtual int this[int x] { set { throw null; } } } public interface I4 { abstract virtual int this[int x] { get => throw null; } } public interface I5 { abstract virtual int this[int x] { get => throw null; set => throw null; } } public interface I6 { abstract virtual int this[int x] { set => throw null; } } public interface I7 { abstract virtual int this[int x] => throw null; } public interface I8 { abstract virtual int this[int x] {get;} = 0; } class Test1 : I0, I1, I2, I3, I4, I5, I6, I7, I8 { int I0.this[int x] { get { throw null; } set { throw null; } } int I1.this[int x] { get { throw null; } } int I2.this[int x] { get { throw null; } set { throw null; } } int I3.this[int x] { set { throw null; } } int I4.this[int x] { get { throw null; } } int I5.this[int x] { get { throw null; } set { throw null; } } int I6.this[int x] { set { throw null; } } int I7.this[int x] { get { throw null; } } int I8.this[int x] { get { throw null; } } } class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 {} "; ValidatePropertyModifiers_15(source1, // (44,45): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // abstract virtual int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(44, 45), // (4,26): error CS0503: The abstract property 'I0.this[int]' cannot be marked virtual // abstract virtual int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I0.this[int]").WithLocation(4, 26), // (8,26): error CS0503: The abstract property 'I1.this[int]' cannot be marked virtual // abstract virtual int this[int x] { get { throw null; } } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I1.this[int]").WithLocation(8, 26), // (8,40): error CS0500: 'I1.this[int].get' cannot declare a body because it is marked abstract // abstract virtual int this[int x] { get { throw null; } } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.this[int].get").WithLocation(8, 40), // (12,26): error CS0503: The abstract property 'I2.this[int]' cannot be marked virtual // virtual abstract int this[int x] Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I2.this[int]").WithLocation(12, 26), // (14,9): error CS0500: 'I2.this[int].get' cannot declare a body because it is marked abstract // get { throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.this[int].get").WithLocation(14, 9), // (15,9): error CS0500: 'I2.this[int].set' cannot declare a body because it is marked abstract // set { throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.this[int].set").WithLocation(15, 9), // (20,26): error CS0503: The abstract property 'I3.this[int]' cannot be marked virtual // abstract virtual int this[int x] { set { throw null; } } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I3.this[int]").WithLocation(20, 26), // (20,40): error CS0500: 'I3.this[int].set' cannot declare a body because it is marked abstract // abstract virtual int this[int x] { set { throw null; } } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I3.this[int].set").WithLocation(20, 40), // (24,26): error CS0503: The abstract property 'I4.this[int]' cannot be marked virtual // abstract virtual int this[int x] { get => throw null; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I4.this[int]").WithLocation(24, 26), // (24,40): error CS0500: 'I4.this[int].get' cannot declare a body because it is marked abstract // abstract virtual int this[int x] { get => throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I4.this[int].get").WithLocation(24, 40), // (28,26): error CS0503: The abstract property 'I5.this[int]' cannot be marked virtual // abstract virtual int this[int x] Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I5.this[int]").WithLocation(28, 26), // (30,9): error CS0500: 'I5.this[int].get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I5.this[int].get").WithLocation(30, 9), // (31,9): error CS0500: 'I5.this[int].set' cannot declare a body because it is marked abstract // set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I5.this[int].set").WithLocation(31, 9), // (36,26): error CS0503: The abstract property 'I6.this[int]' cannot be marked virtual // abstract virtual int this[int x] { set => throw null; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I6.this[int]").WithLocation(36, 26), // (36,40): error CS0500: 'I6.this[int].set' cannot declare a body because it is marked abstract // abstract virtual int this[int x] { set => throw null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I6.this[int].set").WithLocation(36, 40), // (40,26): error CS0503: The abstract property 'I7.this[int]' cannot be marked virtual // abstract virtual int this[int x] => throw null; Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I7.this[int]").WithLocation(40, 26), // (40,41): error CS0500: 'I7.this[int].get' cannot declare a body because it is marked abstract // abstract virtual int this[int x] => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "throw null").WithArguments("I7.this[int].get").WithLocation(40, 41), // (44,26): error CS0503: The abstract property 'I8.this[int]' cannot be marked virtual // abstract virtual int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "this").WithArguments("property", "I8.this[int]").WithLocation(44, 26), // (90,15): error CS0535: 'Test2' does not implement interface member 'I0.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I0").WithArguments("Test2", "I0.this[int]").WithLocation(90, 15), // (90,19): error CS0535: 'Test2' does not implement interface member 'I1.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.this[int]").WithLocation(90, 19), // (90,23): error CS0535: 'Test2' does not implement interface member 'I2.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I2.this[int]").WithLocation(90, 23), // (90,27): error CS0535: 'Test2' does not implement interface member 'I3.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test2", "I3.this[int]").WithLocation(90, 27), // (90,31): error CS0535: 'Test2' does not implement interface member 'I4.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test2", "I4.this[int]").WithLocation(90, 31), // (90,35): error CS0535: 'Test2' does not implement interface member 'I5.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I5").WithArguments("Test2", "I5.this[int]").WithLocation(90, 35), // (90,39): error CS0535: 'Test2' does not implement interface member 'I6.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I6").WithArguments("Test2", "I6.this[int]").WithLocation(90, 39), // (90,43): error CS0535: 'Test2' does not implement interface member 'I7.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I7").WithArguments("Test2", "I7.this[int]").WithLocation(90, 43), // (90,47): error CS0535: 'Test2' does not implement interface member 'I8.this[int]' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I8").WithArguments("Test2", "I8.this[int]").WithLocation(90, 47) ); } [Fact] public void IndexerModifiers_16() { var source1 = @" public interface I1 { extern int this[int x] {get;} } public interface I2 { virtual extern int this[int x] {set;} } public interface I4 { private extern int this[int x] {get;} } public interface I5 { extern sealed int this[int x] {set;} } class Test1 : I1, I2, I4, I5 { } class Test2 : I1, I2, I4, I5 { int I1.this[int x] => 0; int I2.this[int x] { set {} } } "; ValidatePropertyModifiers_16(source1, new DiagnosticDescription[] { // (4,16): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern int this[int x] {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("extern", "7.3", "8.0").WithLocation(4, 16), // (8,24): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern int this[int x] {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("extern", "7.3", "8.0").WithLocation(8, 24), // (8,24): error CS8503: The modifier 'virtual' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern int this[int x] {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("virtual", "7.3", "8.0").WithLocation(8, 24), // (12,24): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern int this[int x] {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("private", "7.3", "8.0").WithLocation(12, 24), // (12,24): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern int this[int x] {get;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("extern", "7.3", "8.0").WithLocation(12, 24), // (16,23): error CS8503: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed int this[int x] {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("sealed", "7.3", "8.0").WithLocation(16, 23), // (16,23): error CS8503: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed int this[int x] {set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "this").WithArguments("extern", "7.3", "8.0").WithLocation(16, 23), // (8,37): warning CS0626: Method, operator, or accessor 'I2.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern int this[int x] {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I2.this[int].set").WithLocation(8, 37), // (12,37): warning CS0626: Method, operator, or accessor 'I4.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern int this[int x] {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I4.this[int].get").WithLocation(12, 37), // (16,36): warning CS0626: Method, operator, or accessor 'I5.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed int this[int x] {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I5.this[int].set").WithLocation(16, 36), // (4,29): warning CS0626: Method, operator, or accessor 'I1.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int this[int x] {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.this[int].get").WithLocation(4, 29) }, // (4,29): error CS8501: Target runtime doesn't support default interface implementation. // extern int this[int x] {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(4, 29), // (8,37): error CS8501: Target runtime doesn't support default interface implementation. // virtual extern int this[int x] {set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(8, 37), // (12,37): error CS8501: Target runtime doesn't support default interface implementation. // private extern int this[int x] {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(12, 37), // (16,36): error CS8501: Target runtime doesn't support default interface implementation. // extern sealed int this[int x] {set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(16, 36), // (8,37): warning CS0626: Method, operator, or accessor 'I2.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern int this[int x] {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I2.this[int].set").WithLocation(8, 37), // (12,37): warning CS0626: Method, operator, or accessor 'I4.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern int this[int x] {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I4.this[int].get").WithLocation(12, 37), // (16,36): warning CS0626: Method, operator, or accessor 'I5.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed int this[int x] {set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I5.this[int].set").WithLocation(16, 36), // (4,29): warning CS0626: Method, operator, or accessor 'I1.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int this[int x] {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.this[int].get").WithLocation(4, 29) ); } [Fact] public void IndexerModifiers_17() { var source1 = @" public interface I1 { abstract extern int this[int x] {get;} } public interface I2 { extern int this[int x] => 0; } public interface I3 { static extern int this[int x] {get => 0; set => throw null;} } public interface I4 { private extern int this[int x] { get {throw null;} set {throw null;}} } public interface I5 { extern sealed int this[int x] {get;} = 0; } class Test1 : I1, I2, I3, I4, I5 { } class Test2 : I1, I2, I3, I4, I5 { int I1.this[int x] => 0; int I2.this[int x] => 0; int I3.this[int x] { get => 0; set => throw null;} int I4.this[int x] { get => 0; set => throw null;} int I5.this[int x] => 0; } "; ValidatePropertyModifiers_17(source1, // (20,42): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // extern sealed int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(20, 42), // (4,25): error CS0180: 'I1.this[int]' cannot be both extern and abstract // abstract extern int this[int x] {get;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "this").WithArguments("I1.this[int]").WithLocation(4, 25), // (8,31): error CS0179: 'I2.this[int].get' cannot be extern and declare a body // extern int this[int x] => 0; Diagnostic(ErrorCode.ERR_ExternHasBody, "0").WithArguments("I2.this[int].get").WithLocation(8, 31), // (12,23): error CS0106: The modifier 'static' is not valid for this item // static extern int this[int x] {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(12, 23), // (12,36): error CS0179: 'I3.this[int].get' cannot be extern and declare a body // static extern int this[int x] {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("I3.this[int].get").WithLocation(12, 36), // (12,46): error CS0179: 'I3.this[int].set' cannot be extern and declare a body // static extern int this[int x] {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("I3.this[int].set").WithLocation(12, 46), // (16,38): error CS0179: 'I4.this[int].get' cannot be extern and declare a body // private extern int this[int x] { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("I4.this[int].get").WithLocation(16, 38), // (16,56): error CS0179: 'I4.this[int].set' cannot be extern and declare a body // private extern int this[int x] { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("I4.this[int].set").WithLocation(16, 56), // (23,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.this[int]"), // (32,12): error CS0539: 'Test2.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // int I4.this[int x] { get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Test2.this[int]").WithLocation(32, 12), // (33,12): error CS0539: 'Test2.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // int I5.this[int x] => 0; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Test2.this[int]").WithLocation(33, 12), // (20,36): warning CS0626: Method, operator, or accessor 'I5.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed int this[int x] {get;} = 0; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I5.this[int].get").WithLocation(20, 36) ); } [Fact] public void IndexerModifiers_18() { var source1 = @" public interface I1 { abstract int this[int x] {get => 0; set => throw null;} } public interface I2 { abstract private int this[int x] => 0; } public interface I3 { static extern int this[int x] {get; set;} } public interface I4 { abstract static int this[int x] { get {throw null;} set {throw null;}} } public interface I5 { override sealed int this[int x] {get;} = 0; } class Test1 : I1, I2, I3, I4, I5 { } class Test2 : I1, I2, I3, I4, I5 { int I1.this[int x] { get => 0; set => throw null;} int I2.this[int x] => 0; int I3.this[int x] { get => 0; set => throw null;} int I4.this[int x] { get => 0; set => throw null;} int I5.this[int x] => 0; } "; ValidatePropertyModifiers_18(source1, // (20,44): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // override sealed int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(20, 44), // (4,31): error CS0500: 'I1.this[int].get' cannot declare a body because it is marked abstract // abstract int this[int x] {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.this[int].get").WithLocation(4, 31), // (4,41): error CS0500: 'I1.this[int].set' cannot declare a body because it is marked abstract // abstract int this[int x] {get => 0; set => throw null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I1.this[int].set").WithLocation(4, 41), // (8,26): error CS0621: 'I2.this[int]': virtual or abstract members cannot be private // abstract private int this[int x] => 0; Diagnostic(ErrorCode.ERR_VirtualPrivate, "this").WithArguments("I2.this[int]").WithLocation(8, 26), // (8,41): error CS0500: 'I2.this[int].get' cannot declare a body because it is marked abstract // abstract private int this[int x] => 0; Diagnostic(ErrorCode.ERR_AbstractHasBody, "0").WithArguments("I2.this[int].get").WithLocation(8, 41), // (12,23): error CS0106: The modifier 'static' is not valid for this item // static extern int this[int x] {get; set;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(12, 23), // (16,25): error CS0106: The modifier 'static' is not valid for this item // abstract static int this[int x] { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(16, 25), // (16,39): error CS0500: 'I4.this[int].get' cannot declare a body because it is marked abstract // abstract static int this[int x] { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I4.this[int].get").WithLocation(16, 39), // (16,57): error CS0500: 'I4.this[int].set' cannot declare a body because it is marked abstract // abstract static int this[int x] { get {throw null;} set {throw null;}} Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I4.this[int].set").WithLocation(16, 57), // (20,25): error CS0106: The modifier 'override' is not valid for this item // override sealed int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("override").WithLocation(20, 25), // (20,38): error CS0501: 'I5.this[int].get' must declare a body because it is not marked abstract, extern, or partial // override sealed int this[int x] {get;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I5.this[int].get").WithLocation(20, 38), // (23,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.this[int]"), // (23,19): error CS0535: 'Test1' does not implement interface member 'I2.this[int]' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I2.this[int]"), // (23,27): error CS0535: 'Test1' does not implement interface member 'I4.this[int]' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test1", "I4.this[int]").WithLocation(23, 27), // (30,12): error CS0122: 'I2.this[int]' is inaccessible due to its protection level // int I2.this[int x] => 0; Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I2.this[int]").WithLocation(30, 12), // (33,12): error CS0539: 'Test2.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // int I5.this[int x] => 0; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Test2.this[int]").WithLocation(33, 12), // (12,36): warning CS0626: Method, operator, or accessor 'I3.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int this[int x] {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I3.this[int].get").WithLocation(12, 36), // (12,41): warning CS0626: Method, operator, or accessor 'I3.this[int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern int this[int x] {get; set;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("I3.this[int].set").WithLocation(12, 41) ); } [Fact] public void IndexerModifiers_20() { var source1 = @" public interface I1 { internal int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } void M2() {this[0] = this[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidatePropertyModifiers_20(source1, source2, Accessibility.Internal); } [Fact] public void IndexerModifiers_21() { var source1 = @" public interface I1 { private int this[int x] { get => throw null; set => throw null; } } public interface I2 { internal int this[int x] { get => throw null; set => throw null; } } public interface I3 { public int this[int x] { get => throw null; set => throw null; } } public interface I4 { int this[int x] { get => throw null; set => throw null; } } class Test1 { static void Test(I1 i1, I2 i2, I3 i3, I4 i4) { int x; x = i1[0]; i1[0] = x; x = i2[0]; i2[0] = x; x = i3[0]; i3[0] = x; x = i4[0]; i4[0] = x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (24,13): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // x = i1[0]; Diagnostic(ErrorCode.ERR_BadAccess, "i1[0]").WithArguments("I1.this[int]").WithLocation(24, 13), // (25,9): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // i1[0] = x; Diagnostic(ErrorCode.ERR_BadAccess, "i1[0]").WithArguments("I1.this[int]").WithLocation(25, 9) ); var source2 = @" class Test2 { static void Test(I1 i1, I2 i2, I3 i3, I4 i4) { int x; x = i1[0]; i1[0] = x; x = i2[0]; i2[0] = x; x = i3[0]; i3[0] = x; x = i4[0]; i4[0] = x; } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (7,13): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // x = i1[0]; Diagnostic(ErrorCode.ERR_BadAccess, "i1[0]").WithArguments("I1.this[int]").WithLocation(7, 13), // (8,9): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // i1[0] = x; Diagnostic(ErrorCode.ERR_BadAccess, "i1[0]").WithArguments("I1.this[int]").WithLocation(8, 9), // (9,13): error CS0122: 'I2.this[int]' is inaccessible due to its protection level // x = i2[0]; Diagnostic(ErrorCode.ERR_BadAccess, "i2[0]").WithArguments("I2.this[int]").WithLocation(9, 13), // (10,9): error CS0122: 'I2.this[int]' is inaccessible due to its protection level // i2[0] = x; Diagnostic(ErrorCode.ERR_BadAccess, "i2[0]").WithArguments("I2.this[int]").WithLocation(10, 9) ); } [Fact] public void IndexerModifiers_22() { var source1 = @" public interface I1 { public int this[int x] { internal get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int this[int x] { get { System.Console.WriteLine(""get_P2""); return 0; } internal set { System.Console.WriteLine(""set_P2""); } } } public interface I3 { int this[int x] { internal get => Test1.GetP3(); set => System.Console.WriteLine(""set_P3""); } } public interface I4 { int this[int x] { get => Test1.GetP4(); internal set => System.Console.WriteLine(""set_P4""); } } class Test1 : I1, I2, I3, I4 { static void Main() { I1 i1 = new Test1(); I2 i2 = new Test1(); I3 i3 = new Test1(); I4 i4 = new Test1(); i1[0] = i1[0]; i2[0] = i2[0]; i3[0] = i3[0]; i4[0] = i4[0]; } public static int GetP3() { System.Console.WriteLine(""get_P3""); return 0; } public static int GetP4() { System.Console.WriteLine(""get_P4""); return 0; } } "; ValidatePropertyModifiers_22(source1, Accessibility.Internal); } [Fact] public void IndexerModifiers_23_00() { var source1 = @" public interface I1 { } public interface I3 { int this[int x] { private get { System.Console.WriteLine(""get_P3""); return 0; } set {System.Console.WriteLine(""set_P3"");} } void M2() { this[0] = this[1]; } } public interface I4 { int this[int x] { get {System.Console.WriteLine(""get_P4""); return 0;} private set {System.Console.WriteLine(""set_P4"");} } void M2() { this[0] = this[1]; } } public interface I5 { int this[int x] { private get => GetP5(); set => System.Console.WriteLine(""set_P5""); } private int GetP5() { System.Console.WriteLine(""get_P5""); return 0; } void M2() { this[0] = this[1]; } } public interface I6 { int this[int x] { get => GetP6(); private set => System.Console.WriteLine(""set_P6""); } private int GetP6() { System.Console.WriteLine(""get_P6""); return 0; } void M2() { this[0] = this[1]; } } "; var source2 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public int this[int x] { get { throw null; } set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public int this[int x] { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } set { throw null; } } } class Test5 : I5 { public int this[int x] { get { throw null; } set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public int this[int x] { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } set { throw null; } } } "; ValidatePropertyModifiers_23(source1, source2); var source3 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public int this[int x] { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public int this[int x] { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test5 : I5 { public int this[int x] { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public int this[int x] { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } "; ValidatePropertyModifiers_23(source1, source3); var source4 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public virtual int this[int x] { get { throw null; } set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public virtual int this[int x] { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } set { throw null; } } } class Test5 : I5 { public virtual int this[int x] { get { throw null; } set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public virtual int this[int x] { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } set { throw null; } } } "; ValidatePropertyModifiers_23(source1, source4); var source5 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { public virtual int this[int x] { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { public virtual int this[int x] { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test5 : I5 { public virtual int this[int x] { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { public virtual int this[int x] { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } "; ValidatePropertyModifiers_23(source1, source5); var source6 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test3(); I4 i4 = new Test4(); I5 i5 = new Test5(); I6 i6 = new Test6(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } class Test3 : I3 { int I3.this[int x] { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test4 : I4 { int I4.this[int x] { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test5 : I5 { int I5.this[int x] { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test6 : I6 { int I6.this[int x] { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } "; ValidatePropertyModifiers_23(source1, source6); var source7 = @" class Test1 : I1 { static void Main() { I3 i3 = new Test33(); I4 i4 = new Test44(); I5 i5 = new Test55(); I6 i6 = new Test66(); i3.M2(); i4.M2(); i5.M2(); i6.M2(); } } interface Test3 : I3 { int I3.this[int x] { set { System.Console.WriteLine(""Test3.set_P3""); } } } class Test33 : Test3 {} interface Test4 : I4 { int I4.this[int x] { get { System.Console.WriteLine(""Test4.get_P4""); return 0; } } } class Test44 : Test4 {} interface Test5 : I5 { int I5.this[int x] { set { System.Console.WriteLine(""Test5.set_P5""); } } } class Test55 : Test5 {} interface Test6 : I6 { int I6.this[int x] { get { System.Console.WriteLine(""Test6.get_P6""); return 0; } } } class Test66 : Test6 {} "; ValidatePropertyModifiers_23(source1, source7); } [Fact] public void IndexerModifiers_23_01() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} void M2() { this[0] = this[1]; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_23(source1, source2, Accessibility.Internal, Accessibility.Public, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_23_02() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_23_03() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } int I1.this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.Standard, // (9,12): error CS0122: 'I1.this[int].get' is inaccessible due to its protection level // int I1.this[int x] Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int].get").WithLocation(9, 12) ); } [Fact] public void IndexerModifiers_23_04() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_05() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_06() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test3()); } public abstract int this[int x] {get; set;} } class Test3 : Test1 { public override int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_07() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallP1(new Test1()); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int this[int x] {get; set;} } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].get'. 'Test1.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].get", "Test1.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_08() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long this[int x] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_08(source1, source2); } [Fact] public void IndexerModifiers_23_09() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long this[int x] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_09(source1, source2, // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.this[int]'. 'Test1.this[int]' cannot implement 'I1.this[int]' because it does not have the matching return type of 'int'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.this[int]", "Test1.this[int]", "int").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_23_10() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} sealed void Test() { this[0] = this[0]; } } "; var source2 = @" public class Test2 : I1 { public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_10(source1, source2, // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].get'. 'Test2.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].get", "Test2.this[int].get", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_11() { var source1 = @" public interface I1 { abstract int this[int x] {internal get; set;} sealed void Test() { this[0] = this[0]; } } public class Test2 : I1 { public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_11(source1, source2, // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].get'. 'Test2.this[int].get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].get", "Test2.this[int].get", "9.0", "10.0").WithLocation(11, 22) ); } [Fact] public void IndexerModifiers_23_51() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} void M2() { this[0] = this[0]; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_23(source1, source2, Accessibility.Public, Accessibility.Internal, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_23_52() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_23_53() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } int I1.this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_03(source1, source2, TargetFramework.Standard, // (9,12): error CS0122: 'I1.this[int].set' is inaccessible due to its protection level // int I1.this[int x] Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int].set").WithLocation(9, 12) ); } [Fact] public void IndexerModifiers_23_54() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_55() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_56() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test3()); } public abstract int this[int x] {get; set;} } class Test3 : Test1 { public override int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_57() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallP1(new Test1()); } public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } public interface I2 { int this[int x] {get; set;} } "; ValidatePropertyModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.this[int].set'. 'Test1.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.this[int].set", "Test1.this[int].set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_58() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } public class Test2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""Test2.get_P1""); return 0; } set { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long this[int x] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_08(source1, source2); } [Fact] public void IndexerModifiers_23_59() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} } public class TestHelper { public static void CallP1(I1 x) {x[0] = x[0];} } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual long this[int x] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyModifiers_11_09(source1, source2, // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.this[int]'. 'Test1.this[int]' cannot implement 'I1.this[int]' because it does not have the matching return type of 'int'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.this[int]", "Test1.this[int]", "int").WithLocation(2, 15) ); } [Fact] public void IndexerModifiers_23_60() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} sealed void Test() { this[0] = this[0]; } } "; var source2 = @" public class Test2 : I1 { public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_10(source1, source2, // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].set'. 'Test2.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].set", "Test2.this[int].set", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void IndexerModifiers_23_61() { var source1 = @" public interface I1 { abstract int this[int x] {get; internal set;} sealed void Test() { this[0] = this[0]; } } public class Test2 : I1 { public int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } set { System.Console.WriteLine(""set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidatePropertyModifiers_11_11(source1, source2, // (11,22): error CS8704: 'Test2' does not implement interface member 'I1.this[int].set'. 'Test2.this[int].set' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.this[int].set", "Test2.this[int].set", "9.0", "10.0").WithLocation(11, 22) ); } [Fact] public void IndexerModifiers_24() { var source1 = @" public interface I1 { int this[int x] { get { System.Console.WriteLine(""get_P1""); return 0; } internal set { System.Console.WriteLine(""set_P1""); } } void M2() {this[0] = this[1];} } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidatePropertyModifiers_24(source1, source2); } [Fact] public void IndexerModifiers_25() { var source1 = @" public interface I1 { int this[int x] { private get => throw null; set => throw null; } } public interface I2 { int this[int x] { internal get => throw null; set => throw null; } } public interface I3 { public int this[int x] { get => throw null; private set => throw null; } } public interface I4 { int this[int x] { get => throw null; internal set => throw null; } } public class Test1 : I1, I2, I3, I4 { static void Main() { int x; I1 i1 = new Test1(); I2 i2 = new Test1(); I3 i3 = new Test1(); I4 i4 = new Test1(); x = i1[0]; i1[0] = x; x = i2[0]; i2[0] = x; x = i3[0]; i3[0] = x; x = i4[0]; i4[0] = x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (29,13): error CS0271: The property or indexer 'I1.this[int]' cannot be used in this context because the get accessor is inaccessible // x = i1[0]; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "i1[0]").WithArguments("I1.this[int]").WithLocation(29, 13), // (34,9): error CS0272: The property or indexer 'I3.this[int]' cannot be used in this context because the set accessor is inaccessible // i3[0] = x; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "i3[0]").WithArguments("I3.this[int]").WithLocation(34, 9) ); var source2 = @" class Test2 { static void Main() { int x; I1 i1 = new Test1(); I2 i2 = new Test1(); I3 i3 = new Test1(); I4 i4 = new Test1(); x = i1[0]; i1[0] = x; x = i2[0]; i2[0] = x; x = i3[0]; i3[0] = x; x = i4[0]; i4[0] = x; } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (12,13): error CS0271: The property or indexer 'I1.this[int]' cannot be used in this context because the get accessor is inaccessible // x = i1[0]; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "i1[0]").WithArguments("I1.this[int]").WithLocation(12, 13), // (14,13): error CS0271: The property or indexer 'I2.this[int]' cannot be used in this context because the get accessor is inaccessible // x = i2[0]; Diagnostic(ErrorCode.ERR_InaccessibleGetter, "i2[0]").WithArguments("I2.this[int]").WithLocation(14, 13), // (17,9): error CS0272: The property or indexer 'I3.this[int]' cannot be used in this context because the set accessor is inaccessible // i3[0] = x; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "i3[0]").WithArguments("I3.this[int]").WithLocation(17, 9), // (19,9): error CS0272: The property or indexer 'I4.this[int]' cannot be used in this context because the set accessor is inaccessible // i4[0] = x; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "i4[0]").WithArguments("I4.this[int]").WithLocation(19, 9) ); } [Fact] public void IndexerModifiers_26() { var source1 = @" public interface I1 { abstract int this[sbyte x] { private get; set; } abstract int this[byte x] { get; private set; } abstract int this[short x] { internal get; } int this[ushort x] {internal get;} = 0; int this[int x] { internal get {throw null;} } int this[uint x] { internal set {throw null;} } int this[long x] { internal get => throw null; } int this[ulong x] { internal set => throw null; } int this[float x] { internal get {throw null;} private set {throw null;}} int this[double x] { internal get => throw null; private set => throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (7,40): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // int this[ushort x] {internal get;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(7, 40), // (4,42): error CS0442: 'I1.this[sbyte].get': abstract properties cannot have private accessors // abstract int this[sbyte x] { private get; set; } Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I1.this[sbyte].get").WithLocation(4, 42), // (5,46): error CS0442: 'I1.this[byte].set': abstract properties cannot have private accessors // abstract int this[byte x] { get; private set; } Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "set").WithArguments("I1.this[byte].set").WithLocation(5, 46), // (6,18): error CS0276: 'I1.this[short]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // abstract int this[short x] { internal get; } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I1.this[short]").WithLocation(6, 18), // (7,9): error CS0276: 'I1.this[ushort]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int this[ushort x] {internal get;} = 0; Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I1.this[ushort]").WithLocation(7, 9), // (8,9): error CS0276: 'I1.this[int]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int this[int x] { internal get {throw null;} } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I1.this[int]").WithLocation(8, 9), // (9,9): error CS0276: 'I1.this[uint]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int this[uint x] { internal set {throw null;} } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I1.this[uint]").WithLocation(9, 9), // (10,9): error CS0276: 'I1.this[long]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int this[long x] { internal get => throw null; } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I1.this[long]").WithLocation(10, 9), // (11,9): error CS0276: 'I1.this[ulong]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // int this[ulong x] { internal set => throw null; } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("I1.this[ulong]").WithLocation(11, 9), // (12,9): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'I1.this[float]' // int this[float x] { internal get {throw null;} private set {throw null;}} Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "this").WithArguments("I1.this[float]").WithLocation(12, 9), // (13,9): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'I1.this[double]' // int this[double x] { internal get => throw null; private set => throw null;} Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "this").WithArguments("I1.this[double]").WithLocation(13, 9) ); } [Fact] public void IndexerModifiers_27() { var source1 = @" public interface I1 { int this[short x] { private get {throw null;} set {} } int this[int x] { get {throw null;} private set {} } } class Test1 : I1 { int I1.this[short x] { get {throw null;} set {} } int I1.this[int x] { get {throw null;} set {} } } interface ITest1 : I1 { int I1.this[short x] { get {throw null;} set {} } int I1.this[int x] { get {throw null;} set {} } } public interface I2 { int this[short x] { private get {throw null;} set {} } int this[int x] { get {throw null;} private set {} } class Test3 : I2 { int I2.this[short x] { get {throw null;} set {} } int I2.this[int x] { get {throw null;} set {} } } interface ITest3 : I2 { int I2.this[short x] { get {throw null;} set {} } int I2.this[int x] { get {throw null;} set {} } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (21,9): error CS0550: 'Test1.I1.this[short].get' adds an accessor not found in interface member 'I1.this[short]' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("Test1.I1.this[short].get", "I1.this[short]").WithLocation(21, 9), // (28,9): error CS0550: 'Test1.I1.this[int].set' adds an accessor not found in interface member 'I1.this[int]' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("Test1.I1.this[int].set", "I1.this[int]").WithLocation(28, 9), // (36,9): error CS0550: 'ITest1.I1.this[short].get' adds an accessor not found in interface member 'I1.this[short]' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("ITest1.I1.this[short].get", "I1.this[short]").WithLocation(36, 9), // (43,9): error CS0550: 'ITest1.I1.this[int].set' adds an accessor not found in interface member 'I1.this[int]' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("ITest1.I1.this[int].set", "I1.this[int]").WithLocation(43, 9), // (65,13): error CS0550: 'I2.Test3.I2.this[short].get' adds an accessor not found in interface member 'I2.this[short]' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.Test3.I2.this[short].get", "I2.this[short]").WithLocation(65, 13), // (72,13): error CS0550: 'I2.Test3.I2.this[int].set' adds an accessor not found in interface member 'I2.this[int]' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.Test3.I2.this[int].set", "I2.this[int]").WithLocation(72, 13), // (80,13): error CS0550: 'I2.ITest3.I2.this[short].get' adds an accessor not found in interface member 'I2.this[short]' // get {throw null;} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.ITest3.I2.this[short].get", "I2.this[short]").WithLocation(80, 13), // (87,13): error CS0550: 'I2.ITest3.I2.this[int].set' adds an accessor not found in interface member 'I2.this[int]' // set {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.ITest3.I2.this[int].set", "I2.this[int]").WithLocation(87, 13) ); } [Fact] public void EventModifiers_01() { var source1 = @" public interface I1 { public event System.Action P01; protected event System.Action P02 {add{}} protected internal event System.Action P03 {remove{}} internal event System.Action P04 {add{}} private event System.Action P05 {remove{}} static event System.Action P06 {add{}} virtual event System.Action P07 {remove{}} sealed event System.Action P08 {add{}} override event System.Action P09 {remove{}} abstract event System.Action P10 {add{}} extern event System.Action P11 {add{} remove{}} extern event System.Action P12 {add; remove;} extern event System.Action P13; private protected event System.Action P14; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_EventNeedsBothAccessors).Verify( // (12,34): error CS0106: The modifier 'override' is not valid for this item // override event System.Action P09 {remove{}} Diagnostic(ErrorCode.ERR_BadMemberFlag, "P09").WithArguments("override").WithLocation(12, 34), // (13,38): error CS8712: 'I1.P10': abstract event cannot use event accessor syntax // abstract event System.Action P10 {add{}} Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.P10").WithLocation(13, 38), // (14,37): error CS0179: 'I1.P11.add' cannot be extern and declare a body // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("I1.P11.add").WithLocation(14, 37), // (14,43): error CS0179: 'I1.P11.remove' cannot be extern and declare a body // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("I1.P11.remove").WithLocation(14, 43), // (15,37): warning CS0626: Method, operator, or accessor 'I1.P12.add' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "add").WithArguments("I1.P12.add").WithLocation(15, 37), // (15,40): error CS0073: An add or remove accessor must have a body // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(15, 40), // (15,42): warning CS0626: Method, operator, or accessor 'I1.P12.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "remove").WithArguments("I1.P12.remove").WithLocation(15, 42), // (15,48): error CS0073: An add or remove accessor must have a body // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(15, 48), // (16,32): warning CS0626: Method, operator, or accessor 'I1.P13.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P13; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P13").WithArguments("I1.P13.remove").WithLocation(16, 32) ); ValidateSymbolsEventModifiers_01(compilation1); } private static void ValidateSymbolsEventModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var p01 = i1.GetMember<EventSymbol>("P01"); Assert.True(p01.IsAbstract); Assert.False(p01.IsVirtual); Assert.False(p01.IsSealed); Assert.False(p01.IsStatic); Assert.False(p01.IsExtern); Assert.False(p01.IsOverride); Assert.Equal(Accessibility.Public, p01.DeclaredAccessibility); ValidateP01Accessor(p01.AddMethod); ValidateP01Accessor(p01.RemoveMethod); void ValidateP01Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } var p02 = i1.GetMember<EventSymbol>("P02"); var p02get = p02.AddMethod; Assert.False(p02.IsAbstract); Assert.True(p02.IsVirtual); Assert.False(p02.IsSealed); Assert.False(p02.IsStatic); Assert.False(p02.IsExtern); Assert.False(p02.IsOverride); Assert.Equal(Accessibility.Protected, p02.DeclaredAccessibility); Assert.False(p02get.IsAbstract); Assert.True(p02get.IsVirtual); Assert.True(p02get.IsMetadataVirtual()); Assert.False(p02get.IsSealed); Assert.False(p02get.IsStatic); Assert.False(p02get.IsExtern); Assert.False(p02get.IsAsync); Assert.False(p02get.IsOverride); Assert.Equal(Accessibility.Protected, p02get.DeclaredAccessibility); var p03 = i1.GetMember<EventSymbol>("P03"); var p03set = p03.RemoveMethod; Assert.False(p03.IsAbstract); Assert.True(p03.IsVirtual); Assert.False(p03.IsSealed); Assert.False(p03.IsStatic); Assert.False(p03.IsExtern); Assert.False(p03.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, p03.DeclaredAccessibility); Assert.False(p03set.IsAbstract); Assert.True(p03set.IsVirtual); Assert.True(p03set.IsMetadataVirtual()); Assert.False(p03set.IsSealed); Assert.False(p03set.IsStatic); Assert.False(p03set.IsExtern); Assert.False(p03set.IsAsync); Assert.False(p03set.IsOverride); Assert.Equal(Accessibility.ProtectedOrInternal, p03set.DeclaredAccessibility); var p04 = i1.GetMember<EventSymbol>("P04"); var p04get = p04.AddMethod; Assert.False(p04.IsAbstract); Assert.True(p04.IsVirtual); Assert.False(p04.IsSealed); Assert.False(p04.IsStatic); Assert.False(p04.IsExtern); Assert.False(p04.IsOverride); Assert.Equal(Accessibility.Internal, p04.DeclaredAccessibility); Assert.False(p04get.IsAbstract); Assert.True(p04get.IsVirtual); Assert.True(p04get.IsMetadataVirtual()); Assert.False(p04get.IsSealed); Assert.False(p04get.IsStatic); Assert.False(p04get.IsExtern); Assert.False(p04get.IsAsync); Assert.False(p04get.IsOverride); Assert.Equal(Accessibility.Internal, p04get.DeclaredAccessibility); var p05 = i1.GetMember<EventSymbol>("P05"); var p05set = p05.RemoveMethod; Assert.False(p05.IsAbstract); Assert.False(p05.IsVirtual); Assert.False(p05.IsSealed); Assert.False(p05.IsStatic); Assert.False(p05.IsExtern); Assert.False(p05.IsOverride); Assert.Equal(Accessibility.Private, p05.DeclaredAccessibility); Assert.False(p05set.IsAbstract); Assert.False(p05set.IsVirtual); Assert.False(p05set.IsMetadataVirtual()); Assert.False(p05set.IsSealed); Assert.False(p05set.IsStatic); Assert.False(p05set.IsExtern); Assert.False(p05set.IsAsync); Assert.False(p05set.IsOverride); Assert.Equal(Accessibility.Private, p05set.DeclaredAccessibility); var p06 = i1.GetMember<EventSymbol>("P06"); var p06get = p06.AddMethod; Assert.False(p06.IsAbstract); Assert.False(p06.IsVirtual); Assert.False(p06.IsSealed); Assert.True(p06.IsStatic); Assert.False(p06.IsExtern); Assert.False(p06.IsOverride); Assert.Equal(Accessibility.Public, p06.DeclaredAccessibility); Assert.False(p06get.IsAbstract); Assert.False(p06get.IsVirtual); Assert.False(p06get.IsMetadataVirtual()); Assert.False(p06get.IsSealed); Assert.True(p06get.IsStatic); Assert.False(p06get.IsExtern); Assert.False(p06get.IsAsync); Assert.False(p06get.IsOverride); Assert.Equal(Accessibility.Public, p06get.DeclaredAccessibility); var p07 = i1.GetMember<EventSymbol>("P07"); var p07set = p07.RemoveMethod; Assert.False(p07.IsAbstract); Assert.True(p07.IsVirtual); Assert.False(p07.IsSealed); Assert.False(p07.IsStatic); Assert.False(p07.IsExtern); Assert.False(p07.IsOverride); Assert.Equal(Accessibility.Public, p07.DeclaredAccessibility); Assert.False(p07set.IsAbstract); Assert.True(p07set.IsVirtual); Assert.True(p07set.IsMetadataVirtual()); Assert.False(p07set.IsSealed); Assert.False(p07set.IsStatic); Assert.False(p07set.IsExtern); Assert.False(p07set.IsAsync); Assert.False(p07set.IsOverride); Assert.Equal(Accessibility.Public, p07set.DeclaredAccessibility); var p08 = i1.GetMember<EventSymbol>("P08"); var p08get = p08.AddMethod; Assert.False(p08.IsAbstract); Assert.False(p08.IsVirtual); Assert.False(p08.IsSealed); Assert.False(p08.IsStatic); Assert.False(p08.IsExtern); Assert.False(p08.IsOverride); Assert.Equal(Accessibility.Public, p08.DeclaredAccessibility); Assert.False(p08get.IsAbstract); Assert.False(p08get.IsVirtual); Assert.False(p08get.IsMetadataVirtual()); Assert.False(p08get.IsSealed); Assert.False(p08get.IsStatic); Assert.False(p08get.IsExtern); Assert.False(p08get.IsAsync); Assert.False(p08get.IsOverride); Assert.Equal(Accessibility.Public, p08get.DeclaredAccessibility); var p09 = i1.GetMember<EventSymbol>("P09"); var p09set = p09.RemoveMethod; Assert.False(p09.IsAbstract); Assert.True(p09.IsVirtual); Assert.False(p09.IsSealed); Assert.False(p09.IsStatic); Assert.False(p09.IsExtern); Assert.False(p09.IsOverride); Assert.Equal(Accessibility.Public, p09.DeclaredAccessibility); Assert.False(p09set.IsAbstract); Assert.True(p09set.IsVirtual); Assert.True(p09set.IsMetadataVirtual()); Assert.False(p09set.IsSealed); Assert.False(p09set.IsStatic); Assert.False(p09set.IsExtern); Assert.False(p09set.IsAsync); Assert.False(p09set.IsOverride); Assert.Equal(Accessibility.Public, p09set.DeclaredAccessibility); var p10 = i1.GetMember<EventSymbol>("P10"); var p10get = p10.AddMethod; Assert.True(p10.IsAbstract); Assert.False(p10.IsVirtual); Assert.False(p10.IsSealed); Assert.False(p10.IsStatic); Assert.False(p10.IsExtern); Assert.False(p10.IsOverride); Assert.Equal(Accessibility.Public, p10.DeclaredAccessibility); Assert.True(p10get.IsAbstract); Assert.False(p10get.IsVirtual); Assert.True(p10get.IsMetadataVirtual()); Assert.False(p10get.IsSealed); Assert.False(p10get.IsStatic); Assert.False(p10get.IsExtern); Assert.False(p10get.IsAsync); Assert.False(p10get.IsOverride); Assert.Equal(Accessibility.Public, p10get.DeclaredAccessibility); foreach (var name in new[] { "P11", "P12", "P13" }) { var p11 = i1.GetMember<EventSymbol>(name); Assert.False(p11.IsAbstract); Assert.True(p11.IsVirtual); Assert.False(p11.IsSealed); Assert.False(p11.IsStatic); Assert.True(p11.IsExtern); Assert.False(p11.IsOverride); Assert.Equal(Accessibility.Public, p11.DeclaredAccessibility); ValidateP11Accessor(p11.AddMethod); ValidateP11Accessor(p11.RemoveMethod); void ValidateP11Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } } var p14 = i1.GetMember<EventSymbol>("P14"); Assert.True(p14.IsAbstract); Assert.False(p14.IsVirtual); Assert.False(p14.IsSealed); Assert.False(p14.IsStatic); Assert.False(p14.IsExtern); Assert.False(p14.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, p14.DeclaredAccessibility); ValidateP14Accessor(p14.AddMethod); ValidateP14Accessor(p14.RemoveMethod); void ValidateP14Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.ProtectedAndInternal, accessor.DeclaredAccessibility); } } [Fact] public void EventModifiers_02() { var source1 = @" public interface I1 { public event System.Action P01; protected event System.Action P02 {add{}} protected internal event System.Action P03 {remove{}} internal event System.Action P04 {add{}} private event System.Action P05 {remove{}} static event System.Action P06 {add{}} virtual event System.Action P07 {remove{}} sealed event System.Action P08 {add{}} override event System.Action P09 {remove{}} abstract event System.Action P10 {add{}} extern event System.Action P11 {add{} remove{}} extern event System.Action P12 {add; remove;} extern event System.Action P13; private protected event System.Action P14; protected event System.Action P15; protected internal event System.Action P16; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_EventNeedsBothAccessors).Verify( // (4,32): error CS8703: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public event System.Action P01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("public", "7.3", "8.0").WithLocation(4, 32), // (5,40): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // protected event System.Action P02 {add{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(5, 40), // (6,49): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // protected internal event System.Action P03 {remove{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(6, 49), // (7,39): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // internal event System.Action P04 {add{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(7, 39), // (8,38): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // private event System.Action P05 {remove{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(8, 38), // (9,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static event System.Action P06 {add{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "P06").WithArguments("default interface implementation", "8.0").WithLocation(9, 32), // (10,38): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual event System.Action P07 {remove{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(10, 38), // (11,37): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // sealed event System.Action P08 {add{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(11, 37), // (12,34): error CS0106: The modifier 'override' is not valid for this item // override event System.Action P09 {remove{}} Diagnostic(ErrorCode.ERR_BadMemberFlag, "P09").WithArguments("override").WithLocation(12, 34), // (12,39): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override event System.Action P09 {remove{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(12, 39), // (13,39): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract event System.Action P10 {add{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(13, 39), // (13,38): error CS8712: 'I1.P10': abstract event cannot use event accessor syntax // abstract event System.Action P10 {add{}} Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.P10").WithLocation(13, 38), // (14,37): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(14, 37), // (14,37): error CS0179: 'I1.P11.add' cannot be extern and declare a body // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("I1.P11.add").WithLocation(14, 37), // (14,43): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(14, 43), // (14,43): error CS0179: 'I1.P11.remove' cannot be extern and declare a body // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("I1.P11.remove").WithLocation(14, 43), // (15,37): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(15, 37), // (15,37): warning CS0626: Method, operator, or accessor 'I1.P12.add' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "add").WithArguments("I1.P12.add").WithLocation(15, 37), // (15,40): error CS0073: An add or remove accessor must have a body // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(15, 40), // (15,42): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(15, 42), // (15,42): warning CS0626: Method, operator, or accessor 'I1.P12.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "remove").WithArguments("I1.P12.remove").WithLocation(15, 42), // (15,48): error CS0073: An add or remove accessor must have a body // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(15, 48), // (16,32): error CS8703: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern event System.Action P13; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P13").WithArguments("extern", "7.3", "8.0").WithLocation(16, 32), // (16,32): warning CS0626: Method, operator, or accessor 'I1.P13.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P13; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P13").WithArguments("I1.P13.remove").WithLocation(16, 32), // (17,43): error CS8703: The modifier 'private protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private protected event System.Action P14; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P14").WithArguments("private protected", "7.3", "8.0").WithLocation(17, 43), // (18,35): error CS8703: The modifier 'protected' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // protected event System.Action P15; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P15").WithArguments("protected", "7.3", "8.0").WithLocation(18, 35), // (19,44): error CS8703: The modifier 'protected internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // protected internal event System.Action P16; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P16").WithArguments("protected internal", "7.3", "8.0").WithLocation(19, 44) ); ValidateSymbolsEventModifiers_01(compilation1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_EventNeedsBothAccessors).Verify( // (5,35): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected event System.Action P02 {add{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P02").WithLocation(5, 35), // (5,40): error CS8701: Target runtime doesn't support default interface implementation. // protected event System.Action P02 {add{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(5, 40), // (6,44): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal event System.Action P03 {remove{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P03").WithLocation(6, 44), // (6,49): error CS8701: Target runtime doesn't support default interface implementation. // protected internal event System.Action P03 {remove{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(6, 49), // (7,39): error CS8701: Target runtime doesn't support default interface implementation. // internal event System.Action P04 {add{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(7, 39), // (8,38): error CS8701: Target runtime doesn't support default interface implementation. // private event System.Action P05 {remove{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(8, 38), // (9,37): error CS8701: Target runtime doesn't support default interface implementation. // static event System.Action P06 {add{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(9, 37), // (10,38): error CS8701: Target runtime doesn't support default interface implementation. // virtual event System.Action P07 {remove{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(10, 38), // (11,37): error CS8701: Target runtime doesn't support default interface implementation. // sealed event System.Action P08 {add{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(11, 37), // (12,34): error CS0106: The modifier 'override' is not valid for this item // override event System.Action P09 {remove{}} Diagnostic(ErrorCode.ERR_BadMemberFlag, "P09").WithArguments("override").WithLocation(12, 34), // (12,39): error CS8701: Target runtime doesn't support default interface implementation. // override event System.Action P09 {remove{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(12, 39), // (13,39): error CS8701: Target runtime doesn't support default interface implementation. // abstract event System.Action P10 {add{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(13, 39), // (13,38): error CS8712: 'I1.P10': abstract event cannot use event accessor syntax // abstract event System.Action P10 {add{}} Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.P10").WithLocation(13, 38), // (14,37): error CS8701: Target runtime doesn't support default interface implementation. // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(14, 37), // (14,37): error CS0179: 'I1.P11.add' cannot be extern and declare a body // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("I1.P11.add").WithLocation(14, 37), // (14,43): error CS8701: Target runtime doesn't support default interface implementation. // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(14, 43), // (14,43): error CS0179: 'I1.P11.remove' cannot be extern and declare a body // extern event System.Action P11 {add{} remove{}} Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("I1.P11.remove").WithLocation(14, 43), // (15,37): error CS8701: Target runtime doesn't support default interface implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(15, 37), // (15,37): warning CS0626: Method, operator, or accessor 'I1.P12.add' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "add").WithArguments("I1.P12.add").WithLocation(15, 37), // (15,40): error CS0073: An add or remove accessor must have a body // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(15, 40), // (15,42): error CS8701: Target runtime doesn't support default interface implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(15, 42), // (15,42): warning CS0626: Method, operator, or accessor 'I1.P12.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "remove").WithArguments("I1.P12.remove").WithLocation(15, 42), // (15,48): error CS0073: An add or remove accessor must have a body // extern event System.Action P12 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(15, 48), // (16,32): error CS8701: Target runtime doesn't support default interface implementation. // extern event System.Action P13; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P13").WithLocation(16, 32), // (16,32): warning CS0626: Method, operator, or accessor 'I1.P13.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P13; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P13").WithArguments("I1.P13.remove").WithLocation(16, 32), // (17,43): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected event System.Action P14; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P14").WithLocation(17, 43), // (18,35): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected event System.Action P15; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P15").WithLocation(18, 35), // (19,44): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal event System.Action P16; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "P16").WithLocation(19, 44) ); ValidateSymbolsEventModifiers_01(compilation2); } [Fact] public void EventModifiers_03() { ValidateEventImplementation_102(@" public interface I1 { public virtual event System.Action E1 { add => System.Console.WriteLine(""add E1""); remove => System.Console.WriteLine(""remove E1""); } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.E1 += null; i1.E1 -= null; } } "); ValidateEventImplementation_102(@" public interface I1 { public virtual event System.Action E1 { add {System.Console.WriteLine(""add E1"");} remove {System.Console.WriteLine(""remove E1"");} } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.E1 += null; i1.E1 -= null; } } "); } [Fact] public void EventModifiers_04() { ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 {} } class Test1 : I1 {} ", new[] { // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 {} Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: false, haveRemove: false); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 { add; } } class Test1 : I1 {} ", new[] { // (6,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";"), // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: true, haveRemove: false); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 { add {} } } class Test1 : I1 {} ", new[] { // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: true, haveRemove: false); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 { add => throw null; } } class Test1 : I1 {} ", new[] { // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: true, haveRemove: false); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 { remove; } } class Test1 : I1 {} ", new[] { // (6,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 15), // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: false, haveRemove: true); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 { remove {} } } class Test1 : I1 {} ", new[] { // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: false, haveRemove: true); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 { remove => throw null; } } class Test1 : I1 {} ", new[] { // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: false, haveRemove: true); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 { add; remove; } } class Test1 : I1 {} ", new[] { // (6,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";"), // (7,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(7, 15) }, haveAdd: true, haveRemove: true); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1; } class Test1 : I1 {} ", new[] { // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1; Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40), // (4,40): warning CS0067: The event 'I1.E1' is never used // public virtual event System.Action E1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: true, haveRemove: true); ValidateEventImplementation_101(@" public interface I1 { public virtual event System.Action E1 = null; } class Test1 : I1 {} ", new[] { // (4,40): error CS0068: 'I1.E1': instance event in interface cannot have initializer // public virtual event System.Action E1 = null; Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "E1").WithArguments("I1.E1").WithLocation(4, 40), // (4,40): error CS0065: 'I1.E1': event property must have both add and remove accessors // public virtual event System.Action E1 = null; Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I1.E1").WithLocation(4, 40), // (4,40): warning CS0067: The event 'I1.E1' is never used // public virtual event System.Action E1 = null; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("I1.E1").WithLocation(4, 40) }, haveAdd: true, haveRemove: true); } [Fact] public void EventModifiers_05() { var source1 = @" public interface I1 { public abstract event System.Action P1; } public interface I2 { event System.Action P2; } class Test1 : I1 { public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove => System.Console.WriteLine(""set_P1""); } } class Test2 : I2 { public event System.Action P2 { add { System.Console.WriteLine(""get_P2""); } remove => System.Console.WriteLine(""set_P2""); } static void Main() { I1 x = new Test1(); x.P1 += null; x.P1 -= null; I2 y = new Test2(); y.P2 += null; y.P2 -= null; } } "; ValidateEventModifiers_05(source1); } private void ValidateEventModifiers_05(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: @"get_P1 set_P1 get_P2 set_P2", symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { for (int i = 1; i <= 2; i++) { var test1 = m.GlobalNamespace.GetTypeMember("Test" + i); var i1 = m.GlobalNamespace.GetTypeMember("I" + i); var p1 = GetSingleEvent(i1); var test1P1 = GetSingleEvent(test1); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Same(test1P1, test1.FindImplementationForInterfaceMember(p1)); ValidateAccessor(p1.AddMethod, test1P1.AddMethod); ValidateAccessor(p1.RemoveMethod, test1P1.RemoveMethod); void ValidateAccessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(implementation, test1.FindImplementationForInterfaceMember(accessor)); } } } } private static EventSymbol GetSingleEvent(NamedTypeSymbol container) { return container.GetMembers().OfType<EventSymbol>().Single(); } private static EventSymbol GetSingleEvent(CSharpCompilation compilation, string containerName) { return GetSingleEvent(compilation.GetTypeByMetadataName(containerName)); } private static EventSymbol GetSingleEvent(ModuleSymbol m, string containerName) { return GetSingleEvent(m.GlobalNamespace.GetTypeMember(containerName)); } [Fact] public void EventModifiers_06() { var source1 = @" public interface I1 { public abstract event System.Action P1; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3); compilation1.VerifyDiagnostics( // (4,41): error CS8503: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract event System.Action P1; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("abstract", "7.3", "8.0").WithLocation(4, 41), // (4,41): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public abstract event System.Action P1; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("public", "7.3", "8.0").WithLocation(4, 41) ); ValidateEventModifiers_06(compilation1); } private static void ValidateEventModifiers_06(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMember<EventSymbol>("P1"); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); ValidateAccessor(p1.AddMethod); ValidateAccessor(p1.RemoveMethod); void ValidateAccessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); } } [Fact] public void EventModifiers_07() { var source1 = @" public interface I1 { public static event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } internal static event System.Action P2 { add { System.Console.WriteLine(""get_P2""); P3 += value; } remove { System.Console.WriteLine(""set_P2""); P3 -= value; } } private static event System.Action P3 { add => System.Console.WriteLine(""get_P3""); remove => System.Console.WriteLine(""set_P3""); } } class Test1 : I1 { static void Main() { I1.P1 += null; I1.P1 -= null; I1.P2 += null; I1.P2 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 get_P3 set_P2 set_P3", symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); foreach (var tuple in new[] { (name: "P1", access: Accessibility.Public), (name: "P2", access: Accessibility.Internal), (name: "P3", access: Accessibility.Private)}) { var p1 = i1.GetMember<EventSymbol>(tuple.name); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.True(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(tuple.access, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); ValidateAccessor(p1.AddMethod); ValidateAccessor(p1.RemoveMethod); void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(tuple.access, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } var source2 = @" public interface I1 { public static event System.Action P1; internal static event System.Action P2 { add; remove; } private static event System.Action P3 = null; } class Test1 : I1 { static void Main() { } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,39): warning CS0067: The event 'I1.P1' is never used // public static event System.Action P1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P1").WithArguments("I1.P1").WithLocation(4, 39), // (8,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(8, 12), // (9,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(9, 15), // (12,40): warning CS0414: The field 'I1.P3' is assigned but its value is never used // private static event System.Action P3 = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "P3").WithArguments("I1.P3").WithLocation(12, 40) ); Validate(compilation2.SourceModule); var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyEmitDiagnostics( // (4,39): error CS8701: Target runtime doesn't support default interface implementation. // public static event System.Action P1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P1").WithLocation(4, 39), // (4,39): warning CS0067: The event 'I1.P1' is never used // public static event System.Action P1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P1").WithArguments("I1.P1").WithLocation(4, 39), // (8,9): error CS8701: Target runtime doesn't support default interface implementation. // add; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(8, 9), // (8,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(8, 12), // (9,9): error CS8701: Target runtime doesn't support default interface implementation. // remove; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(9, 9), // (9,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(9, 15), // (12,40): error CS8701: Target runtime doesn't support default interface implementation. // private static event System.Action P3 = null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P3").WithLocation(12, 40), // (12,40): warning CS0414: The field 'I1.P3' is assigned but its value is never used // private static event System.Action P3 = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "P3").WithArguments("I1.P3").WithLocation(12, 40) ); Validate(compilation3.SourceModule); } [Fact] public void EventModifiers_08() { var source1 = @" public interface I1 { abstract static event System.Action P1; virtual static event System.Action P2 {add {} remove{}} sealed static event System.Action P3 {add; remove;} } class Test1 : I1 { event System.Action I1.P1 {add {} remove{}} event System.Action I1.P2 {add {} remove{}} event System.Action I1.P3 {add {} remove{}} } class Test2 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.Net60); compilation1.VerifyDiagnostics( // (8,46): error CS0073: An add or remove accessor must have a body // sealed static event System.Action P3 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(8, 46), // (8,54): error CS0073: An add or remove accessor must have a body // sealed static event System.Action P3 {add; remove;} Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(8, 54), // (6,40): error CS0112: A static member cannot be marked as 'virtual' // virtual static event System.Action P2 {add {} remove{}} Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P2").WithArguments("virtual").WithLocation(6, 40), // (8,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static event System.Action P3 {add; remove;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P3").WithArguments("sealed", "9.0", "preview").WithLocation(8, 39), // (4,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P1; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("abstract", "9.0", "preview").WithLocation(4, 41), // (13,28): error CS0539: 'Test1.P1' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.P1 {add {} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("Test1.P1").WithLocation(13, 28), // (14,28): error CS0539: 'Test1.P2' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.P2 {add {} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P2").WithArguments("Test1.P2").WithLocation(14, 28), // (15,28): error CS0539: 'Test1.P3' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.P3 {add {} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test1.P3").WithLocation(15, 28), // (18,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(18, 15), // (11,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(11, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMember<EventSymbol>("P1"); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.True(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); ValidateAccessor1(p1.AddMethod); ValidateAccessor1(p1.RemoveMethod); void ValidateAccessor1(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } var p2 = i1.GetMember<EventSymbol>("P2"); Assert.False(p2.IsAbstract); Assert.False(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.True(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2)); ValidateAccessor2(p2.AddMethod); ValidateAccessor2(p2.RemoveMethod); void ValidateAccessor2(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } var p3 = i1.GetMember<EventSymbol>("P3"); Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.False(p3.IsSealed); Assert.True(p3.IsStatic); Assert.False(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); ValidateAccessor3(p3.AddMethod); ValidateAccessor3(p3.RemoveMethod); void ValidateAccessor3(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } [Fact] public void EventModifiers_09() { var source1 = @" public interface I1 { private event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } sealed void M() { P1 += null; P1 -= null; } } public interface I2 { private event System.Action P2 { add => System.Console.WriteLine(""get_P2""); remove => System.Console.WriteLine(""set_P2""); } sealed void M() { P2 += null; P2 -= null; } } class Test1 : I1, I2 { static void Main() { I1 x1 = new Test1(); x1.M(); I2 x2 = new Test1(); x2.M(); } } "; ValidateEventModifiers_09(source1); } private void ValidateEventModifiers_09(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 set_P2 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); for (int i = 1; i <= 2; i++) { var i1 = m.GlobalNamespace.GetTypeMember("I" + i); var p1 = GetSingleEvent(i1); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Private, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); ValidateAccessor(p1.AddMethod); ValidateAccessor(p1.RemoveMethod); void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } } [Fact] public void EventModifiers_10() { var source1 = @" public interface I1 { abstract private event System.Action P1; virtual private event System.Action P2; sealed private event System.Action P3 { add => throw null; remove {} } private event System.Action P4 = null; } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics( // (4,42): error CS0621: 'I1.P1': virtual or abstract members cannot be private // abstract private event System.Action P1; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P1").WithArguments("I1.P1").WithLocation(4, 42), // (6,41): error CS0065: 'I1.P2': event property must have both add and remove accessors // virtual private event System.Action P2; Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P2").WithArguments("I1.P2").WithLocation(6, 41), // (6,41): error CS0621: 'I1.P2': virtual or abstract members cannot be private // virtual private event System.Action P2; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P2").WithArguments("I1.P2").WithLocation(6, 41), // (6,41): warning CS0067: The event 'I1.P2' is never used // virtual private event System.Action P2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P2").WithArguments("I1.P2").WithLocation(6, 41), // (8,40): error CS0238: 'I1.P3' cannot be sealed because it is not an override // sealed private event System.Action P3 Diagnostic(ErrorCode.ERR_SealedNonOverride, "P3").WithArguments("I1.P3").WithLocation(8, 40), // (14,33): error CS0068: 'I1.P4': instance event in interface cannot have initializer // private event System.Action P4 = null; Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "P4").WithArguments("I1.P4").WithLocation(14, 33), // (14,33): error CS0065: 'I1.P4': event property must have both add and remove accessors // private event System.Action P4 = null; Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P4").WithArguments("I1.P4").WithLocation(14, 33), // (17,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1"), // (14,33): warning CS0067: The event 'I1.P4' is never used // private event System.Action P4 = null; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P4").WithArguments("I1.P4").WithLocation(14, 33) ); ValidateEventModifiers_10(compilation1); } private static void ValidateEventModifiers_10(CSharpCompilation compilation1) { var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMembers().OfType<EventSymbol>().ElementAt(0); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Private, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); ValidateP1Accessor(p1.AddMethod); ValidateP1Accessor(p1.RemoveMethod); void ValidateP1Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } var p2 = i1.GetMembers().OfType<EventSymbol>().ElementAt(1); Assert.False(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Private, p2.DeclaredAccessibility); Assert.Same(p2, test1.FindImplementationForInterfaceMember(p2)); ValidateP2Accessor(p2.AddMethod); ValidateP2Accessor(p2.RemoveMethod); void ValidateP2Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Same(accessor, test1.FindImplementationForInterfaceMember(accessor)); } var p3 = i1.GetMembers().OfType<EventSymbol>().ElementAt(2); Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.True(p3.IsSealed); Assert.False(p3.IsStatic); Assert.False(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Private, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.AddMethod); ValidateP3Accessor(p3.RemoveMethod); void ValidateP3Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.True(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } var p4 = i1.GetMembers().OfType<EventSymbol>().ElementAt(3); Assert.False(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.False(p4.IsStatic); Assert.False(p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Private, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); ValidateP4Accessor(p4.AddMethod); ValidateP4Accessor(p4.RemoveMethod); void ValidateP4Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } [Fact] public void EventModifiers_11_01() { var source1 = @" public interface I1 { internal abstract event System.Action P1; sealed void Test() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11(source1, source2, Accessibility.Internal, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } private void ValidateEventModifiers_11(string source1, string source2, Accessibility accessibility, DiagnosticDescription[] expected1, params DiagnosticDescription[] expected2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected1); Validate1(compilation1.SourceModule); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => Validate1(m)).VerifyDiagnostics(); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var p1 = GetSingleEvent(i1); var test1P1 = GetSingleEvent(test1); var p1add = p1.AddMethod; var p1remove = p1.RemoveMethod; ValidateEvent(p1); ValidateMethod(p1add); ValidateMethod(p1remove); Assert.Same(test1P1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test1P1.AddMethod, test1.FindImplementationForInterfaceMember(p1add)); Assert.Same(test1P1.RemoveMethod, test1.FindImplementationForInterfaceMember(p1remove)); } void ValidateEvent(EventSymbol p1) { Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(accessibility, p1.DeclaredAccessibility); } void ValidateMethod(MethodSymbol m1) { Assert.True(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(accessibility, m1.DeclaredAccessibility); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var p1 = GetSingleEvent(i1); ValidateEvent(p1); ValidateMethod(p1.AddMethod); ValidateMethod(p1.RemoveMethod); } var source3 = @" class Test2 : I1 { } "; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected1); Validate1(compilation3.SourceModule); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => Validate1(m)).VerifyDiagnostics(); Validate1(compilation3.SourceModule); var compilation5 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics(expected2); ValidateEventNotImplemented_11(compilation5, "Test2"); } } private static void ValidateEventNotImplemented_11(CSharpCompilation compilation, string className) { var test2 = compilation.GetTypeByMetadataName(className); var i1 = compilation.GetTypeByMetadataName("I1"); var p1 = GetSingleEvent(i1); Assert.Null(test2.FindImplementationForInterfaceMember(p1)); Assert.Null(test2.FindImplementationForInterfaceMember(p1.AddMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(p1.RemoveMethod)); } [Fact] public void EventModifiers_11_02() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_02(source1, source2, // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 15) ); } private void ValidateEventModifiers_11_02(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(expected); ValidateEventImplementation_11(compilation1.SourceModule); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateEventImplementation_11(m)).VerifyDiagnostics(); ValidateEventImplementation_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(expected); ValidateEventImplementation_11(compilation3.SourceModule); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateEventImplementation_11(m)).VerifyDiagnostics(); ValidateEventImplementation_11(compilation3.SourceModule); } } private static void ValidateEventImplementation_11(ModuleSymbol m) { ValidateEventImplementation_11(m, implementedByBase: false); } private static void ValidateEventImplementationByBase_11(ModuleSymbol m) { ValidateEventImplementation_11(m, implementedByBase: true); } private static void ValidateEventImplementation_11(ModuleSymbol m, bool implementedByBase) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var p1 = GetSingleEvent(i1); var test1P1 = GetSingleEvent(implementedByBase ? test1.BaseTypeNoUseSiteDiagnostics : test1); var p1Add = p1.AddMethod; var p1Remove = p1.RemoveMethod; Assert.Same(test1P1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test1P1.AddMethod, test1.FindImplementationForInterfaceMember(p1Add)); Assert.Same(test1P1.RemoveMethod, test1.FindImplementationForInterfaceMember(p1Remove)); Assert.True(test1P1.AddMethod.IsMetadataVirtual()); Assert.True(test1P1.RemoveMethod.IsMetadataVirtual()); } [Fact] public void EventModifiers_11_03() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } event System.Action I1.P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_03(source1, source2, TargetFramework.Standard, // (9,28): error CS0122: 'I1.P1' is inaccessible due to its protection level // event System.Action I1.P1 Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(9, 28) ); } private void ValidateEventModifiers_11_03(string source1, string source2, TargetFramework targetFramework, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, targetFramework: targetFramework, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: !(targetFramework == TargetFramework.Standard || ExecutionConditionUtil.IsMonoOrCoreClr) ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementation_11); ValidateEventImplementation_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: targetFramework, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: targetFramework); compilation3.VerifyDiagnostics(expected); if (expected.Length == 0) { CompileAndVerify(compilation3, expectedOutput: !(targetFramework == TargetFramework.Standard || ExecutionConditionUtil.IsMonoOrCoreClr) ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementation_11); } ValidateEventImplementation_11(compilation3.SourceModule); } } [Fact] public void EventModifiers_11_04() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } public class Test2 : I1 { event System.Action I1.P1 { add { System.Console.WriteLine(""Test2.get_P1""); } remove { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void EventModifiers_11_05() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } public class Test2 : I1 { event System.Action I1.P1 { add { System.Console.WriteLine(""Test2.get_P1""); } remove { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void EventModifiers_11_06() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } public class Test2 : I1 { event System.Action I1.P1 { add { System.Console.WriteLine(""Test2.get_P1""); } remove { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @"abstract class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test3()); } public abstract event System.Action P1; } class Test3 : Test1 { public override event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void EventModifiers_11_07() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } public class Test2 : I1 { event System.Action I1.P1 { add { System.Console.WriteLine(""Test2.get_P1""); } remove { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1, I2 { static void Main() { TestHelper.CallP1(new Test1()); } public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } public interface I2 { event System.Action P1; } "; ValidateEventModifiers_11_02(source1, source2, // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : Test2, I1, I2 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 22) ); } [Fact] public void EventModifiers_11_08() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } public class Test2 : I1 { event System.Action I1.P1 { add { System.Console.WriteLine(""Test2.get_P1""); } remove { System.Console.WriteLine(""Test2.set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual event System.Action<object> P1 { add { System.Console.WriteLine(""Test1.get_P1""); } remove { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidateEventModifiers_11_08(source1, source2); } private void ValidateEventModifiers_11_08(string source1, string source2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: @"Test2.get_P1 Test2.set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationByBase_11); ValidateEventImplementationByBase_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation3, expectedOutput: @"Test2.get_P1 Test2.set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationByBase_11); ValidateEventImplementationByBase_11(compilation3.SourceModule); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation4, expectedOutput: @"Test2.get_P1 Test2.set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationByBase_11); ValidateEventImplementationByBase_11(compilation4.SourceModule); } [Fact] public void EventModifiers_11_09() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } public class TestHelper { public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { TestHelper.CallP1(new Test1()); } public virtual event System.Action<object> P1 { add { System.Console.WriteLine(""Test1.get_P1""); } remove { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidateEventModifiers_11_09(source1, source2, // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.P1'. 'Test1.P1' cannot implement 'I1.P1' because it does not have the matching return type of 'Action'. // class Test1 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("Test1", "I1.P1", "Test1.P1", "System.Action").WithLocation(2, 15) ); } private void ValidateEventModifiers_11_09(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics(expected); ValidateEventNotImplemented_11(compilation1, "Test1"); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation3.VerifyDiagnostics(expected); ValidateEventNotImplemented_11(compilation3, "Test1"); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation4.VerifyDiagnostics(expected); ValidateEventNotImplemented_11(compilation4, "Test1"); } [Fact] public void EventModifiers_11_10() { var source1 = @" public interface I1 { internal abstract event System.Action P1; sealed void Test() { P1 += null; P1 -= null; } } "; var source2 = @" public class Test2 : I1 { public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidateEventModifiers_11_10(source1, source2, // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.remove'. 'Test2.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.remove", "Test2.P1.remove", "9.0", "10.0").WithLocation(2, 22), // (2,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.add'. 'Test2.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.add", "Test2.P1.add", "9.0", "10.0").WithLocation(2, 22) ); } private void ValidateEventModifiers_11_10(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(expected); ValidateEventImplementationByBase_11(compilation1.SourceModule); compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateEventImplementationByBase_11(m)).VerifyDiagnostics(); ValidateEventImplementationByBase_11(compilation1.SourceModule); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(expected); ValidateEventImplementationByBase_11(compilation3.SourceModule); compilation3 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateEventImplementationByBase_11(m)).VerifyDiagnostics(); ValidateEventImplementationByBase_11(compilation3.SourceModule); } } [Fact] public void EventModifiers_11_11() { var source1 = @" public interface I1 { internal abstract event System.Action P1; sealed void Test() { P1 += null; P1 -= null; } } public class Test2 : I1 { public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; var source2 = @" class Test1 : Test2, I1 { static void Main() { I1 x = new Test1(); x.Test(); } } "; ValidateEventModifiers_11_11(source1, source2, // (12,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.remove'. 'Test2.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.remove", "Test2.P1.remove", "9.0", "10.0").WithLocation(12, 22), // (12,22): error CS8704: 'Test2' does not implement interface member 'I1.P1.add'. 'Test2.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class Test2 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test2", "I1.P1.add", "Test2.P1.add", "9.0", "10.0").WithLocation(12, 22) ); } private void ValidateEventModifiers_11_11(string source1, string source2, params DiagnosticDescription[] expected) { var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, assemblyName: "EventModifiers_11_11"); compilation2.VerifyDiagnostics(expected); compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp, assemblyName: "EventModifiers_11_11"); compilation2.VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1", verify: VerifyOnMonoOrCoreClr, symbolValidator: (m) => ValidateEventImplementationByBase_11(m)).VerifyDiagnostics(); ValidateEventImplementationByBase_11(compilation3.SourceModule); } [Fact] public void EventModifiers_12() { var source1 = @" public interface I1 { internal abstract event System.Action P1; } class Test1 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); var test1 = compilation1.GetTypeByMetadataName("Test1"); var i1 = compilation1.GetTypeByMetadataName("I1"); var p1 = i1.GetMember<EventSymbol>("P1"); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Null(test1.FindImplementationForInterfaceMember(p1.AddMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(p1.RemoveMethod)); } [Fact] public void EventModifiers_13() { var source1 = @" public interface I1 { public sealed event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } public interface I2 { public sealed event System.Action P2 { add => System.Console.WriteLine(""get_P2""); remove => System.Console.WriteLine(""set_P2""); } } class Test1 : I1 { static void Main() { I1 i1 = new Test1(); i1.P1 += null; i1.P1 -= null; I2 i2 = new Test2(); i2.P2 += null; i2.P2 -= null; } public event System.Action P1 { add => throw null; remove => throw null; } } class Test2 : I2 { public event System.Action P2 { add => throw null; remove => throw null; } } "; ValidateEventModifiers_13(source1); } private void ValidateEventModifiers_13(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); void Validate(ModuleSymbol m) { for (int i = 1; i <= 2; i++) { var test1 = m.GlobalNamespace.GetTypeMember("Test" + i); var i1 = m.GlobalNamespace.GetTypeMember("I" + i); var p1 = GetSingleEvent(i1); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); ValidateAccessor(p1.AddMethod); ValidateAccessor(p1.RemoveMethod); void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 set_P2 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); } [Fact] public void EventModifiers_14() { var source1 = @" public interface I1 { public sealed event System.Action P1 = null; } public interface I2 { abstract sealed event System.Action P2 {add; remove;} } public interface I3 { virtual sealed event System.Action P3 { add {} remove {} } } class Test1 : I1, I2, I3 { event System.Action I1.P1 { add => throw null; remove => throw null; } event System.Action I2.P2 { add => throw null; remove => throw null; } event System.Action I3.P3 { add => throw null; remove => throw null; } } class Test2 : I1, I2, I3 {} "; ValidateEventModifiers_14(source1, // (4,39): error CS0068: 'I1.P1': instance event in interface cannot have initializer // public sealed event System.Action P1 = null; Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "P1").WithArguments("I1.P1").WithLocation(4, 39), // (4,39): error CS0065: 'I1.P1': event property must have both add and remove accessors // public sealed event System.Action P1; Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P1").WithArguments("I1.P1").WithLocation(4, 39), // (8,41): error CS0238: 'I2.P2' cannot be sealed because it is not an override // abstract sealed event System.Action P2 {add; remove;} Diagnostic(ErrorCode.ERR_SealedNonOverride, "P2").WithArguments("I2.P2").WithLocation(8, 41), // (8,44): error CS8712: 'I2.P2': abstract event cannot use event accessor syntax // abstract sealed event System.Action P2 {add; remove;} Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.P2").WithLocation(8, 44), // (12,40): error CS0238: 'I3.P3' cannot be sealed because it is not an override // virtual sealed event System.Action P3 Diagnostic(ErrorCode.ERR_SealedNonOverride, "P3").WithArguments("I3.P3").WithLocation(12, 40), // (21,28): error CS0539: 'Test1.P1' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.P1 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("Test1.P1").WithLocation(21, 28), // (22,28): error CS0539: 'Test1.P2' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I2.P2 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P2").WithArguments("Test1.P2").WithLocation(22, 28), // (23,28): error CS0539: 'Test1.P3' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I3.P3 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test1.P3").WithLocation(23, 28), // (4,39): warning CS0067: The event 'I1.P1' is never used // public sealed event System.Action P1 = null; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P1").WithArguments("I1.P1").WithLocation(4, 39) ); } private void ValidateEventModifiers_14(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var p1 = GetSingleEvent(compilation1, "I1"); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Null(test2.FindImplementationForInterfaceMember(p1)); Validate1(p1.AddMethod); Validate1(p1.RemoveMethod); void Validate1(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p2 = GetSingleEvent(compilation1, "I2"); var test1P2 = test1.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); Assert.True(p2.IsAbstract); Assert.False(p2.IsVirtual); Assert.True(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2)); Assert.Null(test2.FindImplementationForInterfaceMember(p2)); Validate2(p2.AddMethod); Validate2(p2.RemoveMethod); void Validate2(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.True(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p3 = GetSingleEvent(compilation1, "I3"); var test1P3 = test1.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I3.")).Single(); Assert.False(p3.IsAbstract); Assert.True(p3.IsVirtual); Assert.True(p3.IsSealed); Assert.False(p3.IsStatic); Assert.False(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); Validate3(p3.AddMethod); Validate3(p3.RemoveMethod); void Validate3(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.True(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } } [Fact] public void EventModifiers_15() { var source1 = @" public interface I0 { abstract virtual event System.Action P0; } public interface I1 { abstract virtual event System.Action P1 { add { throw null; } } } public interface I2 { virtual abstract event System.Action P2 { add { throw null; } remove { throw null; } } } public interface I3 { abstract virtual event System.Action P3 { remove { throw null; } } } public interface I4 { abstract virtual event System.Action P4 { add => throw null; } } public interface I5 { abstract virtual event System.Action P5 { add => throw null; remove => throw null; } } public interface I6 { abstract virtual event System.Action P6 { remove => throw null; } } public interface I7 { abstract virtual event System.Action P7 { add; } } public interface I8 { abstract virtual event System.Action P8 { remove; } } class Test1 : I0, I1, I2, I3, I4, I5, I6, I7, I8 { event System.Action I0.P0 { add { throw null; } remove { throw null; } } event System.Action I1.P1 { add { throw null; } } event System.Action I2.P2 { add { throw null; } remove { throw null; } } event System.Action I3.P3 { remove { throw null; } } event System.Action I4.P4 { add { throw null; } } event System.Action I5.P5 { add { throw null; } remove { throw null; } } event System.Action I6.P6 { remove { throw null; } } event System.Action I7.P7 { add { throw null; } } event System.Action I8.P8 { remove { throw null; } } } class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 {} "; ValidateEventModifiers_15(source1, // (4,42): error CS0503: The abstract event 'I0.P0' cannot be marked virtual // abstract virtual event System.Action P0; Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P0").WithArguments("event", "I0.P0").WithLocation(4, 42), // (8,42): error CS0503: The abstract event 'I1.P1' cannot be marked virtual // abstract virtual event System.Action P1 { add { throw null; } } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P1").WithArguments("event", "I1.P1").WithLocation(8, 42), // (8,45): error CS8712: 'I1.P1': abstract event cannot use event accessor syntax // abstract virtual event System.Action P1 { add { throw null; } } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.P1").WithLocation(8, 45), // (12,42): error CS0503: The abstract event 'I2.P2' cannot be marked virtual // virtual abstract event System.Action P2 Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P2").WithArguments("event", "I2.P2").WithLocation(12, 42), // (13,5): error CS8712: 'I2.P2': abstract event cannot use event accessor syntax // { Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.P2").WithLocation(13, 5), // (20,42): error CS0503: The abstract event 'I3.P3' cannot be marked virtual // abstract virtual event System.Action P3 { remove { throw null; } } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P3").WithArguments("event", "I3.P3").WithLocation(20, 42), // (20,45): error CS8712: 'I3.P3': abstract event cannot use event accessor syntax // abstract virtual event System.Action P3 { remove { throw null; } } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I3.P3").WithLocation(20, 45), // (24,42): error CS0503: The abstract event 'I4.P4' cannot be marked virtual // abstract virtual event System.Action P4 { add => throw null; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P4").WithArguments("event", "I4.P4").WithLocation(24, 42), // (24,45): error CS8712: 'I4.P4': abstract event cannot use event accessor syntax // abstract virtual event System.Action P4 { add => throw null; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I4.P4").WithLocation(24, 45), // (28,42): error CS0503: The abstract event 'I5.P5' cannot be marked virtual // abstract virtual event System.Action P5 Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P5").WithArguments("event", "I5.P5").WithLocation(28, 42), // (29,5): error CS8712: 'I5.P5': abstract event cannot use event accessor syntax // { Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I5.P5").WithLocation(29, 5), // (36,42): error CS0503: The abstract event 'I6.P6' cannot be marked virtual // abstract virtual event System.Action P6 { remove => throw null; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P6").WithArguments("event", "I6.P6").WithLocation(36, 42), // (36,45): error CS8712: 'I6.P6': abstract event cannot use event accessor syntax // abstract virtual event System.Action P6 { remove => throw null; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I6.P6").WithLocation(36, 45), // (40,42): error CS0503: The abstract event 'I7.P7' cannot be marked virtual // abstract virtual event System.Action P7 { add; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P7").WithArguments("event", "I7.P7").WithLocation(40, 42), // (40,45): error CS8712: 'I7.P7': abstract event cannot use event accessor syntax // abstract virtual event System.Action P7 { add; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I7.P7").WithLocation(40, 45), // (44,42): error CS0503: The abstract event 'I8.P8' cannot be marked virtual // abstract virtual event System.Action P8 { remove; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P8").WithArguments("event", "I8.P8").WithLocation(44, 42), // (44,45): error CS8712: 'I8.P8': abstract event cannot use event accessor syntax // abstract virtual event System.Action P8 { remove; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I8.P8").WithLocation(44, 45), // (54,28): error CS0065: 'Test1.I1.P1': event property must have both add and remove accessors // event System.Action I1.P1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P1").WithArguments("Test1.I1.P1").WithLocation(54, 28), // (63,28): error CS0065: 'Test1.I3.P3': event property must have both add and remove accessors // event System.Action I3.P3 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P3").WithArguments("Test1.I3.P3").WithLocation(63, 28), // (67,28): error CS0065: 'Test1.I4.P4': event property must have both add and remove accessors // event System.Action I4.P4 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P4").WithArguments("Test1.I4.P4").WithLocation(67, 28), // (76,28): error CS0065: 'Test1.I6.P6': event property must have both add and remove accessors // event System.Action I6.P6 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P6").WithArguments("Test1.I6.P6").WithLocation(76, 28), // (80,28): error CS0065: 'Test1.I7.P7': event property must have both add and remove accessors // event System.Action I7.P7 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P7").WithArguments("Test1.I7.P7").WithLocation(80, 28), // (84,28): error CS0065: 'Test1.I8.P8': event property must have both add and remove accessors // event System.Action I8.P8 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P8").WithArguments("Test1.I8.P8").WithLocation(84, 28), // (90,15): error CS0535: 'Test2' does not implement interface member 'I0.P0' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I0").WithArguments("Test2", "I0.P0").WithLocation(90, 15), // (90,19): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(90, 19), // (90,23): error CS0535: 'Test2' does not implement interface member 'I2.P2' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I2.P2").WithLocation(90, 23), // (90,27): error CS0535: 'Test2' does not implement interface member 'I3.P3' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test2", "I3.P3").WithLocation(90, 27), // (90,31): error CS0535: 'Test2' does not implement interface member 'I4.P4' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test2", "I4.P4").WithLocation(90, 31), // (90,35): error CS0535: 'Test2' does not implement interface member 'I5.P5' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I5").WithArguments("Test2", "I5.P5").WithLocation(90, 35), // (90,39): error CS0535: 'Test2' does not implement interface member 'I6.P6' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I6").WithArguments("Test2", "I6.P6").WithLocation(90, 39), // (90,43): error CS0535: 'Test2' does not implement interface member 'I7.P7' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I7").WithArguments("Test2", "I7.P7").WithLocation(90, 43), // (90,47): error CS0535: 'Test2' does not implement interface member 'I8.P8' // class Test2 : I0, I1, I2, I3, I4, I5, I6, I7, I8 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I8").WithArguments("Test2", "I8.P8").WithLocation(90, 47) ); } private void ValidateEventModifiers_15(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); for (int i = 0; i <= 8; i++) { var i1 = compilation1.GetTypeByMetadataName("I" + i); var p2 = GetSingleEvent(i1); var test1P2 = test1.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith(i1.Name)).Single(); Assert.True(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Same(test1P2, test1.FindImplementationForInterfaceMember(p2)); Assert.Null(test2.FindImplementationForInterfaceMember(p2)); switch (i) { case 3: case 6: case 8: Assert.Null(p2.AddMethod); ValidateAccessor(p2.RemoveMethod, test1P2.RemoveMethod); break; case 1: case 4: case 7: Assert.Null(p2.RemoveMethod); ValidateAccessor(p2.AddMethod, test1P2.AddMethod); break; default: ValidateAccessor(p2.AddMethod, test1P2.AddMethod); ValidateAccessor(p2.RemoveMethod, test1P2.RemoveMethod); break; } void ValidateAccessor(MethodSymbol accessor, MethodSymbol implementedBy) { Assert.True(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(implementedBy, test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } } } [Fact] public void EventModifiers_16() { var source1 = @" public interface I1 { extern event System.Action P1; } public interface I2 { virtual extern event System.Action P2; } public interface I3 { static extern event System.Action P3; } public interface I4 { private extern event System.Action P4; } public interface I5 { extern sealed event System.Action P5; } public interface I6 { static event System.Action P6 { add => throw null; remove => throw null; } } class Test1 : I1, I2, I3, I4, I5 { } class Test2 : I1, I2, I3, I4, I5 { event System.Action I1.P1 { add{} remove{} } event System.Action I2.P2 { add{} remove{} } } "; ValidateEventModifiers_16(source1); } private void ValidateEventModifiers_16(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test2 = m.GlobalNamespace.GetTypeMember("Test2"); bool isSource = !(m is PEModuleSymbol); var p1 = GetSingleEvent(m, "I1"); var test2P1 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I1.")).Single(); Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.Equal(isSource, p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test2P1, test2.FindImplementationForInterfaceMember(p1)); ValidateP1Accessor(p1.AddMethod, test2P1.AddMethod); ValidateP1Accessor(p1.RemoveMethod, test2P1.RemoveMethod); void ValidateP1Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.Equal(isSource, accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(accessor, test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p2 = GetSingleEvent(m, "I2"); var test2P2 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); Assert.False(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.Equal(isSource, p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Same(p2, test1.FindImplementationForInterfaceMember(p2)); Assert.Same(test2P2, test2.FindImplementationForInterfaceMember(p2)); ValidateP2Accessor(p2.AddMethod, test2P2.AddMethod); ValidateP2Accessor(p2.RemoveMethod, test2P2.RemoveMethod); void ValidateP2Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.Equal(isSource, accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(accessor, test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var i3 = m.ContainingAssembly.GetTypeByMetadataName("I3"); var p3 = GetSingleEvent(i3); Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.False(p3.IsSealed); Assert.True(p3.IsStatic); Assert.Equal(isSource, p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.AddMethod); ValidateP3Accessor(p3.RemoveMethod); void ValidateP3Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.Equal(isSource, accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p4 = GetSingleEvent(m, "I4"); Assert.False(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.False(p4.IsStatic); Assert.Equal(isSource, p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Private, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); Assert.Null(test2.FindImplementationForInterfaceMember(p4)); ValidateP4Accessor(p4.AddMethod); ValidateP4Accessor(p4.RemoveMethod); void ValidateP4Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.Equal(isSource, accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p5 = GetSingleEvent(m, "I5"); Assert.False(p5.IsAbstract); Assert.False(p5.IsVirtual); Assert.False(p5.IsSealed); Assert.False(p5.IsStatic); Assert.Equal(isSource, p5.IsExtern); Assert.False(p5.IsOverride); Assert.Equal(Accessibility.Public, p5.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5)); Assert.Null(test2.FindImplementationForInterfaceMember(p5)); ValidateP5Accessor(p5.AddMethod); ValidateP5Accessor(p5.RemoveMethod); void ValidateP5Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.Equal(isSource, accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern event System.Action P1; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("extern", "7.3", "8.0").WithLocation(4, 32), // (8,40): error CS8703: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern event System.Action P2; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P2").WithArguments("extern", "7.3", "8.0").WithLocation(8, 40), // (8,40): error CS8703: The modifier 'virtual' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual extern event System.Action P2; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P2").WithArguments("virtual", "7.3", "8.0").WithLocation(8, 40), // (12,39): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static extern event System.Action P3; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P3").WithArguments("static", "7.3", "8.0").WithLocation(12, 39), // (12,39): error CS8703: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static extern event System.Action P3; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P3").WithArguments("extern", "7.3", "8.0").WithLocation(12, 39), // (16,40): error CS8703: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern event System.Action P4; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P4").WithArguments("private", "7.3", "8.0").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private extern event System.Action P4; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P4").WithArguments("extern", "7.3", "8.0").WithLocation(16, 40), // (20,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed event System.Action P5; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P5").WithArguments("sealed", "7.3", "8.0").WithLocation(20, 39), // (20,39): error CS8703: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern sealed event System.Action P5; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P5").WithArguments("extern", "7.3", "8.0").WithLocation(20, 39), // (24,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static event System.Action P6 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "P6").WithArguments("default interface implementation", "8.0").WithLocation(24, 32), // (8,40): warning CS0626: Method, operator, or accessor 'I2.P2.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern event System.Action P2; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P2").WithArguments("I2.P2.remove").WithLocation(8, 40), // (12,39): warning CS0626: Method, operator, or accessor 'I3.P3.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern event System.Action P3; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P3").WithArguments("I3.P3.remove").WithLocation(12, 39), // (16,40): warning CS0626: Method, operator, or accessor 'I4.P4.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern event System.Action P4; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P4").WithArguments("I4.P4.remove").WithLocation(16, 40), // (20,39): warning CS0626: Method, operator, or accessor 'I5.P5.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed event System.Action P5; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P5").WithArguments("I5.P5.remove").WithLocation(20, 39), // (4,32): warning CS0626: Method, operator, or accessor 'I1.P1.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P1; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P1").WithArguments("I1.P1.remove").WithLocation(4, 32) ); Validate(compilation2.SourceModule); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (4,32): error CS8701: Target runtime doesn't support default interface implementation. // extern event System.Action P1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P1").WithLocation(4, 32), // (8,40): error CS8701: Target runtime doesn't support default interface implementation. // virtual extern event System.Action P2; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P2").WithLocation(8, 40), // (16,40): error CS8701: Target runtime doesn't support default interface implementation. // private extern event System.Action P4; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P4").WithLocation(16, 40), // (20,39): error CS8701: Target runtime doesn't support default interface implementation. // extern sealed event System.Action P5; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P5").WithLocation(20, 39), // (8,40): warning CS0626: Method, operator, or accessor 'I2.P2.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // virtual extern event System.Action P2; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P2").WithArguments("I2.P2.remove").WithLocation(8, 40), // (12,39): error CS8701: Target runtime doesn't support default interface implementation. // static extern event System.Action P3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P3").WithLocation(12, 39), // (12,39): warning CS0626: Method, operator, or accessor 'I3.P3.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern event System.Action P3; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P3").WithArguments("I3.P3.remove").WithLocation(12, 39), // (16,40): warning CS0626: Method, operator, or accessor 'I4.P4.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // private extern event System.Action P4; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P4").WithArguments("I4.P4.remove").WithLocation(16, 40), // (20,39): warning CS0626: Method, operator, or accessor 'I5.P5.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern sealed event System.Action P5; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P5").WithArguments("I5.P5.remove").WithLocation(20, 39), // (4,32): warning CS0626: Method, operator, or accessor 'I1.P1.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P1; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P1").WithArguments("I1.P1.remove").WithLocation(4, 32), // (26,9): error CS8701: Target runtime doesn't support default interface implementation. // add => throw null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(26, 9), // (27,9): error CS8701: Target runtime doesn't support default interface implementation. // remove => throw null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(27, 9) ); Validate(compilation3.SourceModule); } [Fact] public void EventModifiers_17() { var source1 = @" public interface I1 { abstract extern event System.Action P1; } public interface I2 { extern event System.Action P2 = null; } public interface I3 { static extern event System.Action P3 {add => throw null; remove => throw null;} } public interface I4 { private extern event System.Action P4 { add {throw null;} remove {throw null;}} } class Test1 : I1, I2, I3, I4 { } class Test2 : I1, I2, I3, I4 { event System.Action I1.P1 { add => throw null; remove => throw null;} event System.Action I2.P2 { add => throw null; remove => throw null;} event System.Action I3.P3 { add => throw null; remove => throw null;} event System.Action I4.P4 { add => throw null; remove => throw null;} } "; ValidateEventModifiers_17(source1, // (4,41): error CS0180: 'I1.P1' cannot be both extern and abstract // abstract extern event System.Action P1; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P1").WithArguments("I1.P1").WithLocation(4, 41), // (8,32): error CS0068: 'I2.P2': instance event in interface cannot have initializer // extern event System.Action P2 = null; Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "P2").WithArguments("I2.P2").WithLocation(8, 32), // (12,43): error CS0179: 'I3.P3.add' cannot be extern and declare a body // static extern event System.Action P3 {add => throw null; remove => throw null;} Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("I3.P3.add").WithLocation(12, 43), // (12,62): error CS0179: 'I3.P3.remove' cannot be extern and declare a body // static extern event System.Action P3 {add => throw null; remove => throw null;} Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("I3.P3.remove").WithLocation(12, 62), // (16,45): error CS0179: 'I4.P4.add' cannot be extern and declare a body // private extern event System.Action P4 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("I4.P4.add").WithLocation(16, 45), // (16,63): error CS0179: 'I4.P4.remove' cannot be extern and declare a body // private extern event System.Action P4 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("I4.P4.remove").WithLocation(16, 63), // (19,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1, I2, I3, I4 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(19, 15), // (27,28): error CS0539: 'Test2.P3' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I3.P3 { add => throw null; remove => throw null;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test2.P3").WithLocation(27, 28), // (28,28): error CS0539: 'Test2.P4' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I4.P4 { add => throw null; remove => throw null;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P4").WithArguments("Test2.P4").WithLocation(28, 28), // (8,32): warning CS0626: Method, operator, or accessor 'I2.P2.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event System.Action P2 = null; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P2").WithArguments("I2.P2.remove").WithLocation(8, 32), // (8,32): warning CS0067: The event 'I2.P2' is never used // extern event System.Action P2 = null; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P2").WithArguments("I2.P2").WithLocation(8, 32) ); } private void ValidateEventModifiers_17(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var p1 = GetSingleEvent(compilation1, "I1"); var test2P1 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I1.")).Single(); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.True(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test2P1, test2.FindImplementationForInterfaceMember(p1)); ValidateP1Accessor(p1.AddMethod, test2P1.AddMethod); ValidateP1Accessor(p1.RemoveMethod, test2P1.RemoveMethod); void ValidateP1Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p2 = GetSingleEvent(compilation1, "I2"); var test2P2 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); Assert.False(p2.IsAbstract); Assert.True(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.True(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Public, p2.DeclaredAccessibility); Assert.Same(p2, test1.FindImplementationForInterfaceMember(p2)); Assert.Same(test2P2, test2.FindImplementationForInterfaceMember(p2)); ValidateP2Accessor(p2.AddMethod, test2P2.AddMethod); ValidateP2Accessor(p2.RemoveMethod, test2P2.RemoveMethod); void ValidateP2Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.False(accessor.IsAbstract); Assert.True(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Same(accessor, test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p3 = GetSingleEvent(compilation1, "I3"); var test2P3 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I3.")).Single(); Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.False(p3.IsSealed); Assert.True(p3.IsStatic); Assert.True(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.AddMethod); ValidateP3Accessor(p3.RemoveMethod); void ValidateP3Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p4 = GetSingleEvent(compilation1, "I4"); Assert.False(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.False(p4.IsStatic); Assert.True(p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Private, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); Assert.Null(test2.FindImplementationForInterfaceMember(p4)); ValidateP4Accessor(p4.AddMethod); ValidateP4Accessor(p4.RemoveMethod); void ValidateP4Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } } [Fact] public void EventModifiers_18() { var source1 = @" public interface I1 { abstract event System.Action P1 {add => throw null; remove => throw null;} } public interface I2 { abstract private event System.Action P2 = null; } public interface I3 { static extern event System.Action P3; } public interface I4 { abstract static event System.Action P4 { add {throw null;} remove {throw null;}} } public interface I5 { override sealed event System.Action P5 { add {throw null;} remove {throw null;}} } class Test1 : I1, I2, I3, I4, I5 { } class Test2 : I1, I2, I3, I4, I5 { event System.Action I1.P1 { add {throw null;} remove {throw null;}} event System.Action I2.P2 { add {throw null;} remove {throw null;}} event System.Action I3.P3 { add {throw null;} remove {throw null;}} event System.Action I4.P4 { add {throw null;} remove {throw null;}} event System.Action I5.P5 { add {throw null;} remove {throw null;}} } "; ValidateEventModifiers_18(source1, // (4,37): error CS8712: 'I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action P1 {add => throw null; remove => throw null;} Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.P1").WithLocation(4, 37), // (8,42): error CS0068: 'I2.P2': instance event in interface cannot have initializer // abstract private event System.Action P2 = null; Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "P2").WithArguments("I2.P2").WithLocation(8, 42), // (8,42): error CS0621: 'I2.P2': virtual or abstract members cannot be private // abstract private event System.Action P2 = null; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P2").WithArguments("I2.P2").WithLocation(8, 42), // (16,44): error CS8712: 'I4.P4': abstract event cannot use event accessor syntax // abstract static event System.Action P4 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I4.P4").WithLocation(16, 44), // (16,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P4 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P4").WithArguments("abstract", "9.0", "preview").WithLocation(16, 41), // (20,41): error CS0106: The modifier 'override' is not valid for this item // override sealed event System.Action P5 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_BadMemberFlag, "P5").WithArguments("override").WithLocation(20, 41), // (23,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.P1").WithLocation(23, 15), // (23,19): error CS0535: 'Test1' does not implement interface member 'I2.P2' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I2.P2").WithLocation(23, 19), // (30,28): error CS0122: 'I2.P2' is inaccessible due to its protection level // event System.Action I2.P2 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I2.P2").WithLocation(30, 28), // (31,28): error CS0539: 'Test2.P3' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I3.P3 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P3").WithArguments("Test2.P3").WithLocation(31, 28), // (32,28): error CS0539: 'Test2.P4' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I4.P4 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P4").WithArguments("Test2.P4").WithLocation(32, 28), // (33,28): error CS0539: 'Test2.P5' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I5.P5 { add {throw null;} remove {throw null;}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P5").WithArguments("Test2.P5").WithLocation(33, 28), // (12,39): warning CS0626: Method, operator, or accessor 'I3.P3.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern event System.Action P3; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "P3").WithArguments("I3.P3.remove").WithLocation(12, 39), // (23,27): error CS0535: 'Test1' does not implement interface member 'I4.P4' // class Test1 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test1", "I4.P4").WithLocation(23, 27), // (27,27): error CS0535: 'Test2' does not implement interface member 'I4.P4' // class Test2 : I1, I2, I3, I4, I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test2", "I4.P4").WithLocation(27, 27), // (8,42): warning CS0067: The event 'I2.P2' is never used // abstract private event System.Action P2 = null; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P2").WithArguments("I2.P2").WithLocation(8, 42) ); } private void ValidateEventModifiers_18(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var p1 = GetSingleEvent(compilation1, "I1"); var test2P1 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I1.")).Single(); Assert.True(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); Assert.Same(test2P1, test2.FindImplementationForInterfaceMember(p1)); ValidateP1Accessor(p1.AddMethod, test2P1.AddMethod); ValidateP1Accessor(p1.RemoveMethod, test2P1.RemoveMethod); void ValidateP1Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p2 = GetSingleEvent(compilation1, "I2"); var test2P2 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); Assert.True(p2.IsAbstract); Assert.False(p2.IsVirtual); Assert.False(p2.IsSealed); Assert.False(p2.IsStatic); Assert.False(p2.IsExtern); Assert.False(p2.IsOverride); Assert.Equal(Accessibility.Private, p2.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p2)); Assert.Same(test2P2, test2.FindImplementationForInterfaceMember(p2)); ValidateP2Accessor(p2.AddMethod, test2P2.AddMethod); ValidateP2Accessor(p2.RemoveMethod, test2P2.RemoveMethod); void ValidateP2Accessor(MethodSymbol accessor, MethodSymbol implementation) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Private, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Same(implementation, test2.FindImplementationForInterfaceMember(accessor)); } var p3 = GetSingleEvent(compilation1, "I3"); var test2P3 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I3.")).Single(); Assert.False(p3.IsAbstract); Assert.False(p3.IsVirtual); Assert.False(p3.IsSealed); Assert.True(p3.IsStatic); Assert.True(p3.IsExtern); Assert.False(p3.IsOverride); Assert.Equal(Accessibility.Public, p3.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p3)); Assert.Null(test2.FindImplementationForInterfaceMember(p3)); ValidateP3Accessor(p3.AddMethod); ValidateP3Accessor(p3.RemoveMethod); void ValidateP3Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.True(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p4 = GetSingleEvent(compilation1, "I4"); var test2P4 = test2.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I4.")).Single(); Assert.True(p4.IsAbstract); Assert.False(p4.IsVirtual); Assert.False(p4.IsSealed); Assert.True(p4.IsStatic); Assert.False(p4.IsExtern); Assert.False(p4.IsOverride); Assert.Equal(Accessibility.Public, p4.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p4)); Assert.Null(test2.FindImplementationForInterfaceMember(p4)); ValidateP4Accessor(p4.AddMethod); ValidateP4Accessor(p4.RemoveMethod); void ValidateP4Accessor(MethodSymbol accessor) { Assert.True(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.True(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } var p5 = GetSingleEvent(compilation1, "I5"); Assert.False(p5.IsAbstract); Assert.False(p5.IsVirtual); Assert.False(p5.IsSealed); Assert.False(p5.IsStatic); Assert.False(p5.IsExtern); Assert.False(p5.IsOverride); Assert.Equal(Accessibility.Public, p5.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p5)); Assert.Null(test2.FindImplementationForInterfaceMember(p5)); ValidateP5Accessor(p5.AddMethod); ValidateP5Accessor(p5.RemoveMethod); void ValidateP5Accessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.False(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(Accessibility.Public, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); Assert.Null(test2.FindImplementationForInterfaceMember(accessor)); } } [Fact] public void EventModifiers_20() { var source1 = @" public interface I1 { internal event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } void M2() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidateEventModifiers_20(source1, source2, Accessibility.Internal); } private void ValidateEventModifiers_20(string source1, string source2, Accessibility accessibility) { var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Single(); var p1 = GetSingleEvent(i1); var p1add = p1.AddMethod; var p1remove = p1.RemoveMethod; ValidateEvent(p1); ValidateMethod(p1add); ValidateMethod(p1remove); Assert.Same(p1, test1.FindImplementationForInterfaceMember(p1)); Assert.Same(p1add, test1.FindImplementationForInterfaceMember(p1add)); Assert.Same(p1remove, test1.FindImplementationForInterfaceMember(p1remove)); } void ValidateEvent(EventSymbol p1) { Assert.False(p1.IsAbstract); Assert.True(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.False(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(accessibility, p1.DeclaredAccessibility); } void ValidateMethod(MethodSymbol m1) { Assert.False(m1.IsAbstract); Assert.True(m1.IsVirtual); Assert.True(m1.IsMetadataVirtual()); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(accessibility, m1.DeclaredAccessibility); } var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); { var i1 = compilation2.GetTypeByMetadataName("I1"); var p1 = GetSingleEvent(i1); ValidateEvent(p1); ValidateMethod(p1.AddMethod); ValidateMethod(p1.RemoveMethod); } var compilation3 = CreateCompilation(source2, new[] { compilation2.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation3.SourceModule); var compilation4 = CreateCompilation(source2, new[] { compilation2.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); Validate1(compilation4.SourceModule); } [Fact] public void EventModifiers_21() { var source1 = @" public interface I1 { private static event System.Action P1 { add => throw null; remove => throw null; } internal static event System.Action P2 { add => throw null; remove => throw null; } public static event System.Action P3 { add => throw null; remove => throw null; } static event System.Action P4 { add => throw null; remove => throw null; } } class Test1 { static void Main() { I1.P1 += null; I1.P1 -= null; I1.P2 += null; I1.P2 -= null; I1.P3 += null; I1.P3 -= null; I1.P4 += null; I1.P4 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (17,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(17, 12), // (18,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(18, 12) ); var source2 = @" class Test2 { static void Main() { I1.P1 += null; I1.P1 -= null; I1.P2 += null; I1.P2 -= null; I1.P3 += null; I1.P3 -= null; I1.P4 += null; I1.P4 -= null; } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(6, 12), // (7,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(7, 12), // (8,12): error CS0122: 'I1.P2' is inaccessible due to its protection level // I1.P2 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(8, 12), // (9,12): error CS0122: 'I1.P2' is inaccessible due to its protection level // I1.P2 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(9, 12) ); } [Fact] public void EventModifiers_22() { var source0 = @" public interface I1 { protected static event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } protected internal static event System.Action P2 { add { System.Console.WriteLine(""get_P2""); } remove { System.Console.WriteLine(""set_P2""); } } private protected static event System.Action P3 { add => System.Console.WriteLine(""get_P3""); remove => System.Console.WriteLine(""set_P3""); } } "; var source1 = @" class Test1 : I1 { static void Main() { I1.P1 += null; I1.P1 -= null; I1.P2 += null; I1.P2 -= null; I1.P3 += null; I1.P3 -= null; } } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 set_P2 get_P3 set_P3", symbolValidator: validate, verify: VerifyOnMonoOrCoreClr); validate(compilation1.SourceModule); var source2 = @" class Test1 { static void Main() { I1.P2 += null; I1.P2 -= null; } } "; var compilation2 = CreateCompilation(source0 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P2 set_P2", verify: VerifyOnMonoOrCoreClr); var compilation3 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); var source3 = @" class Test1 : I1 { static void Main() { I1.P1 += null; I1.P1 -= null; I1.P2 += null; I1.P2 -= null; } } "; var source4 = @" class Test1 { static void Main() { I1.P1 += null; I1.P1 -= null; I1.P2 += null; I1.P2 -= null; I1.P3 += null; I1.P3 -= null; } } "; foreach (var reference in new[] { compilation3.ToMetadataReference(), compilation3.EmitToImageReference() }) { var compilation4 = CreateCompilation(source3, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"get_P1 set_P1 get_P2 set_P2", verify: VerifyOnMonoOrCoreClr); var compilation5 = CreateCompilation(source4, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (6,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(6, 12), // (7,12): error CS0122: 'I1.P1' is inaccessible due to its protection level // I1.P1 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(7, 12), // (8,12): error CS0122: 'I1.P2' is inaccessible due to its protection level // I1.P2 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(8, 12), // (9,12): error CS0122: 'I1.P2' is inaccessible due to its protection level // I1.P2 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P2").WithArguments("I1.P2").WithLocation(9, 12), // (10,12): error CS0122: 'I1.P3' is inaccessible due to its protection level // I1.P3 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(10, 12), // (11,12): error CS0122: 'I1.P3' is inaccessible due to its protection level // I1.P3 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(11, 12) ); var compilation6 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (10,12): error CS0122: 'I1.P3' is inaccessible due to its protection level // I1.P3 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(10, 12), // (11,12): error CS0122: 'I1.P3' is inaccessible due to its protection level // I1.P3 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("I1.P3").WithLocation(11, 12) ); } void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = m.GlobalNamespace.GetTypeMember("I1"); foreach (var tuple in new[] { (name: "P1", access: Accessibility.Protected), (name: "P2", access: Accessibility.ProtectedOrInternal), (name: "P3", access: Accessibility.ProtectedAndInternal)}) { var p1 = i1.GetMember<EventSymbol>(tuple.name); Assert.False(p1.IsAbstract); Assert.False(p1.IsVirtual); Assert.False(p1.IsSealed); Assert.True(p1.IsStatic); Assert.False(p1.IsExtern); Assert.False(p1.IsOverride); Assert.Equal(tuple.access, p1.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(p1)); ValidateAccessor(p1.AddMethod); ValidateAccessor(p1.RemoveMethod); void ValidateAccessor(MethodSymbol accessor) { Assert.False(accessor.IsAbstract); Assert.False(accessor.IsVirtual); Assert.False(accessor.IsMetadataVirtual()); Assert.False(accessor.IsSealed); Assert.True(accessor.IsStatic); Assert.False(accessor.IsExtern); Assert.False(accessor.IsAsync); Assert.False(accessor.IsOverride); Assert.Equal(tuple.access, accessor.DeclaredAccessibility); Assert.Null(test1.FindImplementationForInterfaceMember(accessor)); } } } } [Fact] public void EventModifiers_23() { var source1 = @" public interface I1 { protected abstract event System.Action P1; sealed void Test() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11(source1, source2, Accessibility.Protected, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } [Fact] public void EventModifiers_24() { var source1 = @" public interface I1 { protected internal abstract event System.Action P1; sealed void Test() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11(source1, source2, Accessibility.ProtectedOrInternal, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } [Fact] public void EventModifiers_25() { var source1 = @" public interface I1 { private protected abstract event System.Action P1; sealed void Test() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.Test(); } public event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11(source1, source2, Accessibility.ProtectedAndInternal, new DiagnosticDescription[] { // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.remove'. 'Test1.P1.remove' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.remove", "Test1.P1.remove", "9.0", "10.0").WithLocation(2, 15), // (2,15): error CS8704: 'Test1' does not implement interface member 'I1.P1.add'. 'Test1.P1.add' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("Test1", "I1.P1.add", "Test1.P1.add", "9.0", "10.0").WithLocation(2, 15) }, // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 15) ); } [Fact] public void EventModifiers_26() { var source1 = @" public interface I1 { protected abstract event System.Action P1; public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } event System.Action I1.P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_03(source1, source2, TargetFramework.NetCoreApp); } [Fact] public void EventModifiers_27() { var source1 = @" public interface I1 { protected internal abstract event System.Action P1; public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } event System.Action I1.P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_03(source1, source2, TargetFramework.NetCoreApp); } [Fact] public void EventModifiers_28() { var source1 = @" public interface I1 { private protected abstract event System.Action P1; public static void CallP1(I1 x) { x.P1 += null; x.P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1.CallP1(new Test1()); } event System.Action I1.P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } } "; ValidateEventModifiers_11_03(source1, source2, TargetFramework.NetCoreApp, // (9,28): error CS0122: 'I1.P1' is inaccessible due to its protection level // event System.Action I1.P1 Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(9, 28) ); } [Fact] public void EventModifiers_29() { var source1 = @" public interface I1 { protected event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } void M2() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidateEventModifiers_20(source1, source2, Accessibility.Protected); } [Fact] public void EventModifiers_30() { var source1 = @" public interface I1 { protected internal event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } void M2() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidateEventModifiers_20(source1, source2, Accessibility.ProtectedOrInternal); } [Fact] public void EventModifiers_31() { var source1 = @" public interface I1 { private protected event System.Action P1 { add { System.Console.WriteLine(""get_P1""); } remove { System.Console.WriteLine(""set_P1""); } } void M2() { P1 += null; P1 -= null; } } "; var source2 = @" class Test1 : I1 { static void Main() { I1 x = new Test1(); x.M2(); } } "; ValidateEventModifiers_20(source1, source2, Accessibility.ProtectedAndInternal); } [Fact] public void NestedTypes_01() { var source1 = @" public interface I1 { interface T1 { void M1(); } class T2 {} struct T3 {} enum T4 { B } delegate void T5(); } class Test1 : I1.T1 { static void Main() { I1.T1 a = new Test1(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } public void M1() { System.Console.WriteLine(""M1""); } } "; ValidateNestedTypes_01(source1); } private void ValidateNestedTypes_01(string source1, Accessibility expected = Accessibility.Public, TargetFramework targetFramework = TargetFramework.Standard, bool execute = true, Verification verify = Verification.Passes) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: targetFramework); for (int i = 1; i <= 5; i++) { Assert.Equal(expected, compilation1.GetMember("I1.T" + i).DeclaredAccessibility); } CompileAndVerify(compilation1, expectedOutput: !execute ? null : @"M1 I1+T2 I1+T3 B I1+T5", verify: verify); } [Fact] public void NestedTypes_02() { var source1 = @" public interface I1 { interface T1 { void M1(); } class T2 {} struct T3 {} enum T4 { B } } class Test1 : I1.T1 { static void Main() { I1.T1 a = new Test1(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); } public void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); for (int i = 1; i <= 4; i++) { Assert.Equal(Accessibility.Public, compilation1.GetMember("I1.T" + i).DeclaredAccessibility); } compilation1.VerifyDiagnostics( // (4,15): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // interface T1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T1").WithArguments("default interface implementation", "8.0").WithLocation(4, 15), // (9,11): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // class T2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T2").WithArguments("default interface implementation", "8.0").WithLocation(9, 11), // (12,12): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // struct T3 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T3").WithArguments("default interface implementation", "8.0").WithLocation(12, 12), // (15,10): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // enum T4 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T4").WithArguments("default interface implementation", "8.0").WithLocation(15, 10) ); } [Fact] public void NestedTypes_03() { var source1 = @" public interface I1 { public interface T1 { void M1(); } public class T2 {} public struct T3 {} public enum T4 { B } public delegate void T5(); } class Test1 : I1.T1 { static void Main() { I1.T1 a = new Test1(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } public void M1() { System.Console.WriteLine(""M1""); } } "; ValidateNestedTypes_01(source1); } [Fact] public void NestedTypes_04() { var source0 = @" public interface I1 { protected interface T1 { void M1(); } protected class T2 {} protected struct T3 {} protected enum T4 { B } protected delegate void T5(); } "; var source1 = @" class Test1 : I1 { static void Main() { I1.T1 a = new Test2(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } class Test2 : I1.T1 { public void M1() { System.Console.WriteLine(""M1""); } } } "; ValidateNestedTypes_01(source0 + source1, Accessibility.Protected, targetFramework: TargetFramework.NetCoreApp, execute: ExecutionConditionUtil.IsMonoOrCoreClr, verify: VerifyOnMonoOrCoreClr); var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); for (int i = 1; i <= 5; i++) { Assert.Equal(Accessibility.Protected, compilation1.GetMember("I1.T" + i).DeclaredAccessibility); } compilation1.VerifyDiagnostics( // (4,25): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected interface T1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T1").WithLocation(4, 25), // (9,21): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected class T2 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T2").WithLocation(9, 21), // (12,22): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected struct T3 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T3").WithLocation(12, 22), // (15,20): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected enum T4 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T4").WithLocation(15, 20), // (20,29): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected delegate void T5(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T5").WithLocation(20, 29) ); var source2 = @" class Test1 { static void Main() { I1.T1 a = new Test2(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } class Test2 : I1.T1 { public void M1() { System.Console.WriteLine(""M1""); } } } "; var compilation2 = CreateCompilation(source2 + source0, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var expected = new DiagnosticDescription[] { // (6,12): error CS0122: 'I1.T1' is inaccessible due to its protection level // I1.T1 a = new Test2(); Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(6, 12), // (7,11): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // a.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(7, 11), // (8,41): error CS0122: 'I1.T2' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T2()); Diagnostic(ErrorCode.ERR_BadAccess, "T2").WithArguments("I1.T2").WithLocation(8, 41), // (9,41): error CS0122: 'I1.T3' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T3()); Diagnostic(ErrorCode.ERR_BadAccess, "T3").WithArguments("I1.T3").WithLocation(9, 41), // (10,37): error CS0122: 'I1.T4' is inaccessible due to its protection level // System.Console.WriteLine(I1.T4.B); Diagnostic(ErrorCode.ERR_BadAccess, "T4").WithArguments("I1.T4").WithLocation(10, 37), // (11,41): error CS0122: 'I1.T5' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "T5").WithArguments("I1.T5").WithLocation(11, 41), // (11,46): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(11, 46), // (14,22): error CS0122: 'I1.T1' is inaccessible due to its protection level // class Test2 : I1.T1 Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(14, 22) }; compilation2.VerifyDiagnostics(expected); var compilation3 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); foreach (var reference in new[] { compilation3.ToMetadataReference(), compilation3.EmitToImageReference() }) { var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics(); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 I1+T2 I1+T3 B I1+T5", verify: VerifyOnMonoOrCoreClr); var compilation5 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics(expected); } } [Fact] public void NestedTypes_05() { var source0 = @" public interface I1 { protected internal interface T1 { void M1(); } protected internal class T2 {} protected internal struct T3 {} protected internal enum T4 { B } protected internal delegate void T5(); } "; var source1 = @" class Test1 : I1 { static void Main() { I1.T1 a = new Test2(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } class Test2 : I1.T1 { public void M1() { System.Console.WriteLine(""M1""); } } } "; var source2 = @" class Test1 { static void Main() { I1.T1 a = new Test2(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } class Test2 : I1.T1 { public void M1() { System.Console.WriteLine(""M1""); } } } "; ValidateNestedTypes_01(source0 + source1, Accessibility.ProtectedOrInternal, targetFramework: TargetFramework.NetCoreApp, execute: ExecutionConditionUtil.IsMonoOrCoreClr, verify: VerifyOnMonoOrCoreClr); ValidateNestedTypes_01(source0 + source2, Accessibility.ProtectedOrInternal, targetFramework: TargetFramework.NetCoreApp, execute: ExecutionConditionUtil.IsMonoOrCoreClr, verify: VerifyOnMonoOrCoreClr); var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); for (int i = 1; i <= 5; i++) { Assert.Equal(Accessibility.ProtectedOrInternal, compilation1.GetMember("I1.T" + i).DeclaredAccessibility); } compilation1.VerifyDiagnostics( // (4,34): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal interface T1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T1").WithLocation(4, 34), // (9,30): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal class T2 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T2").WithLocation(9, 30), // (12,31): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal struct T3 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T3").WithLocation(12, 31), // (15,29): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal enum T4 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T4").WithLocation(15, 29), // (20,38): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // protected internal delegate void T5(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T5").WithLocation(20, 38) ); var compilation3 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); foreach (var reference in new[] { compilation3.ToMetadataReference(), compilation3.EmitToImageReference() }) { var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics(); CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 I1+T2 I1+T3 B I1+T5", verify: VerifyOnMonoOrCoreClr); var compilation5 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (6,12): error CS0122: 'I1.T1' is inaccessible due to its protection level // I1.T1 a = new Test2(); Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(6, 12), // (7,11): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // a.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(7, 11), // (8,41): error CS0122: 'I1.T2' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T2()); Diagnostic(ErrorCode.ERR_BadAccess, "T2").WithArguments("I1.T2").WithLocation(8, 41), // (9,41): error CS0122: 'I1.T3' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T3()); Diagnostic(ErrorCode.ERR_BadAccess, "T3").WithArguments("I1.T3").WithLocation(9, 41), // (10,37): error CS0122: 'I1.T4' is inaccessible due to its protection level // System.Console.WriteLine(I1.T4.B); Diagnostic(ErrorCode.ERR_BadAccess, "T4").WithArguments("I1.T4").WithLocation(10, 37), // (11,41): error CS0122: 'I1.T5' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "T5").WithArguments("I1.T5").WithLocation(11, 41), // (11,46): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(11, 46), // (14,22): error CS0122: 'I1.T1' is inaccessible due to its protection level // class Test2 : I1.T1 Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(14, 22) ); } } [Fact] public void NestedTypes_06() { var source1 = @" public interface I1 { internal interface T1 { void M1(); } internal class T2 {} internal struct T3 {} internal enum T4 { B } internal delegate void T5(); } "; var source2 = @" class Test1 : I1.T1 { static void Main() { I1.T1 a = new Test1(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } public void M1() { System.Console.WriteLine(""M1""); } } "; ValidateNestedTypes_01(source1 + source2, Accessibility.Internal); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe); var expected = new[] { // (2,18): error CS0122: 'I1.T1' is inaccessible due to its protection level // class Test1 : I1.T1 Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(2, 18), // (6,12): error CS0122: 'I1.T1' is inaccessible due to its protection level // I1.T1 a = new Test1(); Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(6, 12), // (7,11): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // a.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(7, 11), // (8,41): error CS0122: 'I1.T2' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T2()); Diagnostic(ErrorCode.ERR_BadAccess, "T2").WithArguments("I1.T2").WithLocation(8, 41), // (9,41): error CS0122: 'I1.T3' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T3()); Diagnostic(ErrorCode.ERR_BadAccess, "T3").WithArguments("I1.T3").WithLocation(9, 41), // (10,37): error CS0122: 'I1.T4' is inaccessible due to its protection level // System.Console.WriteLine(I1.T4.B); Diagnostic(ErrorCode.ERR_BadAccess, "T4").WithArguments("I1.T4").WithLocation(10, 37), // (11,41): error CS0122: 'I1.T5' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "T5").WithArguments("I1.T5").WithLocation(11, 41), // (11,46): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(11, 46) }; compilation2.VerifyDiagnostics(expected); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe); compilation3.VerifyDiagnostics(expected); } [Fact] public void NestedTypes_07() { var source1 = @" public interface I1 { private interface T1 { void M1(); } private class T2 {} private struct T3 {} private enum T4 { B } private delegate void T5(); class Test1 : I1.T1 { static void Main() { I1.T1 a = new Test1(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } public void M1() { System.Console.WriteLine(""M1""); } } } "; ValidateNestedTypes_01(source1, Accessibility.Private); } [Fact] public void NestedTypes_08() { var source1 = @" public interface I1 { private interface T1 { void M1(); } private class T2 {} private struct T3 {} private enum T4 { B } } class Test1 : I1.T1 { static void Main() { I1.T1 a = new Test1(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); } public void M1() { System.Console.WriteLine(""M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (21,18): error CS0122: 'I1.T1' is inaccessible due to its protection level // class Test1 : I1.T1 Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(21, 18), // (25,12): error CS0122: 'I1.T1' is inaccessible due to its protection level // I1.T1 a = new Test1(); Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(25, 12), // (26,11): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // a.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(26, 11), // (27,41): error CS0122: 'I1.T2' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T2()); Diagnostic(ErrorCode.ERR_BadAccess, "T2").WithArguments("I1.T2").WithLocation(27, 41), // (28,41): error CS0122: 'I1.T3' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T3()); Diagnostic(ErrorCode.ERR_BadAccess, "T3").WithArguments("I1.T3").WithLocation(28, 41), // (29,37): error CS0122: 'I1.T4' is inaccessible due to its protection level // System.Console.WriteLine(I1.T4.B); Diagnostic(ErrorCode.ERR_BadAccess, "T4").WithArguments("I1.T4").WithLocation(29, 37) ); } [Fact] public void NestedTypes_09() { var source0 = @" public interface I1 { private protected interface T1 { void M1(); } private protected class T2 {} private protected struct T3 {} private protected enum T4 { B } private protected delegate void T5(); } "; var source1 = @" class Test1 : I1 { static void Main() { I1.T1 a = new Test2(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } class Test2 : I1.T1 { public void M1() { System.Console.WriteLine(""M1""); } } } "; var source2 = @" class Test1 { static void Main() { I1.T1 a = new Test2(); a.M1(); System.Console.WriteLine(new I1.T2()); System.Console.WriteLine(new I1.T3()); System.Console.WriteLine(I1.T4.B); System.Console.WriteLine(new I1.T5(a.M1)); } class Test2 : I1.T1 { public void M1() { System.Console.WriteLine(""M1""); } } } "; ValidateNestedTypes_01(source0 + source1, Accessibility.ProtectedAndInternal, targetFramework: TargetFramework.NetCoreApp, execute: ExecutionConditionUtil.IsMonoOrCoreClr, verify: VerifyOnMonoOrCoreClr); var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); for (int i = 1; i <= 5; i++) { Assert.Equal(Accessibility.ProtectedAndInternal, compilation1.GetMember("I1.T" + i).DeclaredAccessibility); } compilation1.VerifyDiagnostics( // (4,33): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected interface T1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T1").WithLocation(4, 33), // (9,29): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected class T2 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T2").WithLocation(9, 29), // (12,30): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected struct T3 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T3").WithLocation(12, 30), // (15,28): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected enum T4 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T4").WithLocation(15, 28), // (20,37): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // private protected delegate void T5(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "T5").WithLocation(20, 37) ); var compilation2 = CreateCompilation(source2 + source0, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var expected = new DiagnosticDescription[] { // (6,12): error CS0122: 'I1.T1' is inaccessible due to its protection level // I1.T1 a = new Test2(); Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(6, 12), // (7,11): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // a.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(7, 11), // (8,41): error CS0122: 'I1.T2' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T2()); Diagnostic(ErrorCode.ERR_BadAccess, "T2").WithArguments("I1.T2").WithLocation(8, 41), // (9,41): error CS0122: 'I1.T3' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T3()); Diagnostic(ErrorCode.ERR_BadAccess, "T3").WithArguments("I1.T3").WithLocation(9, 41), // (10,37): error CS0122: 'I1.T4' is inaccessible due to its protection level // System.Console.WriteLine(I1.T4.B); Diagnostic(ErrorCode.ERR_BadAccess, "T4").WithArguments("I1.T4").WithLocation(10, 37), // (11,41): error CS0122: 'I1.T5' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "T5").WithArguments("I1.T5").WithLocation(11, 41), // (11,46): error CS0122: 'I1.T1.M1()' is inaccessible due to its protection level // System.Console.WriteLine(new I1.T5(a.M1)); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1.T1.M1()").WithLocation(11, 46), // (14,22): error CS0122: 'I1.T1' is inaccessible due to its protection level // class Test2 : I1.T1 Diagnostic(ErrorCode.ERR_BadAccess, "T1").WithArguments("I1.T1").WithLocation(14, 22) }; compilation2.VerifyDiagnostics(expected); var compilation3 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); foreach (var reference in new[] { compilation3.ToMetadataReference(), compilation3.EmitToImageReference() }) { var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics(expected); var compilation5 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics(expected); } } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_10() { var source1 = @" interface I1 { protected interface I2 { } } class C1 { protected interface I2 { } } interface I3 : I1, I1.I2 { private void M1(I1.I2 x) { } } interface I4 : I1, I2 { I2 MI4(); } interface I5 : I1.I2, I1 { private void M1(I1.I2 x) { } } interface I6 : I2, I1 { I2 MI6(); } class C3 : I1, I1.I2 { private void M1(I1.I2 x) { } } class C4 : I1, I2 { void MC4(I2 x) { } } class C5 : I1.I2, I1 { private void M1(I1.I2 x) { } } class C6 : I2, I1 { void MC6(I2 x) { } } class C33 : C1, C1.I2 { protected void M1(C1.I2 x) { } } class C44 : C1, I2 { void M1(I2 x) { } } interface I7 : I8 { public interface I8 : I7 { } } class C7 : I8 { public interface I8 { } } interface I9 : I9.I10 { public interface I10 : I9 { } } interface I11 { public interface I12 : I13 { } public interface I13 { } public interface I14 : I11.I13 { } } class C11 { public interface I12 : I13 { } public interface I13 { } public interface I14 : I11.I13 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (16,23): error CS0122: 'I1.I2' is inaccessible due to its protection level // interface I3 : I1, I1.I2 Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1.I2").WithLocation(16, 23), // (21,20): error CS0246: The type or namespace name 'I2' could not be found (are you missing a using directive or an assembly reference?) // interface I4 : I1, I2 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("I2").WithLocation(21, 20), // (23,8): error CS0050: Inconsistent accessibility: return type 'I1.I2' is less accessible than method 'I4.MI4()' // I2 MI4(); Diagnostic(ErrorCode.ERR_BadVisReturnType, "MI4").WithArguments("I4.MI4()", "I1.I2").WithLocation(23, 8), // (26,19): error CS0122: 'I1.I2' is inaccessible due to its protection level // interface I5 : I1.I2, I1 Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1.I2").WithLocation(26, 19), // (31,16): error CS0246: The type or namespace name 'I2' could not be found (are you missing a using directive or an assembly reference?) // interface I6 : I2, I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("I2").WithLocation(31, 16), // (33,8): error CS0050: Inconsistent accessibility: return type 'I1.I2' is less accessible than method 'I6.MI6()' // I2 MI6(); Diagnostic(ErrorCode.ERR_BadVisReturnType, "MI6").WithArguments("I6.MI6()", "I1.I2").WithLocation(33, 8), // (36,19): error CS0122: 'I1.I2' is inaccessible due to its protection level // class C3 : I1, I1.I2 Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1.I2").WithLocation(36, 19), // (41,16): error CS0246: The type or namespace name 'I2' could not be found (are you missing a using directive or an assembly reference?) // class C4 : I1, I2 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("I2").WithLocation(41, 16), // (43,14): error CS0246: The type or namespace name 'I2' could not be found (are you missing a using directive or an assembly reference?) // void MC4(I2 x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("I2").WithLocation(43, 14), // (46,15): error CS0122: 'I1.I2' is inaccessible due to its protection level // class C5 : I1.I2, I1 Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("I1.I2").WithLocation(46, 15), // (51,12): error CS0246: The type or namespace name 'I2' could not be found (are you missing a using directive or an assembly reference?) // class C6 : I2, I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("I2").WithLocation(51, 12), // (53,14): error CS0246: The type or namespace name 'I2' could not be found (are you missing a using directive or an assembly reference?) // void MC6(I2 x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("I2").WithLocation(53, 14), // (56,20): error CS0122: 'C1.I2' is inaccessible due to its protection level // class C33 : C1, C1.I2 Diagnostic(ErrorCode.ERR_BadAccess, "I2").WithArguments("C1.I2").WithLocation(56, 20), // (61,17): error CS0246: The type or namespace name 'I2' could not be found (are you missing a using directive or an assembly reference?) // class C44 : C1, I2 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("I2").WithLocation(61, 17), // (66,16): error CS0246: The type or namespace name 'I8' could not be found (are you missing a using directive or an assembly reference?) // interface I7 : I8 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I8").WithArguments("I8").WithLocation(66, 16), // (73,12): error CS0246: The type or namespace name 'I8' could not be found (are you missing a using directive or an assembly reference?) // class C7 : I8 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I8").WithArguments("I8").WithLocation(73, 12), // (80,11): error CS0529: Inherited interface 'I9.I10' causes a cycle in the interface hierarchy of 'I9' // interface I9 : I9.I10 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I9").WithArguments("I9", "I9.I10").WithLocation(80, 11), // (82,22): error CS0529: Inherited interface 'I9' causes a cycle in the interface hierarchy of 'I9.I10' // public interface I10 : I9 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I10").WithArguments("I9.I10", "I9").WithLocation(82, 22) ); } [Fact] [WorkItem(38735, "https://github.com/dotnet/roslyn/issues/38735")] public void NestedTypes_52() { var source1 = @" interface I1 : IA<int>.NF { } interface IQ<T> { } interface IA<T> : IB<IQ<T>> { } interface IB<T> : IA<IQ<T>> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (2,24): error CS0426: The type name 'NF' does not exist in the type 'IA<int>' // interface I1 : IA<int>.NF { } Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "NF").WithArguments("NF", "IA<int>").WithLocation(2, 24), // (6,11): error CS0529: Inherited interface 'IB<IQ<T>>' causes a cycle in the interface hierarchy of 'IA<T>' // interface IA<T> : IB<IQ<T>> { } Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IA").WithArguments("IA<T>", "IB<IQ<T>>").WithLocation(6, 11), // (8,11): error CS0529: Inherited interface 'IA<IQ<T>>' causes a cycle in the interface hierarchy of 'IB<T>' // interface IB<T> : IA<IQ<T>> { } Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IB").WithArguments("IB<T>", "IA<IQ<T>>").WithLocation(8, 11) ); } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void MethodImplementationInDerived_01() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I5 : I4 { } public interface I1 : I2, I5 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source2 = @" class Test1 : I1 { static void Main() { I2 i2 = new Test1(); i2.M1(); I4 i4 = new Test1(); i4.M1(); } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); } private static void ValidateMethodImplementationInDerived_01(ModuleSymbol m) { ValidateMethodImplementationInDerived_01(m, i4M1IsAbstract: false); } private static void ValidateMethodImplementationInDerived_01(ModuleSymbol m, bool i4M1IsAbstract) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var i1i2m1 = i1.GetMember<MethodSymbol>("I2.M1"); var i1i4m1 = i1.GetMember<MethodSymbol>("I4.M1"); var i2 = i1.AllInterfacesNoUseSiteDiagnostics.Where(i => i.Name == "I2").Single(); var i2m1 = i2.GetMembers().OfType<MethodSymbol>().Single(); var i4 = i1.AllInterfacesNoUseSiteDiagnostics.Where(i => i.Name == "I4").Single(); var i4m1 = i4.GetMembers().OfType<MethodSymbol>().Single(); var i3 = i1.ContainingNamespace.GetTypeMember("I3"); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); ValidateExplicitImplementation(i1i2m1); ValidateExplicitImplementation(i1i4m1, i4M1IsAbstract); Assert.Null(test1.FindImplementationForInterfaceMember(i1i2m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1i4m1)); Assert.Same(i1i2m1, test1.FindImplementationForInterfaceMember(i2m1)); Assert.Same(i4M1IsAbstract ? null : i1i4m1, test1.FindImplementationForInterfaceMember(i4m1)); Assert.Null(i1.FindImplementationForInterfaceMember(i1i2m1)); Assert.Null(i1.FindImplementationForInterfaceMember(i1i4m1)); Assert.Same(i1i2m1, i1.FindImplementationForInterfaceMember(i2m1)); Assert.Same(i4M1IsAbstract ? null : i1i4m1, i1.FindImplementationForInterfaceMember(i4m1)); Assert.Null(i2.FindImplementationForInterfaceMember(i2m1)); Assert.Null(i4.FindImplementationForInterfaceMember(i4m1)); Assert.Same(i1i2m1, i3.FindImplementationForInterfaceMember(i2m1)); Assert.Same(i4M1IsAbstract ? null : i1i4m1, i3.FindImplementationForInterfaceMember(i4m1)); } private static void ValidateExplicitImplementation(MethodSymbol m1, bool isAbstract = false) { Assert.True(m1.IsMetadataVirtual()); Assert.True(m1.IsMetadataFinal); Assert.False(m1.IsMetadataNewSlot()); Assert.Equal(isAbstract, m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.Equal(isAbstract, m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); if (m1.ContainingModule is PEModuleSymbol peModule) { int rva; peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)m1.OriginalDefinition).Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); } } [Fact] public void MethodImplementationInDerived_02() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I1 : I2, I4 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // void I2.M1() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M1").WithArguments("default interface implementation", "8.0").WithLocation(14, 13), // (18,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // void I4.M1() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M1").WithArguments("default interface implementation", "8.0").WithLocation(18, 13) ); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); var source2 = @" public interface I3 : I1 { } class Test1 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (6,15): error CS8506: 'I1.I2.M1()' cannot implement interface member 'I2.M1()' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1()", "I2.M1()", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15), // (6,15): error CS8506: 'I1.I4.M1()' cannot implement interface member 'I4.M1()' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1()", "I4.M1()", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15) ); ValidateMethodImplementationInDerived_01(compilation2.SourceModule); } [Fact] public void MethodImplementationInDerived_03() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I1 : I2, I4 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,13): error CS8501: Target runtime doesn't support default interface implementation. // void I2.M1() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(14, 13), // (18,13): error CS8501: Target runtime doesn't support default interface implementation. // void I4.M1() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(18, 13) ); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); var source2 = @" public interface I3 : I1 { } class Test1 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (6,15): error CS8502: 'I1.I2.M1()' cannot implement interface member 'I2.M1()' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1()", "I2.M1()", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I4.M1()' cannot implement interface member 'I4.M1()' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1()", "I4.M1()", "Test1").WithLocation(6, 15) ); } [Fact] public void MethodImplementationInDerived_04() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I1 : I2, I4 { void I2.M1(); void I4.M1(); } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (15,13): error CS0501: 'I1.I4.M1()' must declare a body because it is not marked abstract, extern, or partial // void I4.M1(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M1").WithArguments("I1.I4.M1()").WithLocation(15, 13), // (14,13): error CS0501: 'I1.I2.M1()' must declare a body because it is not marked abstract, extern, or partial // void I2.M1(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M1").WithArguments("I1.I2.M1()").WithLocation(14, 13) ); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); } [Fact] public void MethodImplementationInDerived_05() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I1 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I2.M1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (18,10): error CS0540: 'I1.I4.M1()': containing type does not implement interface 'I4' // void I4.M1() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I4").WithArguments("I1.I4.M1()", "I4").WithLocation(18, 10), // (14,10): error CS0540: 'I1.I2.M1()': containing type does not implement interface 'I2' // void I2.M1() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.I2.M1()", "I2").WithLocation(14, 10) ); } [Fact] public void MethodImplementationInDerived_06() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I1 : I2, I4 { public static void I2.M1() { System.Console.WriteLine(""I2.M1""); } internal virtual void I4.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,27): error CS0106: The modifier 'static' is not valid for this item // public static void I2.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("static").WithLocation(14, 27), // (14,27): error CS0106: The modifier 'public' is not valid for this item // public static void I2.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("public").WithLocation(14, 27), // (18,30): error CS0106: The modifier 'internal' is not valid for this item // internal virtual void I4.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("internal").WithLocation(18, 30), // (18,30): error CS0106: The modifier 'virtual' is not valid for this item // internal virtual void I4.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("virtual").WithLocation(18, 30) ); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); } [Fact] public void MethodImplementationInDerived_07() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I1 : I2, I4 { private sealed void I2.M1() { System.Console.WriteLine(""I2.M1""); } protected abstract void I4.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,28): error CS0106: The modifier 'sealed' is not valid for this item // private sealed void I2.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("sealed").WithLocation(14, 28), // (14,28): error CS0106: The modifier 'private' is not valid for this item // private sealed void I2.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("private").WithLocation(14, 28), // (18,32): error CS0106: The modifier 'protected' is not valid for this item // protected abstract void I4.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected").WithLocation(18, 32), // (18,32): error CS0500: 'I1.I4.M1()' cannot declare a body because it is marked abstract // protected abstract void I4.M1() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M1").WithArguments("I1.I4.M1()").WithLocation(18, 32), // (28,15): error CS0535: 'Test1' does not implement interface member 'I4.M1()' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I4.M1()").WithLocation(28, 15) ); ValidateMethodImplementationInDerived_01(compilation1.SourceModule, i4M1IsAbstract: true); } [Fact] public void MethodImplementationInDerived_08() { var source1 = @" public interface I2 { void M1(); } public interface I4 { void M1(); } public interface I1 : I2, I4 { private protected void I2.M1() { System.Console.WriteLine(""I2.M1""); } internal protected override void I4.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,31): error CS0106: The modifier 'private protected' is not valid for this item // private protected void I2.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("private protected").WithLocation(14, 31), // (18,41): error CS0106: The modifier 'protected internal' is not valid for this item // internal protected override void I4.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected internal").WithLocation(18, 41), // (18,41): error CS0106: The modifier 'override' is not valid for this item // internal protected override void I4.M1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("override").WithLocation(18, 41) ); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); } [Fact] public void MethodImplementationInDerived_09() { var source1 = @" public interface I2 { void M1(); } public interface I1 : I2 { extern void I2.M1(); } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (9,20): warning CS0626: Method, operator, or accessor 'I1.I2.M1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void I2.M1(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M1").WithArguments("I1.I2.M1()").WithLocation(9, 20) ); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var i1i2m1 = i1.GetMember<MethodSymbol>("I2.M1"); var i2 = i1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I2").Single(); var i2m1 = i2.GetMembers().OfType<MethodSymbol>().Single(); var i3 = i1.ContainingNamespace.GetTypeMember("I3"); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); ValidateExplicitExternImplementation(i1i2m1); Assert.Null(test1.FindImplementationForInterfaceMember(i1i2m1)); Assert.Same(i1i2m1, test1.FindImplementationForInterfaceMember(i2m1)); Assert.Null(i1.FindImplementationForInterfaceMember(i1i2m1)); Assert.Same(i1i2m1, i1.FindImplementationForInterfaceMember(i2m1)); Assert.Null(i2.FindImplementationForInterfaceMember(i2m1)); Assert.Same(i1i2m1, i3.FindImplementationForInterfaceMember(i2m1)); } CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (9,20): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // extern void I2.M1(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M1").WithArguments("default interface implementation", "8.0").WithLocation(9, 20), // (9,20): warning CS0626: Method, operator, or accessor 'I1.I2.M1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void I2.M1(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M1").WithArguments("I1.I2.M1()").WithLocation(9, 20) ); Validate1(compilation2.SourceModule); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (9,20): error CS8501: Target runtime doesn't support default interface implementation. // extern void I2.M1(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(9, 20), // (9,20): warning CS0626: Method, operator, or accessor 'I1.I2.M1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void I2.M1(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M1").WithArguments("I1.I2.M1()").WithLocation(9, 20) ); Validate1(compilation3.SourceModule); var source2 = @" public interface I2 { void M1(); } public interface I1 : I2 { extern void I2.M1() {} } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation4 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics( // (9,20): error CS0179: 'I1.I2.M1()' cannot be extern and declare a body // extern void I2.M1() Diagnostic(ErrorCode.ERR_ExternHasBody, "M1").WithArguments("I1.I2.M1()").WithLocation(9, 20) ); Validate1(compilation4.SourceModule); } private static void ValidateExplicitExternImplementation(MethodSymbol m1) { Assert.True(m1.IsMetadataVirtual()); Assert.True(m1.IsMetadataFinal); Assert.False(m1.IsMetadataNewSlot()); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.NotEqual(m1.OriginalDefinition is PEMethodSymbol, m1.IsExtern); Assert.False(m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); if (m1.ContainingModule is PEModuleSymbol peModule) { int rva; peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)m1).Handle, out _, out _, out _, out rva); Assert.Equal(0, rva); } } [Fact] public void MethodImplementationInDerived_10() { var source1 = @" using System.Threading.Tasks; public interface I2 { Task M1(); } public interface I1 : I2 { async Task I2.M1() { await Task.Factory.StartNew(() => System.Console.WriteLine(""I2.M1"")); } } public interface I3 : I1 { } class Test1 : I1 { static void Main() { I2 i2 = new Test1(); i2.M1().Wait(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var i1i2m1 = i1.GetMember<MethodSymbol>("I2.M1"); var i2 = i1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I2").Single(); var i2m1 = i2.GetMembers().OfType<MethodSymbol>().Single(); var i3 = i1.ContainingNamespace.GetTypeMember("I3"); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); Validate2(i1i2m1); Assert.Null(test1.FindImplementationForInterfaceMember(i1i2m1)); Assert.Equal("System.Threading.Tasks.Task I1.I2.M1()", test1.FindImplementationForInterfaceMember(i2m1).ToTestDisplayString()); Assert.Null(i1.FindImplementationForInterfaceMember(i1i2m1)); Assert.Equal("System.Threading.Tasks.Task I1.I2.M1()", i1.FindImplementationForInterfaceMember(i2m1).ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i2m1)); Assert.Equal("System.Threading.Tasks.Task I1.I2.M1()", i3.FindImplementationForInterfaceMember(i2m1).ToTestDisplayString()); } void Validate2(MethodSymbol m1) { Assert.True(m1.IsMetadataVirtual()); Assert.True(m1.IsMetadataFinal); Assert.False(m1.IsMetadataNewSlot()); Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.NotEqual(m1 is PEMethodSymbol, m1.IsAsync); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); if (m1.ContainingModule is PEModuleSymbol peModule) { int rva; peModule.Module.GetMethodDefPropsOrThrow(((PEMethodSymbol)m1).Handle, out _, out _, out _, out rva); Assert.NotEqual(0, rva); } } CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "I2.M1", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void MethodImplementationInDerived_11() { var source1 = @" public interface I2 { internal void M1(); } public interface I4 { internal void M1(); } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { i2.M1(); i4.M1(); } } "; var source2 = @" public interface I1 : I2, I5 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { TestHelper.Test(new Test1(), new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); var compilation2 = CreateCompilation(source3, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); var compilation3 = CreateCompilation(source3, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); var compilation5 = CreateCompilation(source2 + source3, new[] { compilation4.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics( // (8,13): error CS0122: 'I4.M1()' is inaccessible due to its protection level // void I4.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I4.M1()").WithLocation(8, 13), // (4,13): error CS0122: 'I2.M1()' is inaccessible due to its protection level // void I2.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1()").WithLocation(4, 13) ); var compilation6 = CreateCompilation(source2 + source3, new[] { compilation4.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation6.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation6.SourceModule); compilation6.VerifyDiagnostics( // (8,13): error CS0122: 'I4.M1()' is inaccessible due to its protection level // void I4.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I4.M1()").WithLocation(8, 13), // (4,13): error CS0122: 'I2.M1()' is inaccessible due to its protection level // void I2.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1()").WithLocation(4, 13) ); } [Fact] [WorkItem(20083, "https://github.com/dotnet/roslyn/issues/20083")] public void MethodImplementationInDerived_12() { var source1 = @" public interface I1 { void M1(){ System.Console.WriteLine(""Unexpected!!!""); } } public interface I2 : I1 { void I1.M1() { System.Console.WriteLine(""I2.I1.M1""); } } public interface I3 : I1 { void I1.M1() { System.Console.WriteLine(""I3.I1.M1""); } } public interface I4 : I1 { void I1.M1() { System.Console.WriteLine(""I4.I1.M1""); } } public interface I5 : I2, I3 { void I1.M1() { System.Console.WriteLine(""I5.I1.M1""); } } public interface I6 : I1, I2, I3, I5 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = i1.GetMember<MethodSymbol>("M1"); var i2 = FindType(m, "I2"); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); var i5 = FindType(m, "I5"); var i5m1 = i5.GetMember<MethodSymbol>("I1.M1"); var i6 = FindType(m, "I6"); ValidateExplicitImplementation(i2m1); ValidateExplicitImplementation(i5m1); Assert.Same(i1m1, i1.FindImplementationForInterfaceMember(i1m1)); Assert.Same(i2m1, i2.FindImplementationForInterfaceMember(i1m1)); Assert.Same(i5m1, i5.FindImplementationForInterfaceMember(i1m1)); Assert.Same(i5m1, i6.FindImplementationForInterfaceMember(i1m1)); } CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var refs1 = new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }; var source2 = @" public interface I7 : I2, I3 {} public interface I8 : I1, I2, I3, I5, I4 {} "; var source3 = @" class Test1 : I2, I3 {} class Test2 : I7 {} class Test3 : I1, I2, I3, I4 {} class Test4 : I1, I2, I3, I5, I4 {} class Test5 : I8 {} "; var source4 = @" class Test5 : I2 {} class Test6 : I1, I2, I3, I5 {} class Test7 : I6 { static void Main() { I1 i1 = new Test5(); i1.M1(); i1 = new Test6(); i1.M1(); i1 = new Test7(); i1.M1(); } } "; var source5 = @" class Test8 : I2, I3 { void I1.M1() { System.Console.WriteLine(""Test8.I1.M1""); } static void Main() { I1 i1 = new Test8(); i1.M1(); i1 = new Test9(); i1.M1(); i1 = new Test10(); i1.M1(); i1 = new Test11(); i1.M1(); i1 = new Test12(); i1.M1(); } } class Test9 : I7 { void I1.M1() { System.Console.WriteLine(""Test9.I1.M1""); } } class Test10 : I1, I2, I3, I4 { public void M1() { System.Console.WriteLine(""Test10.M1""); } } class Test11 : I1, I2, I3, I5, I4 { public void M1() { System.Console.WriteLine(""Test11.M1""); } } class Test12 : I8 { public virtual void M1() { System.Console.WriteLine(""Test12.M1""); } } "; foreach (var ref1 in refs1) { var compilation2 = CreateCompilation(source2, new[] { ref1 }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // According to LDM decision captured at https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-06-14.md, // we do not require interfaces to have a most specific implementation of all members. Therefore, there are no // errors in this compilation. compilation2.VerifyDiagnostics(); Validate2(compilation2.SourceModule); void Validate2(ModuleSymbol m) { Validate1(m); var i1 = FindType(m, "I1"); var i1m1 = i1.GetMember<MethodSymbol>("M1"); var i7 = FindType(m, "I7"); var i8 = FindType(m, "I8"); Assert.Null(i7.FindImplementationForInterfaceMember(i1m1)); Assert.Null(i8.FindImplementationForInterfaceMember(i1m1)); } CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); compilation2 = CreateCompilation(source2, new[] { ref1 }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); Validate2(compilation2.SourceModule); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); var refs2 = new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }; var compilation4 = CreateCompilation(source4, new[] { ref1 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); Validate4(compilation4.SourceModule); void Validate4(ModuleSymbol m) { Validate1(m); var i1 = FindType(m, "I1"); var i1m1 = i1.GetMember<MethodSymbol>("M1"); var i2 = FindType(m, "I2"); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); var i5 = FindType(m, "I5"); var i5m1 = i5.GetMember<MethodSymbol>("I1.M1"); var test5 = FindType(m, "Test5"); var test6 = FindType(m, "Test6"); var test7 = FindType(m, "Test7"); Assert.Same(i2m1, test5.FindImplementationForInterfaceMember(i1m1)); Assert.Same(i5m1, test6.FindImplementationForInterfaceMember(i1m1)); Assert.Same(i5m1, test7.FindImplementationForInterfaceMember(i1m1)); } CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.I1.M1 I5.I1.M1 I5.I1.M1 " , verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate4); foreach (var ref2 in refs2) { var compilation3 = CreateCompilation(source3, new[] { ref1, ref2 }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8505: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I2.I1.M1()', nor 'I3.I1.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1()", "I2.I1.M1()", "I3.I1.M1()").WithLocation(2, 15), // (5,15): error CS8505: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I2.I1.M1()', nor 'I3.I1.M1()' are most specific. // class Test2 : I7 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I7").WithArguments("I1.M1()", "I2.I1.M1()", "I3.I1.M1()").WithLocation(5, 15), // (8,15): error CS8505: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I2.I1.M1()', nor 'I3.I1.M1()' are most specific. // class Test3 : I1, I2, I3, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.M1()", "I2.I1.M1()", "I3.I1.M1()").WithLocation(8, 15), // (11,15): error CS8505: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I5.I1.M1()', nor 'I4.I1.M1()' are most specific. // class Test4 : I1, I2, I3, I5, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.M1()", "I5.I1.M1()", "I4.I1.M1()").WithLocation(11, 15), // (14,15): error CS8505: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I5.I1.M1()', nor 'I4.I1.M1()' are most specific. // class Test5 : I8 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I8").WithArguments("I1.M1()", "I5.I1.M1()", "I4.I1.M1()").WithLocation(14, 15) ); Validate3(compilation3.SourceModule); void Validate3(ModuleSymbol m) { Validate1(m); Validate2(m); var i1 = FindType(m, "I1"); var i1m1 = i1.GetMember<MethodSymbol>("M1"); var test1 = FindType(m, "Test1"); var test2 = FindType(m, "Test2"); var test3 = FindType(m, "Test3"); var test4 = FindType(m, "Test4"); var test5 = FindType(m, "Test5"); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test3.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test4.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test5.FindImplementationForInterfaceMember(i1m1)); } var compilation5 = CreateCompilation(source5, new[] { ref1, ref2 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics(); Validate5(compilation5.SourceModule); void Validate5(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = i1.GetMember<MethodSymbol>("M1"); var test8 = FindType(m, "Test8"); var test9 = FindType(m, "Test9"); var test10 = FindType(m, "Test10"); var test11 = FindType(m, "Test11"); var test12 = FindType(m, "Test12"); Assert.Same(test8.GetMember<MethodSymbol>("I1.M1"), test8.FindImplementationForInterfaceMember(i1m1)); Assert.Same(test9.GetMember<MethodSymbol>("I1.M1"), test9.FindImplementationForInterfaceMember(i1m1)); Assert.Same(test10.GetMember<MethodSymbol>("M1"), test10.FindImplementationForInterfaceMember(i1m1)); Assert.Same(test11.GetMember<MethodSymbol>("M1"), test11.FindImplementationForInterfaceMember(i1m1)); Assert.Same(test12.GetMember<MethodSymbol>("M1"), test12.FindImplementationForInterfaceMember(i1m1)); } CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"Test8.I1.M1 Test9.I1.M1 Test10.M1 Test11.M1 Test12.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate5); } } } private static NamedTypeSymbol FindType(ModuleSymbol m, string name) { var result = m.GlobalNamespace.GetMember<NamedTypeSymbol>(name); if ((object)result != null) { return result; } foreach (var assembly in m.ReferencedAssemblySymbols) { result = assembly.Modules[0].GlobalNamespace.GetMember<NamedTypeSymbol>(name); if ((object)result != null) { return result; } } Assert.NotNull(result); return result; } [Fact] public void MethodImplementationInDerived_13() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { void I1.M1() { } } public interface I3 : I1 { void I1.M1() { } } "; var source2 = @" class Test1 : I2, I3 { public int M1() => 1; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (2,15): error CS8505: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I2.I1.M1()', nor 'I3.I1.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1()", "I2.I1.M1()", "I3.I1.M1()").WithLocation(2, 15), // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implement 'I1.M1()' because it does not have the matching return type of 'void'. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test1", "I1.M1()", "Test1.M1()", "void").WithLocation(2, 15) ); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8505: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I2.I1.M1()', nor 'I3.I1.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1()", "I2.I1.M1()", "I3.I1.M1()").WithLocation(2, 15), // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implement 'I1.M1()' because it does not have the matching return type of 'void'. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test1", "I1.M1()", "Test1.M1()", "void").WithLocation(2, 15) ); } [Fact] [WorkItem(20084, "https://github.com/dotnet/roslyn/issues/20084")] public void MethodImplementationInDerived_14() { var source1 = @" public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } void M2<S>() { System.Console.WriteLine(""I1.M2""); } } public interface I2<T> : I1<T> { void I1<T>.M1() { System.Console.WriteLine(""I2.I1.M1""); } void I1<T>.M2<S>() { System.Console.WriteLine(""I2.I1.M2""); } } public interface I3<T> : I1<T> {} "; var source2 = @" class Test1 : I1<int> { static void Main() { I1<int> i1Int = new Test1(); i1Int.M1(); i1Int.M2<int>(); I1<long> i1Long = new Test2(); i1Long.M1(); i1Long.M2<int>(); } } class Test2 : I2<long> {} "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = i1.GetMember<MethodSymbol>("M1"); var i1m2 = i1.GetMember<MethodSymbol>("M2"); var i2 = FindType(m, "I2"); var i2m1 = i2.GetMember<MethodSymbol>("I1<T>.M1"); var i2m2 = i2.GetMember<MethodSymbol>("I1<T>.M2"); var i2i1 = i2.InterfacesNoUseSiteDiagnostics().Single(); var i2i1m1 = i2i1.GetMember<MethodSymbol>("M1"); var i2i1m2 = i2i1.GetMember<MethodSymbol>("M2"); var i3 = FindType(m, "I3"); var i3i1 = i3.InterfacesNoUseSiteDiagnostics().Single(); var i3i1m1 = i3i1.GetMember<MethodSymbol>("M1"); var i3i1m2 = i3i1.GetMember<MethodSymbol>("M2"); Assert.Same(i1m1, i1.FindImplementationForInterfaceMember(i1m1)); Assert.Same(i1m2, i1.FindImplementationForInterfaceMember(i1m2)); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(i2.FindImplementationForInterfaceMember(i1m2)); Assert.Null(i2.FindImplementationForInterfaceMember(i3i1m1)); Assert.Null(i2.FindImplementationForInterfaceMember(i3i1m2)); Assert.Same(i2m1, i2.FindImplementationForInterfaceMember(i2i1m1)); Assert.Same(i2m2, i2.FindImplementationForInterfaceMember(i2i1m2)); Assert.Null(i3.FindImplementationForInterfaceMember(i1m1)); Assert.Null(i3.FindImplementationForInterfaceMember(i1m2)); Assert.Null(i3.FindImplementationForInterfaceMember(i2i1m1)); Assert.Null(i3.FindImplementationForInterfaceMember(i2i1m2)); Assert.Same(i3i1m1, i3.FindImplementationForInterfaceMember(i3i1m1)); Assert.Same(i3i1m2, i3.FindImplementationForInterfaceMember(i3i1m2)); ValidateExplicitImplementation(i2m1); ValidateExplicitImplementation(i2m2); var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test1i1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)); var test1i1m1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)).GetMember<MethodSymbol>("M1"); var test1i1m2 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)).GetMember<MethodSymbol>("M2"); var test2 = m.GlobalNamespace.GetTypeMember("Test2"); var test2i1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)); var test2i1m1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)).GetMember<MethodSymbol>("M1"); var test2i1m2 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)).GetMember<MethodSymbol>("M2"); var test2i2 = i2.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)); var test2i2m1 = i2.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)).GetMember<MethodSymbol>("I1<T>.M1"); var test2i2m2 = i2.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)).GetMember<MethodSymbol>("I1<T>.M2"); Assert.NotSame(test1i1, test1i1m1.ContainingType); Assert.NotSame(test1i1, test1i1m2.ContainingType); Assert.NotSame(test2i1, test2i1m1.ContainingType); Assert.NotSame(test2i1, test2i1m2.ContainingType); Assert.NotSame(test2i2, test2i2m1.ContainingType); Assert.NotSame(test2i2, test2i2m2.ContainingType); Assert.Null(test1i1.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1i1.FindImplementationForInterfaceMember(i1m2)); Assert.Equal(test1i1m1, test1i1.FindImplementationForInterfaceMember(test1i1m1)); Assert.Equal(test1i1m2, test1i1.FindImplementationForInterfaceMember(test1i1m2)); Assert.Equal(test2i1m1, test2i1.FindImplementationForInterfaceMember(test2i1m1)); Assert.Equal(test2i1m2, test2i1.FindImplementationForInterfaceMember(test2i1m2)); Assert.Null(test2i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test2i2.FindImplementationForInterfaceMember(i1m2)); Assert.Equal(test2i2m1, test2i2.FindImplementationForInterfaceMember(test2i1m1)); Assert.Equal(test2i2m2, test2i2.FindImplementationForInterfaceMember(test2i1m2)); ValidateExplicitImplementation(test2i2m1); ValidateExplicitImplementation(test2i2m2); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m2)); Assert.Equal(test1i1m1, test1.FindImplementationForInterfaceMember(test1i1m1)); Assert.Equal(test1i1m2, test1.FindImplementationForInterfaceMember(test1i1m2)); Assert.Null(test2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1m2)); Assert.Equal(test2i2m1, test2.FindImplementationForInterfaceMember(test2i1m1)); Assert.Equal(test2i2m2, test2.FindImplementationForInterfaceMember(test2i1m2)); } CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1 I1.M2 I2.I1.M1 I2.I1.M2 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1 I1.M2 I2.I1.M1 I2.I1.M2 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1 I1.M2 I2.I1.M1 I2.I1.M2 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); } [Fact] public void MethodImplementationInDerived_15() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2 : I1<string> { void I1<string>.M1() { } } public interface I3 : I1<string?> { void I1<string?>.M1() { } } "; var source2 = @"#nullable enable warnings class Test1 : I2, I3 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (2,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(2, 7), // (2,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(2, 15), // (2,19): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I3").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(2, 19) ); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (2,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(2, 7), // (2,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(2, 15), // (2,19): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I3").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(2, 19) ); test1 = compilation3.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); } [Fact] public void MethodImplementationInDerived_16() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2 : I1<string> { void I1<string>.M1() { } } public interface I3 : I1<string?> { void I1<string?>.M1() { } } "; var source2 = @"#nullable enable warnings class Test1 : I2, I3, I1<string> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (2,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(2, 7), // (2,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(2, 15), // (2,19): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I3").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(2, 19), // (2,23): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1<string>").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(2, 23) ); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[4].GetMember("M1"))); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (2,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(2, 7), // (2,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(2, 15), // (2,19): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I3").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(2, 19), // (2,23): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1<string>").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(2, 23) ); test1 = compilation3.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[4].GetMember("M1"))); } [Fact] public void MethodImplementationInDerived_17() { var source1 = @" public interface I1<T> { void M1(); } public interface I2 : I1<string> { void I1<string>.M1() { } } #nullable enable public interface I3 : I1<string?> { void I1<string?>.M1() { } } "; var source2 = @" #nullable enable class Test1 : I2, I3, I1<string> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (3,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(3, 15), // (3,19): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I3").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(3, 19), // (3,23): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1<string>").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(3, 23) ); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[4].GetMember("M1"))); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (3,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(3, 15), // (3,19): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I3").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(3, 19), // (3,23): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1<string>").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(3, 23) ); test1 = compilation3.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[4].GetMember("M1"))); } [Fact] public void MethodImplementationInDerived_18() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2 : I1<string> { void I1<string>.M1() { } } public interface I3 : I1<string?> { void I1<string?>.M1() { } } "; var source2 = @" #nullable enable class Test1 : I2, I3, I1<string?> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3, I1<string?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7), // (4,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string?> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(4, 15), // (4,23): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string?>.M1()' are most specific. // class Test1 : I2, I3, I1<string?> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1<string?>").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string?>.M1()").WithLocation(4, 23) ); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3, I1<string?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7), // (4,15): error CS8705: Interface member 'I1<string>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string?> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1<string>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(4, 15), // (4,23): error CS8705: Interface member 'I1<string?>.M1()' does not have a most specific implementation. Neither 'I2.I1<string>.M1()', nor 'I3.I1<string>.M1()' are most specific. // class Test1 : I2, I3, I1<string?> Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1<string?>").WithArguments("I1<string?>.M1()", "I2.I1<string>.M1()", "I3.I1<string>.M1()").WithLocation(4, 23) ); test1 = compilation3.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); } [Fact] public void MethodImplementationInDerived_19() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2 : I1<string> { } public interface I3 : I2, I1<string?> { void I1<string>.M1() { } void I1<string?>.M1() { } } "; var source2 = @" #nullable enable class Test1 : I3 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (13,18): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'I3' with different nullability of reference types. // public interface I3 : I2, I1<string?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "I3").WithArguments("I1<string?>", "I3").WithLocation(13, 18), // (13,18): error CS8646: 'I1<string>.M1()' is explicitly implemented more than once. // public interface I3 : I2, I1<string?> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "I3").WithArguments("I1<string>.M1()").WithLocation(13, 18), // (13,18): error CS8646: 'I1<string?>.M1()' is explicitly implemented more than once. // public interface I3 : I2, I1<string?> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "I3").WithArguments("I1<string?>.M1()").WithLocation(13, 18) ); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7), // (4,15): error CS0535: 'Test1' does not implement interface member 'I1<string>.M1()' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1<string>.M1()").WithLocation(4, 15), // (4,15): error CS0535: 'Test1' does not implement interface member 'I1<string?>.M1()' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1<string?>.M1()").WithLocation(4, 15) ); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I3", "I2", "I1<System.String>", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[2].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); } [Fact] public void MethodImplementationInDerived_20() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2 : I1<string> { } public interface I3 : I1<string?> { void I1<string?>.M1() { System.Console.WriteLine(""I3.M1""); } } "; var source2 = @" #nullable enable class Test1 : I2, I3 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>", "I3", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I3.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I3.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7), // (4,15): warning CS8644: 'Test1' does not implement interface member 'I1<string>.M1()'. Nullability of reference types in interface implemented by the base type doesn't match. // class Test1 : I2, I3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, "I2").WithArguments("Test1", "I1<string>.M1()").WithLocation(4, 15) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I3.M1 I3.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_21() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2 : I1<string> { } public interface I3 : I1<string?> { void I1<string?>.M1() { System.Console.WriteLine(""I3.M1""); } } "; var source2 = @" #nullable enable class Test1 : I3, I2 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I3", "I1<System.String?>", "I2", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I3.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I3.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I3, I2 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string>", "Test1").WithLocation(4, 7), // (4,19): warning CS8644: 'Test1' does not implement interface member 'I1<string>.M1()'. Nullability of reference types in interface implemented by the base type doesn't match. // class Test1 : I3, I2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, "I2").WithArguments("Test1", "I1<string>.M1()").WithLocation(4, 19) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I3.M1 I3.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_22() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2<T> : I1<T> { void I1<T>.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3 : I2<string> { } public interface I4 : I2<string?> { } "; var source2 = @" #nullable enable class Test1 : I3, I4 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I3", "I2<System.String>", "I1<System.String>", "I4", "I2<System.String?>", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I2<System.String?>.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[2].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I2<System.String?>.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[5].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I2<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I3, I4 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I2<string?>", "Test1").WithLocation(4, 7), // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I3, I4 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I2.M1 I2.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_23() { var source1 = @" #nullable enable public interface I1<T> { void M1() { System.Console.WriteLine(""I1.M1""); } } public interface I2<T> : I1<T> { void I1<T>.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3 : I2<string> { } public interface I4 : I2<string?> { } "; var source2 = @" #nullable enable class Test1 : I4, I3 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I4", "I2<System.String?>", "I1<System.String?>", "I3", "I2<System.String>", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I2<System.String>.I1<System.String>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[2].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I2<System.String>.I1<System.String>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[5].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I2<string>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I4, I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I2<string>", "Test1").WithLocation(4, 7), // (4,7): warning CS8645: 'I1<string>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I4, I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string>", "Test1").WithLocation(4, 7) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I2.M1 I2.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_24() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2 : I1<string> { void I1<string?>.M1() { System.Console.WriteLine(""I2.M1""); } } "; var source2 = @" #nullable enable class Test1 : I2 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (11,10): warning CS8643: Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type. // void I1<string?>.M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInExplicitlyImplementedInterface, "I1<string?>").WithLocation(11, 10) ); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2", "I1<System.String>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I2.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[1].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I2.M1 I2.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_25() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2 : I1<string> { void I1<string>.M1() { System.Console.WriteLine(""I2.M1""); } } "; var source2 = @" #nullable enable class Test1 : I2, I1<string?> { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2, I1<string?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7), // (4,19): warning CS8644: 'Test1' does not implement interface member 'I1<string?>.M1()'. Nullability of reference types in interface implemented by the base type doesn't match. // class Test1 : I2, I1<string?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, "I1<string?>").WithArguments("Test1", "I1<string?>.M1()").WithLocation(4, 19) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I2.M1 I2.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_26() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2 : I1<string?> { void I1<string>.M1() { System.Console.WriteLine(""I2.M1""); } } "; var source2 = @" #nullable enable class Test1 : I2, I1<string?> { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (11,10): warning CS8643: Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type. // void I1<string>.M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInExplicitlyImplementedInterface, "I1<string>").WithLocation(11, 10) ); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I2.M1 I2.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_27() { var source1 = @" #nullable enable public interface I1<T> { void M1(); } public interface I2<T>: I1<T> { void I1<T>.M1() { System.Console.WriteLine(""I2.M1""); } } public interface I3<T> : I1<T> { void I1<T>.M1() { System.Console.WriteLine(""I3.M1""); } } public interface I4 : I2<string?>, I3<string?> { void I1<string?>.M1() { System.Console.WriteLine(""I4.M1""); } } "; var source2 = @" #nullable enable class Test1 : I2<string>, I3<string>, I4 { static void Main() { ((I1<string?>)new Test1()).M1(); ((I1<string>)new Test1()).M1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I2<System.String>", "I3<System.String>", "I1<System.String>", "I4", "I2<System.String?>", "I3<System.String?>", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Equal("void I4.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[2].GetMember("M1")).ToTestDisplayString()); Assert.Equal("void I4.I1<System.String?>.M1()", test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[6].GetMember("M1")).ToTestDisplayString()); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I2<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2<string>, I3<string>, I4 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I2<string?>", "Test1").WithLocation(4, 7), // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2<string>, I3<string>, I4 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7), // (4,7): warning CS8645: 'I3<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I2<string>, I3<string>, I4 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I3<string?>", "Test1").WithLocation(4, 7), // (4,15): warning CS8644: 'Test1' does not implement interface member 'I1<string>.M1()'. Nullability of reference types in interface implemented by the base type doesn't match. // class Test1 : I2<string>, I3<string>, I4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, "I2<string>").WithArguments("Test1", "I1<string>.M1()").WithLocation(4, 15) ); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" I4.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr); } } [Fact] public void MethodImplementationInDerived_28() { var source1 = @" public interface I2 { protected void M1(); } public interface I4 { protected void M1(); } public interface I5 : I4 { static void Test(I5 i4) { i4.M1(); } } public interface I6 : I2 { static void Test(I6 i2) { i2.M1(); } } "; var source2 = @" public interface I1 : I6, I5 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { I6.Test(new Test1()); I5.Test(new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); } var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); foreach (var reference in new[] { compilation4.ToMetadataReference(), compilation4.EmitToImageReference() }) { var compilation5 = CreateCompilation(source2 + source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics(); CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); } } [Fact] public void MethodImplementationInDerived_29() { var source1 = @" public interface I2 { protected internal void M1(); } public interface I4 { protected internal void M1(); } public interface I5 : I4 { static void Test(I5 i4) { i4.M1(); } } public interface I6 : I2 { static void Test(I6 i2) { i2.M1(); } } "; var source2 = @" public interface I1 : I6, I5 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { I6.Test(new Test1()); I5.Test(new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); } var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); foreach (var reference in new[] { compilation4.ToMetadataReference(), compilation4.EmitToImageReference() }) { var compilation5 = CreateCompilation(source2 + source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics(); CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); } } [Fact] public void MethodImplementationInDerived_30() { var source1 = @" public interface I2 { private protected void M1(); } public interface I4 { private protected void M1(); } public interface I5 : I4 { static void Test(I5 i4) { i4.M1(); } } public interface I6 : I2 { static void Test(I6 i2) { i2.M1(); } } "; var source2 = @" public interface I1 : I6, I5 { void I2.M1() { System.Console.WriteLine(""I2.M1""); } void I4.M1() { System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { I6.Test(new Test1()); I5.Test(new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateMethodImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateMethodImplementationInDerived_01); } var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); foreach (var reference in new[] { compilation4.ToMetadataReference(), compilation4.EmitToImageReference() }) { var compilation5 = CreateCompilation(source2 + source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateMethodImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics( // (4,13): error CS0122: 'I2.M1()' is inaccessible due to its protection level // void I2.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1()").WithLocation(4, 13), // (8,13): error CS0122: 'I4.M1()' is inaccessible due to its protection level // void I4.M1() Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I4.M1()").WithLocation(8, 13) ); } } [Fact] public void MethodImplementationInDerived_31() { var source1 = @" public interface I1 { void M1(); void M2(); } public interface I2 : I1 { public virtual void M1() {} new public virtual void M2() {} } public interface I3 : I1, I2 { } class Test1 : I1, I2 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (10,25): warning CS0108: 'I2.M1()' hides inherited member 'I1.M1()'. Use the new keyword if hiding was intended. // public virtual void M1() Diagnostic(ErrorCode.WRN_NewRequired, "M1").WithArguments("I2.M1()", "I1.M1()").WithLocation(10, 25), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.M2()' // class Test1 : I1, I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M2()").WithLocation(20, 15), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I1, I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I1.M1()").WithLocation(20, 15) ); } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void PropertyImplementationInDerived_01() { var source1 = @" public interface I2 { int M1 {get;} } public interface I4 { int M1 {set;} } public interface I5 : I4 { } public interface I1 : I2, I5 { int I2.M1 { get { System.Console.WriteLine(""I2.M1""); return 1; } } int I4.M1 { set => System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source2 = @" class Test1 : I1 { static void Main() { I2 i2 = new Test1(); _ = i2.M1; I4 i4 = new Test1(); i4.M1 = 0; } } "; ValidatePropertyImplementationInDerived_01(source1, source2); } private void ValidatePropertyImplementationInDerived_01(string source1, string source2) { foreach (var options in new[] { TestOptions.DebugExe, TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All) }) { var compilation1 = CreateCompilation(source1 + source2, options: options, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidatePropertyImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationInDerived_01); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: options, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidatePropertyImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationInDerived_01); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: options, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidatePropertyImplementationInDerived_01(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationInDerived_01); } } private static void ValidatePropertyImplementationInDerived_01(ModuleSymbol m) { ValidatePropertyImplementationInDerived_01(m, i4M1IsAbstract: false); } private static void ValidatePropertyImplementationInDerived_01(ModuleSymbol m, bool i4M1IsAbstract) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var i1i2m1 = i1.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); var i1i4m1 = i1.GetMembers().OfType<PropertySymbol>().Where(p => p.Name.StartsWith("I4.")).Single(); var i2 = i1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I2").Single(); var i2m1 = i2.GetMembers().OfType<PropertySymbol>().Single(); var i4 = i1.AllInterfacesNoUseSiteDiagnostics.Where(i => i.Name == "I4").Single(); var i4m1 = i4.GetMembers().OfType<PropertySymbol>().Single(); var i3 = i1.ContainingNamespace.GetTypeMember("I3"); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); ValidateExplicitImplementation(i1i2m1); ValidateExplicitImplementation(i1i4m1, i4M1IsAbstract); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1i2m1); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1i4m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, test1, i2m1); VerifyFindImplementationForInterfaceMemberSame(i4M1IsAbstract ? null : i1i4m1, test1, i4m1); VerifyFindImplementationForInterfaceMemberSame(null, i1, i1i2m1); VerifyFindImplementationForInterfaceMemberSame(null, i1, i1i4m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, i1, i2m1); VerifyFindImplementationForInterfaceMemberSame(i4M1IsAbstract ? null : i1i4m1, i1, i4m1); VerifyFindImplementationForInterfaceMemberSame(i2m1.IsAbstract ? null : i2m1, i2, i2m1); VerifyFindImplementationForInterfaceMemberSame(i4m1.IsAbstract ? null : i4m1, i4, i4m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, i3, i2m1); VerifyFindImplementationForInterfaceMemberSame(i4M1IsAbstract ? null : i1i4m1, i3, i4m1); } private static void VerifyFindImplementationForInterfaceMemberSame(PropertySymbol expected, NamedTypeSymbol implementingType, PropertySymbol interfaceProperty) { Assert.Same(expected, implementingType.FindImplementationForInterfaceMember(interfaceProperty)); ValidateAccessor(expected?.GetMethod, interfaceProperty.GetMethod); ValidateAccessor(expected?.SetMethod, interfaceProperty.SetMethod); void ValidateAccessor(MethodSymbol accessor, MethodSymbol interfaceAccessor) { if ((object)interfaceAccessor != null) { Assert.Same(interfaceAccessor.DeclaredAccessibility == Accessibility.Private ? null : accessor, implementingType.FindImplementationForInterfaceMember(interfaceAccessor)); } else { Assert.Null(accessor); } } } private static void VerifyFindImplementationForInterfaceMemberEqual(PropertySymbol expected, NamedTypeSymbol implementingType, PropertySymbol interfaceProperty) { Assert.Equal(expected, implementingType.FindImplementationForInterfaceMember(interfaceProperty)); ValidateAccessor(expected?.GetMethod, interfaceProperty.GetMethod); ValidateAccessor(expected?.SetMethod, interfaceProperty.SetMethod); void ValidateAccessor(MethodSymbol accessor, MethodSymbol interfaceAccessor) { if ((object)interfaceAccessor != null) { Assert.Equal(accessor, implementingType.FindImplementationForInterfaceMember(interfaceAccessor)); } else { Assert.Null(accessor); } } } private static void ValidateExplicitImplementation(PropertySymbol m1, bool isAbstract = false) { Assert.Equal(isAbstract, m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.Equal(isAbstract, m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); ValidateAccessor(m1.GetMethod, isAbstract); ValidateAccessor(m1.SetMethod, isAbstract); static void ValidateAccessor(MethodSymbol accessor, bool isAbstract) { if ((object)accessor != null) { ValidateExplicitImplementation(accessor, isAbstract); } } } [Fact] public void PropertyImplementationInDerived_02() { var source1 = @" public interface I2 { int M1 {get;} } public interface I4 { int M1 {set;} } public interface I1 : I2, I4 { int I2.M1 => Getter(); private int Getter() { System.Console.WriteLine(""I2.M1""); return 1; } int I4.M1 { set { System.Console.WriteLine(""I2.M1""); } } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_02(source1, new DiagnosticDescription[] { // (14,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int I2.M1 => Getter(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "Getter()").WithArguments("default interface implementation", "8.0").WithLocation(14, 18), // (16,17): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // private int Getter() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "Getter").WithArguments("default interface implementation", "8.0").WithLocation(16, 17), // (24,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // set Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(24, 9) }, // (6,15): error CS8506: 'I1.I2.M1.get' cannot implement interface member 'I2.M1.get' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1.get", "I2.M1.get", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15), // (6,15): error CS8506: 'I1.I4.M1.set' cannot implement interface member 'I4.M1.set' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1.set", "I4.M1.set", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15) ); } private void ValidatePropertyImplementationInDerived_02(string source1, DiagnosticDescription[] expected1, params DiagnosticDescription[] expected2) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected1); ValidatePropertyImplementationInDerived_01(compilation1.SourceModule); var source2 = @" public interface I3 : I1 { } class Test1 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(expected2); ValidatePropertyImplementationInDerived_01(compilation2.SourceModule); } [Fact] public void PropertyImplementationInDerived_03() { var source1 = @" public interface I2 { int M1 {get; set;} } public interface I4 { int M1 {set;} } public interface I1 : I2, I4 { int I2.M1 { get { System.Console.WriteLine(""I2.M1""); return 1; } set { System.Console.WriteLine(""I2.M1""); } } int I4.M1 { set { System.Console.WriteLine(""I2.M1""); } } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_03(source1, new DiagnosticDescription[] { // (16,9): error CS8501: Target runtime doesn't support default interface implementation. // get Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(16, 9), // (21,9): error CS8501: Target runtime doesn't support default interface implementation. // set Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(21, 9), // (29,9): error CS8501: Target runtime doesn't support default interface implementation. // set Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(29, 9) }, // (6,15): error CS8502: 'I1.I2.M1.set' cannot implement interface member 'I2.M1.set' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1.set", "I2.M1.set", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I2.M1.get' cannot implement interface member 'I2.M1.get' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1.get", "I2.M1.get", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I4.M1.set' cannot implement interface member 'I4.M1.set' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1.set", "I4.M1.set", "Test1").WithLocation(6, 15) ); } private void ValidatePropertyImplementationInDerived_03(string source1, DiagnosticDescription[] expected1, params DiagnosticDescription[] expected2) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected1); ValidatePropertyImplementationInDerived_01(compilation1.SourceModule); var source2 = @" public interface I3 : I1 { } class Test1 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(expected2); } [Fact] public void PropertyImplementationInDerived_04() { var source1 = @" public interface I2 { int M1 {get;} } public interface I4 { int M1 {set;} } public interface I1 : I2, I4 { int I2.M1 {get;} int I4.M1 {set;} } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (14,16): error CS0501: 'I1.I2.M1.get' must declare a body because it is not marked abstract, extern, or partial // int I2.M1 {get;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.I2.M1.get").WithLocation(14, 16), // (15,16): error CS0501: 'I1.I4.M1.set' must declare a body because it is not marked abstract, extern, or partial // int I4.M1 {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.I4.M1.set").WithLocation(15, 16) ); } private void ValidatePropertyImplementationInDerived_04(string source1, params DiagnosticDescription[] expected) { ValidatePropertyImplementationInDerived_04(source1, i4M1IsAbstract: false, expected); } private void ValidatePropertyImplementationInDerived_04(string source1, bool i4M1IsAbstract, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); ValidatePropertyImplementationInDerived_01(compilation1.SourceModule, i4M1IsAbstract); } [Fact] public void PropertyImplementationInDerived_05() { var source1 = @" public interface I2 { int M1 {get;} } public interface I4 { int M1 {set;} } public interface I1 { int I2.M1 {get => throw null;} int I4.M1 {set => throw null;} } "; ValidatePropertyImplementationInDerived_05(source1, // (14,9): error CS0540: 'I1.I2.M1': containing type does not implement interface 'I2' // int I2.M1 {get => throw null;} Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.I2.M1", "I2").WithLocation(14, 9), // (15,9): error CS0540: 'I1.I4.M1': containing type does not implement interface 'I4' // int I4.M1 {set => throw null;} Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I4").WithArguments("I1.I4.M1", "I4").WithLocation(15, 9) ); } private void ValidatePropertyImplementationInDerived_05(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected); } [Fact] public void PropertyImplementationInDerived_06() { var source1 = @" public interface I2 { int M1 {get; set;} } public interface I4 { int M1 {get; set;} } public interface I1 : I2, I4 { public static int I2.M1 { internal get => throw null; set => throw null; } internal virtual int I4.M1 { public get => throw null; set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (14,26): error CS0106: The modifier 'static' is not valid for this item // public static int I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("static").WithLocation(14, 26), // (14,26): error CS0106: The modifier 'public' is not valid for this item // public static int I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("public").WithLocation(14, 26), // (16,18): error CS0106: The modifier 'internal' is not valid for this item // internal get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("internal").WithLocation(16, 18), // (19,29): error CS0106: The modifier 'internal' is not valid for this item // internal virtual int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("internal").WithLocation(19, 29), // (19,29): error CS0106: The modifier 'virtual' is not valid for this item // internal virtual int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("virtual").WithLocation(19, 29), // (21,16): error CS0106: The modifier 'public' is not valid for this item // public get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("public").WithLocation(21, 16) ); } [Fact] public void PropertyImplementationInDerived_07() { var source1 = @" public interface I2 { int M1 {get; set;} } public interface I4 { int M1 {get; set;} } public interface I1 : I2, I4 { private sealed int I2.M1 { private get => throw null; set => throw null; } protected abstract int I4.M1 { get => throw null; protected set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, i4M1IsAbstract: true, // (14,27): error CS0106: The modifier 'sealed' is not valid for this item // private sealed int I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("sealed").WithLocation(14, 27), // (14,27): error CS0106: The modifier 'private' is not valid for this item // private sealed int I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("private").WithLocation(14, 27), // (16,17): error CS0106: The modifier 'private' is not valid for this item // private get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("private").WithLocation(16, 17), // (19,31): error CS0106: The modifier 'protected' is not valid for this item // protected abstract int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected").WithLocation(19, 31), // (21,9): error CS0500: 'I1.I4.M1.get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.I4.M1.get").WithLocation(21, 9), // (22,19): error CS0106: The modifier 'protected' is not valid for this item // protected set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("protected").WithLocation(22, 19), // (22,19): error CS0500: 'I1.I4.M1.set' cannot declare a body because it is marked abstract // protected set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I1.I4.M1.set").WithLocation(22, 19), // (30,15): error CS0535: 'Test1' does not implement interface member 'I4.M1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I4.M1").WithLocation(30, 15) ); } [Fact] public void PropertyImplementationInDerived_08() { var source1 = @" public interface I2 { int M1 {get; set;} } public interface I4 { int M1 {get; set;} } public interface I1 : I2, I4 { private protected int I2.M1 { private protected get => throw null; set => throw null; } internal protected override int I4.M1 { get => throw null; internal protected set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (14,30): error CS0106: The modifier 'private protected' is not valid for this item // private protected int I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("private protected").WithLocation(14, 30), // (16,27): error CS0106: The modifier 'private protected' is not valid for this item // private protected get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("private protected").WithLocation(16, 27), // (19,40): error CS0106: The modifier 'protected internal' is not valid for this item // internal protected override int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected internal").WithLocation(19, 40), // (19,40): error CS0106: The modifier 'override' is not valid for this item // internal protected override int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("override").WithLocation(19, 40), // (22,28): error CS0106: The modifier 'protected internal' is not valid for this item // internal protected set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("protected internal").WithLocation(22, 28) ); } [Fact] public void PropertyImplementationInDerived_09() { var source1 = @" public interface I2 { int M1 {get;} } public interface I1 : I2 { extern int I2.M1 {get;} } public interface I3 : I1 { } class Test1 : I1 {} "; var source2 = @" public interface I2 { int M1 {set;} } public interface I1 : I2 { extern int I2.M1 { set {}} } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_09(source1, source2, new DiagnosticDescription[] { // (9,23): warning CS0626: Method, operator, or accessor 'I1.I2.M1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int I2.M1 {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.I2.M1.get").WithLocation(9, 23) }, new DiagnosticDescription[] { // (9,23): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // extern int I2.M1 {get;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(9, 23), // (9,23): warning CS0626: Method, operator, or accessor 'I1.I2.M1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int I2.M1 {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.I2.M1.get").WithLocation(9, 23) }, new DiagnosticDescription[] { // (9,23): error CS8501: Target runtime doesn't support default interface implementation. // extern int I2.M1 {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(9, 23), // (9,23): warning CS0626: Method, operator, or accessor 'I1.I2.M1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int I2.M1 {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.I2.M1.get").WithLocation(9, 23) }, // (10,7): error CS0179: 'I1.I2.M1.set' cannot be extern and declare a body // { set {}} Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("I1.I2.M1.set").WithLocation(10, 7) ); } private void ValidatePropertyImplementationInDerived_09(string source1, string source2, DiagnosticDescription[] expected1, DiagnosticDescription[] expected2, DiagnosticDescription[] expected3, params DiagnosticDescription[] expected4) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(expected1); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var i1i2m1 = GetSingleProperty(i1); var i2 = i1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I2").Single(); var i2m1 = GetSingleProperty(i2); var i3 = i1.ContainingNamespace.GetTypeMember("I3"); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); ValidateExplicitExternImplementation(i1i2m1); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1i2m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, test1, i2m1); VerifyFindImplementationForInterfaceMemberSame(null, i1, i1i2m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, i1, i2m1); VerifyFindImplementationForInterfaceMemberSame(null, i2, i2m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, i3, i2m1); } CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(expected2); Validate1(compilation2.SourceModule); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected3); Validate1(compilation3.SourceModule); var compilation4 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(expected4); Validate1(compilation4.SourceModule); } private static void ValidateExplicitExternImplementation(PropertySymbol m1) { Assert.False(m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.False(m1.IsSealed); Assert.False(m1.IsStatic); Assert.NotEqual(m1.OriginalDefinition is PEPropertySymbol, m1.IsExtern); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); ValidateAccessor(m1.GetMethod); ValidateAccessor(m1.SetMethod); void ValidateAccessor(MethodSymbol accessor) { if ((object)accessor != null) { ValidateExplicitExternImplementation(accessor); } } } [Fact] public void PropertyImplementationInDerived_10() { var source1 = @" public interface I1 { int M1 {get;set;} int M2 {get;set;} } public interface I2 : I1 { int I1.M1 { get => throw null; } int I1.M2 { set => throw null; } } class Test1 : I2 {} public interface I3 { int M1 {get;} int M2 {set;} int M3 {get;set;} int M4 {get;set;} } public interface I4 : I3 { int I3.M1 { get => throw null; set => throw null; } int I3.M2 { get => throw null; set => throw null; } int I3.M3 {get; set;} int I3.M4 {get; set;} = 0; } class Test2 : I4 {} "; ValidatePropertyImplementationInDerived_05(source1, // (10,12): error CS0551: Explicit interface implementation 'I2.I1.M1' is missing accessor 'I1.M1.set' // int I1.M1 Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M1").WithArguments("I2.I1.M1", "I1.M1.set").WithLocation(10, 12), // (14,12): error CS0551: Explicit interface implementation 'I2.I1.M2' is missing accessor 'I1.M2.get' // int I1.M2 Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M2").WithArguments("I2.I1.M2", "I1.M2.get").WithLocation(14, 12), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.M1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1").WithLocation(20, 15), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.M2' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M2").WithLocation(20, 15), // (36,9): error CS0550: 'I4.I3.M1.set' adds an accessor not found in interface member 'I3.M1' // set => throw null; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I4.I3.M1.set", "I3.M1").WithLocation(36, 9), // (40,9): error CS0550: 'I4.I3.M2.get' adds an accessor not found in interface member 'I3.M2' // get => throw null; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I4.I3.M2.get", "I3.M2").WithLocation(40, 9), // (43,16): error CS0501: 'I4.I3.M3.get' must declare a body because it is not marked abstract, extern, or partial // int I3.M3 {get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I4.I3.M3.get").WithLocation(43, 16), // (43,21): error CS0501: 'I4.I3.M3.set' must declare a body because it is not marked abstract, extern, or partial // int I3.M3 {get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I4.I3.M3.set").WithLocation(43, 21), // (44,12): error CS8053: Instance properties in interfaces cannot have initializers. // int I3.M4 {get; set;} = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "M4").WithArguments("I4.I3.M4").WithLocation(44, 12), // (44,16): error CS0501: 'I4.I3.M4.get' must declare a body because it is not marked abstract, extern, or partial // int I3.M4 {get; set;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I4.I3.M4.get").WithLocation(44, 16), // (44,21): error CS0501: 'I4.I3.M4.set' must declare a body because it is not marked abstract, extern, or partial // int I3.M4 {get; set;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I4.I3.M4.set").WithLocation(44, 21) ); } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void PropertyImplementationInDerived_11() { var source1 = @" public interface I2 { internal int M1 {get;} } public interface I4 { int M1 {get; internal set;} } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { _ = i2.M1; i4.M1 = i4.M1; } } "; var source2 = @" public interface I1 : I2, I5 { int I2.M1 => Getter(); private int Getter() { System.Console.WriteLine(""I2.M1""); return 1; } int I4.M1 { get { System.Console.WriteLine(""I4.M1""); return 1; } set => System.Console.WriteLine(""I4.M1.set""); } } public interface I3 : I1 { } "; ValidatePropertyImplementationInDerived_11(source1, source2, // (4,12): error CS0122: 'I2.M1' is inaccessible due to its protection level // int I2.M1 => Getter(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1").WithLocation(4, 12), // (11,12): error CS0122: 'I4.M1.set' is inaccessible due to its protection level // int I4.M1 Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I4.M1.set").WithLocation(11, 12) ); } private void ValidatePropertyImplementationInDerived_11(string source1, string source2, params DiagnosticDescription[] expected) { var source3 = @" class Test1 : I1 { static void Main() { TestHelper.Test(new Test1(), new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidatePropertyImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 I4.M1.set ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationInDerived_01); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidatePropertyImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 I4.M1.set ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationInDerived_01); } var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); foreach (var reference in new[] { compilation4.ToMetadataReference(), compilation4.EmitToImageReference() }) { var compilation5 = CreateCompilation(source2 + source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidatePropertyImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics(expected); if (expected.Length == 0) { CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1 I4.M1 I4.M1.set ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidatePropertyImplementationInDerived_01); } } } [Fact] [WorkItem(20083, "https://github.com/dotnet/roslyn/issues/20083")] public void PropertyImplementationInDerived_12() { var source1 = @" public interface I1 { int M1 { get => throw null; set => throw null;} } public interface I2 : I1 { int I1.M1 { get { System.Console.WriteLine(""I2.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I2.I1.M1.set""); } } } public interface I3 : I1 { int I1.M1 { get { System.Console.WriteLine(""I3.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I3.I1.M1.set""); } } } public interface I4 : I1 { int I1.M1 { get { System.Console.WriteLine(""I4.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I4.I1.M1.set""); } } } public interface I5 : I2, I3 { int I1.M1 { get { System.Console.WriteLine(""I5.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I5.I1.M1.set""); } } } public interface I6 : I1, I2, I3, I5 {} "; var source4 = @" class Test5 : I2 {} class Test6 : I1, I2, I3, I5 {} class Test7 : I6 { static void Main() { I1 i1 = new Test5(); i1.M1 = i1.M1; i1 = new Test6(); i1.M1 = i1.M1; i1 = new Test7(); i1.M1 = i1.M1; } } "; var source5 = @" class Test8 : I2, I3 { int I1.M1 { get { System.Console.WriteLine(""Test8.I1.M1.get""); return 1; } set { System.Console.WriteLine(""Test8.I1.M1.set""); } } static void Main() { I1 i1 = new Test8(); i1.M1 = i1.M1; i1 = new Test9(); i1.M1 = i1.M1; i1 = new Test10(); i1.M1 = i1.M1; i1 = new Test11(); i1.M1 = i1.M1; i1 = new Test12(); i1.M1 = i1.M1; } } class Test9 : I7 { int I1.M1 { get { System.Console.WriteLine(""Test9.I1.M1.get""); return 1; } set { System.Console.WriteLine(""Test9.I1.M1.set""); } } } class Test10 : I1, I2, I3, I4 { public int M1 { get { System.Console.WriteLine(""Test10.M1.get""); return 1; } set { System.Console.WriteLine(""Test10.M1.set""); } } } class Test11 : I1, I2, I3, I5, I4 { public int M1 { get { System.Console.WriteLine(""Test11.M1.get""); return 1; } set { System.Console.WriteLine(""Test11.M1.set""); } } } class Test12 : I8 { public virtual int M1 { get { System.Console.WriteLine(""Test12.M1.get""); return 1; } set { System.Console.WriteLine(""Test12.M1.set""); } } } "; ValidatePropertyImplementationInDerived_12(source1, source4, source5, new DiagnosticDescription[] { // (2,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(2, 15), // (5,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test2 : I7 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I7").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(5, 15), // (8,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test3 : I1, I2, I3, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(8, 15), // (11,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I5.I1.M1', nor 'I4.I1.M1' are most specific. // class Test4 : I1, I2, I3, I5, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.M1", "I5.I1.M1", "I4.I1.M1").WithLocation(11, 15), // (14,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I5.I1.M1', nor 'I4.I1.M1' are most specific. // class Test5 : I8 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I8").WithArguments("I1.M1", "I5.I1.M1", "I4.I1.M1").WithLocation(14, 15) } ); } private void ValidatePropertyImplementationInDerived_12(string source1, string source4, string source5, DiagnosticDescription[] expected1, DiagnosticDescription[] expected2 = null) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = GetSingleProperty(i1); var i2 = FindType(m, "I2"); var i2m1 = GetSingleProperty(i2); var i5 = FindType(m, "I5"); var i5m1 = GetSingleProperty(i5); var i6 = FindType(m, "I6"); ValidateExplicitImplementation(i2m1); ValidateExplicitImplementation(i5m1); VerifyFindImplementationForInterfaceMemberSame(i1m1, i1, i1m1); VerifyFindImplementationForInterfaceMemberSame(i2m1, i2, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, i5, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, i6, i1m1); } CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var refs1 = new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }; var source2 = @" public interface I7 : I2, I3 {} public interface I8 : I1, I2, I3, I5, I4 {} "; var source3 = @" class Test1 : I2, I3 {} class Test2 : I7 {} class Test3 : I1, I2, I3, I4 {} class Test4 : I1, I2, I3, I5, I4 {} class Test5 : I8 {} "; foreach (var ref1 in refs1) { var compilation2 = CreateCompilation(source2, new[] { ref1 }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // According to LDM decision captured at https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-06-14.md, // we do not require interfaces to have a most specific implementation of all members. Therefore, there are no // errors in this compilation. compilation2.VerifyDiagnostics(); Validate2(compilation2.SourceModule); void Validate2(ModuleSymbol m) { Validate1(m); var i1 = FindType(m, "I1"); var i1m1 = GetSingleProperty(i1); var i7 = FindType(m, "I7"); var i8 = FindType(m, "I8"); VerifyFindImplementationForInterfaceMemberSame(null, i7, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i8, i1m1); } CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); compilation2 = CreateCompilation(source2, new[] { ref1 }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); Validate2(compilation2.SourceModule); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); var refs2 = new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }; var compilation4 = CreateCompilation(source4, new[] { ref1 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); Validate4(compilation4.SourceModule); void Validate4(ModuleSymbol m) { Validate1(m); var i1 = FindType(m, "I1"); var i1m1 = GetSingleProperty(i1); var i2 = FindType(m, "I2"); var i2m1 = GetSingleProperty(i2); var i5 = FindType(m, "I5"); var i5m1 = GetSingleProperty(i5); var test5 = FindType(m, "Test5"); var test6 = FindType(m, "Test6"); var test7 = FindType(m, "Test7"); VerifyFindImplementationForInterfaceMemberSame(i2m1, test5, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, test6, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, test7, i1m1); } CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.I1.M1.get I2.I1.M1.set I5.I1.M1.get I5.I1.M1.set I5.I1.M1.get I5.I1.M1.set " , verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate4); foreach (var ref2 in refs2) { var compilation3 = CreateCompilation(source3, new[] { ref1, ref2 }, options: TestOptions.DebugDll.WithConcurrentBuild(false), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(ref1 is CompilationReference ? expected1 : expected2 ?? expected1); Validate3(compilation3.SourceModule); void Validate3(ModuleSymbol m) { Validate1(m); Validate2(m); var i1 = FindType(m, "I1"); var i1m1 = GetSingleProperty(i1); var test1 = FindType(m, "Test1"); var test2 = FindType(m, "Test2"); var test3 = FindType(m, "Test3"); var test4 = FindType(m, "Test4"); var test5 = FindType(m, "Test5"); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test2, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test3, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test4, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test5, i1m1); } var compilation5 = CreateCompilation(source5, new[] { ref1, ref2 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics(); Validate5(compilation5.SourceModule); void Validate5(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = GetSingleProperty(i1); var test8 = FindType(m, "Test8"); var test9 = FindType(m, "Test9"); var test10 = FindType(m, "Test10"); var test11 = FindType(m, "Test11"); var test12 = FindType(m, "Test12"); VerifyFindImplementationForInterfaceMemberSame(GetSingleProperty(test8), test8, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleProperty(test9), test9, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleProperty(test10), test10, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleProperty(test11), test11, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleProperty(test12), test12, i1m1); } CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"Test8.I1.M1.get Test8.I1.M1.set Test9.I1.M1.get Test9.I1.M1.set Test10.M1.get Test10.M1.set Test11.M1.get Test11.M1.set Test12.M1.get Test12.M1.set ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate5); } } } [Fact] public void PropertyImplementationInDerived_13() { var source1 = @" public interface I1 { int M1 {get;} } public interface I2 : I1 { int I1.M1 => throw null; } public interface I3 : I1 { int I1.M1 => throw null; } "; var source2 = @" class Test1 : I2, I3 { public long M1 => 1; } "; ValidatePropertyImplementationInDerived_13(source1, source2, new DiagnosticDescription[] { // (2,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(2, 15), // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.M1'. 'Test1.M1' cannot implement 'I1.M1' because it does not have the matching return type of 'int'. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test1", "I1.M1", "Test1.M1", "int").WithLocation(2, 15) } ); } private void ValidatePropertyImplementationInDerived_13(string source1, string source2, DiagnosticDescription[] expected1, DiagnosticDescription[] expected2 = null) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(expected1); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics(expected2 ?? expected1); } [Fact] [WorkItem(20084, "https://github.com/dotnet/roslyn/issues/20084")] public void PropertyImplementationInDerived_14() { var source1 = @" public interface I1<T> { int M1 { get { System.Console.WriteLine(""I1.M1.get""); return 1; } set => System.Console.WriteLine(""I1.M1.set""); } } public interface I2<T> : I1<T> { int I1<T>.M1 { get { System.Console.WriteLine(""I2.I1.M1.get""); return 1; } set => System.Console.WriteLine(""I2.I1.M1.set""); } } public interface I3<T> : I1<T> {} "; var source2 = @" class Test1 : I1<int> { static void Main() { I1<int> i1Int = new Test1(); i1Int.M1 = i1Int.M1; I1<long> i1Long = new Test2(); i1Long.M1 = i1Long.M1; } } class Test2 : I2<long> {} "; ValidatePropertyImplementationInDerived_14(source1, source2); } private void ValidatePropertyImplementationInDerived_14(string source1, string source2) { var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = GetSingleProperty(i1); var i2 = FindType(m, "I2"); var i2m1 = GetSingleProperty(i2); var i2i1 = i2.InterfacesNoUseSiteDiagnostics().Single(); var i2i1m1 = GetSingleProperty(i2i1); var i3 = FindType(m, "I3"); var i3i1 = i3.InterfacesNoUseSiteDiagnostics().Single(); var i3i1m1 = GetSingleProperty(i3i1); VerifyFindImplementationForInterfaceMemberSame(i1m1, i1, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i2, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i2, i3i1m1); VerifyFindImplementationForInterfaceMemberSame(i2m1, i2, i2i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i3, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i3, i2i1m1); VerifyFindImplementationForInterfaceMemberEqual(i3i1m1, i3, i3i1m1); ValidateExplicitImplementation(i2m1); var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test1i1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)); var test1i1m1 = GetSingleProperty(i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32))); var test2 = m.GlobalNamespace.GetTypeMember("Test2"); var test2i1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)); var test2i1m1 = GetSingleProperty(i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64))); var test2i2 = i2.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)); var test2i2m1 = GetSingleProperty(i2.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64))); Assert.NotSame(test1i1, test1i1m1.ContainingType); Assert.NotSame(test2i1, test2i1m1.ContainingType); Assert.NotSame(test2i2, test2i2m1.ContainingType); VerifyFindImplementationForInterfaceMemberSame(null, test1i1, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test1i1m1, test1i1, test1i1m1); VerifyFindImplementationForInterfaceMemberEqual(test2i1m1, test2i1, test2i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test2i2, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test2i2m1, test2i2, test2i1m1); ValidateExplicitImplementation(test2i2m1); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test1i1m1, test1, test1i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test2, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test2i2m1, test2, test2i1m1); } CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1.get I1.M1.set I2.I1.M1.get I2.I1.M1.set ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1.get I1.M1.set I2.I1.M1.get I2.I1.M1.set ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1.get I1.M1.set I2.I1.M1.get I2.I1.M1.set ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); } [Fact] public void PropertyImplementationInDerived_15() { var source1 = @" public interface I2 { virtual int M1 {get => throw null; private set => throw null;} } public interface I4 { int M1 {set => throw null; private get => throw null;} } public interface I5 : I4 { } public interface I1 : I2, I5 { int I2.M1 { get { System.Console.WriteLine(""I2.M1""); return 1; } } int I4.M1 { set => System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source2 = @" class Test1 : I1 { static void Main() { I2 i2 = new Test1(); _ = i2.M1; I4 i4 = new Test1(); i4.M1 = 0; } } "; ValidatePropertyImplementationInDerived_01(source1, source2); } [Fact] public void PropertyImplementationInDerived_16() { var source1 = @" public interface I2 { int M1 {get; set;} } public interface I4 { int M1 {get; set;} } public interface I1 : I2, I4 { int I2.M1 { protected get => throw null; set => throw null; } protected int I4.M1 { get => throw null; set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (16,19): error CS0106: The modifier 'protected' is not valid for this item // protected get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("protected").WithLocation(16, 19), // (19,22): error CS0106: The modifier 'protected' is not valid for this item // protected int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected").WithLocation(19, 22) ); } [Fact] public void PropertyImplementationInDerived_17() { var source1 = @" public interface I2 { int M1 {get; set;} } public interface I4 { int M1 {get; set;} } public interface I1 : I2, I4 { int I2.M1 { get => throw null; protected internal set => throw null; } protected internal int I4.M1 { get => throw null; set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (17,28): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("protected internal").WithLocation(17, 28), // (19,31): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected internal").WithLocation(19, 31) ); } [Fact] public void PropertyImplementationInDerived_18() { var source1 = @" public interface I2 { int M1 {get; set;} } public interface I4 { int M1 {get; set;} } public interface I1 : I2, I4 { int I2.M1 { private protected get => throw null; set => throw null; } private protected int I4.M1 { get => throw null; set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (16,27): error CS0106: The modifier 'private protected' is not valid for this item // private protected get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("private protected").WithLocation(16, 27), // (19,30): error CS0106: The modifier 'private protected' is not valid for this item // private protected int I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("private protected").WithLocation(19, 30) ); } [Fact] public void PropertyImplementationInDerived_19() { var source1 = @" #nullable enable public interface I1<T> { int M1 {get; set;} } public interface I2 : I1<string> { } public interface I3 : I2, I1<string?> { int I1<string>.M1 { get => throw null!; set => throw null!; } int I1<string?>.M1 { get => throw null!; set => throw null!; } } "; var source2 = @" #nullable enable class Test1 : I3 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (13,18): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'I3' with different nullability of reference types. // public interface I3 : I2, I1<string?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "I3").WithArguments("I1<string?>", "I3").WithLocation(13, 18), // (13,18): error CS8646: 'I1<string>.M1' is explicitly implemented more than once. // public interface I3 : I2, I1<string?> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "I3").WithArguments("I1<string>.M1").WithLocation(13, 18), // (13,18): error CS8646: 'I1<string?>.M1' is explicitly implemented more than once. // public interface I3 : I2, I1<string?> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "I3").WithArguments("I1<string?>.M1").WithLocation(13, 18), // (21,21): error CS0102: The type 'I3' already contains a definition for 'I1<System.String>.M1' // int I1<string?>.M1 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "M1").WithArguments("I3", "I1<System.String>.M1").WithLocation(21, 21) ); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,7): warning CS8645: 'I1<string?>' is already listed in the interface list on type 'Test1' with different nullability of reference types. // class Test1 : I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Test1").WithArguments("I1<string?>", "Test1").WithLocation(4, 7), // (4,15): error CS0535: 'Test1' does not implement interface member 'I1<string>.M1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1<string>.M1").WithLocation(4, 15), // (4,15): error CS0535: 'Test1' does not implement interface member 'I1<string?>.M1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1<string?>.M1").WithLocation(4, 15) ); var test1 = compilation2.GetTypeByMetadataName("Test1"); Assert.Equal(new[] { "I3", "I2", "I1<System.String>", "I1<System.String?>" }, test1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString())); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[2].GetMember("M1"))); Assert.Null(test1.FindImplementationForInterfaceMember(test1.AllInterfacesNoUseSiteDiagnostics[3].GetMember("M1"))); } [Fact] public void PropertyImplementationInDerived_20() { var source1 = @" public interface I2 { protected int M1 {get;} public static void Test(I2 i2) { _ = i2.M1; } } public interface I4 { int M1 {get; protected set;} public static void Test(I4 i4) { i4.M1 = i4.M1; } } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { I2.Test(i2); I4.Test(i4); } } "; var source2 = @" public interface I1 : I2, I5 { int I2.M1 => Getter(); private int Getter() { System.Console.WriteLine(""I2.M1""); return 1; } int I4.M1 { get { System.Console.WriteLine(""I4.M1""); return 1; } set => System.Console.WriteLine(""I4.M1.set""); } } public interface I3 : I1 { } "; ValidatePropertyImplementationInDerived_11(source1, source2); } [Fact] public void PropertyImplementationInDerived_21() { var source1 = @" public interface I2 { protected internal int M1 {get;} public static void Test(I2 i2) { _ = i2.M1; } } public interface I4 { int M1 {get; protected internal set;} public static void Test(I4 i4) { i4.M1 = i4.M1; } } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { I2.Test(i2); I4.Test(i4); } } "; var source2 = @" public interface I1 : I2, I5 { int I2.M1 => Getter(); private int Getter() { System.Console.WriteLine(""I2.M1""); return 1; } int I4.M1 { get { System.Console.WriteLine(""I4.M1""); return 1; } set => System.Console.WriteLine(""I4.M1.set""); } } public interface I3 : I1 { } "; ValidatePropertyImplementationInDerived_11(source1, source2); } [Fact] public void PropertyImplementationInDerived_22() { var source1 = @" public interface I2 { private protected int M1 {get;} public static void Test(I2 i2) { _ = i2.M1; } } public interface I4 { int M1 {get; private protected set;} public static void Test(I4 i4) { i4.M1 = i4.M1; } } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { I2.Test(i2); I4.Test(i4); } } "; var source2 = @" public interface I1 : I2, I5 { int I2.M1 => Getter(); private int Getter() { System.Console.WriteLine(""I2.M1""); return 1; } int I4.M1 { get { System.Console.WriteLine(""I4.M1""); return 1; } set => System.Console.WriteLine(""I4.M1.set""); } } public interface I3 : I1 { } "; ValidatePropertyImplementationInDerived_11(source1, source2, // (4,12): error CS0122: 'I2.M1' is inaccessible due to its protection level // int I2.M1 => Getter(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1").WithLocation(4, 12), // (11,12): error CS0122: 'I4.M1.set' is inaccessible due to its protection level // int I4.M1 Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I4.M1.set").WithLocation(11, 12) ); } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void EventImplementationInDerived_01() { var source1 = @" public interface I2 { event System.Action M1; } public interface I4 { event System.Action M1; } public interface I5 : I4 { } public interface I1 : I2, I5 { event System.Action I2.M1 { add { System.Console.WriteLine(""I2.M1.add""); } remove { System.Console.WriteLine(""I2.M1.remove""); } } event System.Action I4.M1 { add => System.Console.WriteLine(""I4.M1.add""); remove => System.Console.WriteLine(""I4.M1.remove""); } } public interface I3 : I1 { } "; var source2 = @" class Test1 : I1 { static void Main() { I2 i2 = new Test1(); i2.M1 += null; i2.M1 -= null; I4 i4 = new Test1(); i4.M1 += null; i4.M1 -= null; } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateEventImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); } private static void ValidateEventImplementationInDerived_01(ModuleSymbol m) { ValidateEventImplementationInDerived_01(m, i4M1IsAbstract: false); } private static void ValidateEventImplementationInDerived_01(ModuleSymbol m, bool i4M1IsAbstract) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1 = test1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I1").Single(); var i1i2m1 = i1.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I2.")).Single(); var i1i4m1 = i1.GetMembers().OfType<EventSymbol>().Where(p => p.Name.StartsWith("I4.")).Single(); var i2 = i1.InterfacesNoUseSiteDiagnostics().Where(i => i.Name == "I2").Single(); var i2m1 = i2.GetMembers().OfType<EventSymbol>().Single(); var i4 = i1.AllInterfacesNoUseSiteDiagnostics.Where(i => i.Name == "I4").Single(); var i4m1 = i4.GetMembers().OfType<EventSymbol>().Single(); var i3 = i1.ContainingNamespace.GetTypeMember("I3"); Assert.True(i1.IsAbstract); Assert.True(i1.IsMetadataAbstract); ValidateExplicitImplementation(i1i2m1); ValidateExplicitImplementation(i1i4m1, i4M1IsAbstract); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1i2m1); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1i4m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, test1, i2m1); VerifyFindImplementationForInterfaceMemberSame(i4M1IsAbstract ? null : i1i4m1, test1, i4m1); VerifyFindImplementationForInterfaceMemberSame(null, i1, i1i2m1); VerifyFindImplementationForInterfaceMemberSame(null, i1, i1i4m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, i1, i2m1); VerifyFindImplementationForInterfaceMemberSame(i4M1IsAbstract ? null : i1i4m1, i1, i4m1); VerifyFindImplementationForInterfaceMemberSame(null, i2, i2m1); VerifyFindImplementationForInterfaceMemberSame(null, i4, i4m1); VerifyFindImplementationForInterfaceMemberSame(i1i2m1, i3, i2m1); VerifyFindImplementationForInterfaceMemberSame(i4M1IsAbstract ? null : i1i4m1, i3, i4m1); } private static void VerifyFindImplementationForInterfaceMemberSame(EventSymbol expected, NamedTypeSymbol implementingType, EventSymbol interfaceEvent) { Assert.Same(expected, implementingType.FindImplementationForInterfaceMember(interfaceEvent)); ValidateAccessor(expected?.AddMethod, interfaceEvent.AddMethod); ValidateAccessor(expected?.RemoveMethod, interfaceEvent.RemoveMethod); void ValidateAccessor(MethodSymbol accessor, MethodSymbol interfaceAccessor) { if ((object)interfaceAccessor != null) { Assert.Same(accessor, implementingType.FindImplementationForInterfaceMember(interfaceAccessor)); } else { Assert.Null(accessor); } } } private static void VerifyFindImplementationForInterfaceMemberEqual(EventSymbol expected, NamedTypeSymbol implementingType, EventSymbol interfaceEvent) { Assert.Equal(expected, implementingType.FindImplementationForInterfaceMember(interfaceEvent)); ValidateAccessor(expected?.AddMethod, interfaceEvent.AddMethod); ValidateAccessor(expected?.RemoveMethod, interfaceEvent.RemoveMethod); void ValidateAccessor(MethodSymbol accessor, MethodSymbol interfaceAccessor) { if ((object)interfaceAccessor != null) { Assert.Equal(accessor, implementingType.FindImplementationForInterfaceMember(interfaceAccessor)); } else { Assert.Null(accessor); } } } private static void ValidateExplicitImplementation(EventSymbol m1, bool isAbstract = false) { Assert.Equal(isAbstract, m1.IsAbstract); Assert.False(m1.IsVirtual); Assert.Equal(isAbstract, m1.IsSealed); Assert.False(m1.IsStatic); Assert.False(m1.IsExtern); Assert.False(m1.IsOverride); Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility); ValidateAccessor(m1.AddMethod, isAbstract); ValidateAccessor(m1.RemoveMethod, isAbstract); static void ValidateAccessor(MethodSymbol accessor, bool isAbstract) { if ((object)accessor != null) { ValidateExplicitImplementation(accessor, isAbstract); } } } [Fact] public void EventImplementationInDerived_02() { var source1 = @" public interface I2 { event System.Action M1; } public interface I4 { event System.Action M1; } public interface I1 : I2, I4 { event System.Action I2.M1 { add => throw null; remove => throw null; } event System.Action I4.M1 { add => throw null; remove => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (16,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // add => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(16, 9), // (17,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // remove => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(17, 9), // (22,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // add => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "add").WithArguments("default interface implementation", "8.0").WithLocation(22, 9), // (23,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // remove => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "remove").WithArguments("default interface implementation", "8.0").WithLocation(23, 9) ); ValidateEventImplementationInDerived_01(compilation1.SourceModule); var source2 = @" public interface I3 : I1 { } class Test1 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (6,15): error CS8506: 'I1.I2.M1.remove' cannot implement interface member 'I2.M1.remove' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1.remove", "I2.M1.remove", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15), // (6,15): error CS8506: 'I1.I2.M1.add' cannot implement interface member 'I2.M1.add' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1.add", "I2.M1.add", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15), // (6,15): error CS8506: 'I1.I4.M1.remove' cannot implement interface member 'I4.M1.remove' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1.remove", "I4.M1.remove", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15), // (6,15): error CS8506: 'I1.I4.M1.add' cannot implement interface member 'I4.M1.add' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1.add", "I4.M1.add", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15) ); ValidateEventImplementationInDerived_01(compilation2.SourceModule); } [Fact] public void EventImplementationInDerived_03() { var source1 = @" public interface I2 { event System.Action M1; } public interface I4 { event System.Action M1; } public interface I1 : I2, I4 { event System.Action I2.M1 { add => throw null; remove => throw null; } event System.Action I4.M1 { add => throw null; remove => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular, skipUsesIsNullable: true); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (16,9): error CS8501: Target runtime doesn't support default interface implementation. // add => throw null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(16, 9), // (17,9): error CS8501: Target runtime doesn't support default interface implementation. // remove => throw null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(17, 9), // (22,9): error CS8501: Target runtime doesn't support default interface implementation. // add => throw null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "add").WithLocation(22, 9), // (23,9): error CS8501: Target runtime doesn't support default interface implementation. // remove => throw null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "remove").WithLocation(23, 9) ); ValidateEventImplementationInDerived_01(compilation1.SourceModule); var source2 = @" public interface I3 : I1 { } class Test1 : I1 {} "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (6,15): error CS8502: 'I1.I2.M1.remove' cannot implement interface member 'I2.M1.remove' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1.remove", "I2.M1.remove", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I2.M1.add' cannot implement interface member 'I2.M1.add' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.M1.add", "I2.M1.add", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I4.M1.remove' cannot implement interface member 'I4.M1.remove' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1.remove", "I4.M1.remove", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I4.M1.add' cannot implement interface member 'I4.M1.add' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.M1.add", "I4.M1.add", "Test1").WithLocation(6, 15) ); } [Fact] public void EventImplementationInDerived_04() { var source1 = @" public interface I2 { event System.Action M1; } public interface I4 { event System.Action M1; } public interface I1 : I2, I4 { event System.Action I2.M1 { add; remove; } event System.Action I4.M1 { add; remove {} } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (16,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(16, 12), // (17,15): error CS0073: An add or remove accessor must have a body // remove; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(17, 15), // (21,12): error CS0073: An add or remove accessor must have a body // add; Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(21, 12) ); ValidateEventImplementationInDerived_01(compilation1.SourceModule); } [Fact] public void EventImplementationInDerived_05() { var source1 = @" public interface I2 { event System.Action M1; } public interface I1 { event System.Action I2.M1 { add => throw null; remove => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (9,25): error CS0540: 'I1.I2.M1': containing type does not implement interface 'I2' // event System.Action I2.M1 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.I2.M1", "I2").WithLocation(9, 25) ); } [Fact] public void EventImplementationInDerived_06() { var source1 = @" public interface I2 { event System.Action M1; } public interface I4 { event System.Action M1; } public interface I1 : I2, I4 { public static event System.Action I2.M1 { add => throw null; remove => throw null; } internal virtual event System.Action I4.M1 { add => throw null; remove => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,42): error CS0106: The modifier 'static' is not valid for this item // public static event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("static").WithLocation(14, 42), // (14,42): error CS0106: The modifier 'public' is not valid for this item // public static event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("public").WithLocation(14, 42), // (19,45): error CS0106: The modifier 'internal' is not valid for this item // internal virtual event System.Action I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("internal").WithLocation(19, 45), // (19,45): error CS0106: The modifier 'virtual' is not valid for this item // internal virtual event System.Action I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("virtual").WithLocation(19, 45) ); ValidateEventImplementationInDerived_01(compilation1.SourceModule); } [Fact] public void EventImplementationInDerived_07() { var source1 = @" public interface I2 { event System.Action M1; } public interface I4 { event System.Action M1; } public interface I1 : I2, I4 { private sealed event System.Action I2.M1 { add => throw null; remove => throw null; } protected abstract event System.Action I4.M1 { add => throw null; remove => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,43): error CS0106: The modifier 'sealed' is not valid for this item // private sealed event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("sealed").WithLocation(14, 43), // (14,43): error CS0106: The modifier 'private' is not valid for this item // private sealed event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("private").WithLocation(14, 43), // (19,47): error CS0106: The modifier 'protected' is not valid for this item // protected abstract event System.Action I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected").WithLocation(19, 47), // (20,5): error CS8712: 'I1.I4.M1': abstract event cannot use event accessor syntax // { Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.I4.M1").WithLocation(20, 5), // (30,15): error CS0535: 'Test1' does not implement interface member 'I4.M1' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I4.M1").WithLocation(30, 15) ); ValidateEventImplementationInDerived_01(compilation1.SourceModule, i4M1IsAbstract: true); } [Fact] public void EventImplementationInDerived_08() { var source1 = @" public interface I2 { event System.Action M1; } public interface I4 { event System.Action M1; } public interface I1 : I2, I4 { private protected extern event System.Action I2.M1 { add => throw null; remove => throw null; } internal protected override event System.Action I4.M1 { add => throw null; remove => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (14,53): error CS0106: The modifier 'private protected' is not valid for this item // private protected extern event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("private protected").WithLocation(14, 53), // (14,53): error CS0106: The modifier 'extern' is not valid for this item // private protected extern event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("extern").WithLocation(14, 53), // (19,56): error CS0106: The modifier 'protected internal' is not valid for this item // internal protected override event System.Action I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("protected internal").WithLocation(19, 56), // (19,56): error CS0106: The modifier 'override' is not valid for this item // internal protected override event System.Action I4.M1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("override").WithLocation(19, 56) ); ValidateEventImplementationInDerived_01(compilation1.SourceModule); } [Fact] public void EventImplementationInDerived_10() { var source1 = @" public interface I1 { event System.Action M1; event System.Action M2; } public interface I2 : I1 { event System.Action I1.M1 { add => throw null; } event System.Action I1.M2 { remove => throw null; } } class Test1 : I2 {} public interface I3 { event System.Action M1; } public interface I4 : I3 { event System.Action I3.M1; } class Test2 : I4 {} public interface I5 : I3 { event System.Action I3.M1 } class Test3 : I5 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (30,28): error CS0071: An explicit interface implementation of an event must use event accessor syntax // event System.Action I3.M1; Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "M1").WithLocation(30, 28), // (10,28): error CS0065: 'I2.I1.M1': event property must have both add and remove accessors // event System.Action I1.M1 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M1").WithArguments("I2.I1.M1").WithLocation(10, 28), // (14,28): error CS0065: 'I2.I1.M2': event property must have both add and remove accessors // event System.Action I1.M2 Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M2").WithArguments("I2.I1.M2").WithLocation(14, 28), // (33,15): error CS0535: 'Test2' does not implement interface member 'I3.M1' // class Test2 : I4 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I4").WithArguments("Test2", "I3.M1").WithLocation(33, 15), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.M1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1").WithLocation(20, 15), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.M2' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M2").WithLocation(20, 15), // (38,27): error CS0071: An explicit interface implementation of an event must use event accessor syntax // event System.Action I3.M1 Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, ".").WithLocation(38, 27), // (41,15): error CS0535: 'Test3' does not implement interface member 'I3.M1' // class Test3 : I5 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I5").WithArguments("Test3", "I3.M1").WithLocation(41, 15) ); } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void EventImplementationInDerived_11() { var source1 = @" public interface I2 { internal event System.Action M1; } public interface I4 { event System.Action M1; } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { i2.M1 += null; i2.M1 -= null; i4.M1 += null; i4.M1 -= null; } } "; var source2 = @" public interface I1 : I2, I5 { event System.Action I2.M1 { add { System.Console.WriteLine(""I2.M1.add""); } remove => System.Console.WriteLine(""I2.M1.remove""); } event System.Action I4.M1 { add { System.Console.WriteLine(""I4.M1.add""); } remove => System.Console.WriteLine(""I4.M1.remove""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { TestHelper.Test(new Test1(), new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateEventImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); var compilation2 = CreateCompilation(source3, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); var compilation3 = CreateCompilation(source3, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); var compilation5 = CreateCompilation(source2 + source3, new[] { compilation4.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics( // (4,28): error CS0122: 'I2.M1' is inaccessible due to its protection level // event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1").WithLocation(4, 28) ); var compilation6 = CreateCompilation(source2 + source3, new[] { compilation4.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation6.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation6.SourceModule); compilation6.VerifyDiagnostics( // (4,28): error CS0122: 'I2.M1' is inaccessible due to its protection level // event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1").WithLocation(4, 28) ); } [Fact] [WorkItem(20083, "https://github.com/dotnet/roslyn/issues/20083")] public void EventImplementationInDerived_12() { var source1 = @" public interface I1 { event System.Action M1 { add => throw null; remove => throw null;} } public interface I2 : I1 { event System.Action I1.M1 { add { System.Console.WriteLine(""I2.I1.M1.add""); } remove { System.Console.WriteLine(""I2.I1.M1.remove""); } } } public interface I3 : I1 { event System.Action I1.M1 { add { System.Console.WriteLine(""I3.I1.M1.add""); } remove { System.Console.WriteLine(""I3.I1.M1.remove""); } } } public interface I4 : I1 { event System.Action I1.M1 { add { System.Console.WriteLine(""I4.I1.M1.add""); } remove { System.Console.WriteLine(""I4.I1.M1.remove""); } } } public interface I5 : I2, I3 { event System.Action I1.M1 { add { System.Console.WriteLine(""I5.I1.M1.add""); } remove { System.Console.WriteLine(""I5.I1.M1.remove""); } } } public interface I6 : I1, I2, I3, I5 {} "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate1(compilation1.SourceModule); void Validate1(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = GetSingleEvent(i1); var i2 = FindType(m, "I2"); var i2m1 = GetSingleEvent(i2); var i5 = FindType(m, "I5"); var i5m1 = GetSingleEvent(i5); var i6 = FindType(m, "I6"); ValidateExplicitImplementation(i2m1); ValidateExplicitImplementation(i5m1); VerifyFindImplementationForInterfaceMemberSame(i1m1, i1, i1m1); VerifyFindImplementationForInterfaceMemberSame(i2m1, i2, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, i5, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, i6, i1m1); } CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate1); var refs1 = new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }; var source2 = @" public interface I7 : I2, I3 {} public interface I8 : I1, I2, I3, I5, I4 {} "; var source3 = @" class Test1 : I2, I3 {} class Test2 : I7 {} class Test3 : I1, I2, I3, I4 {} class Test4 : I1, I2, I3, I5, I4 {} class Test5 : I8 {} "; var source4 = @" class Test5 : I2 {} class Test6 : I1, I2, I3, I5 {} class Test7 : I6 { static void Main() { I1 i1 = new Test5(); i1.M1 += null; i1.M1 -= null; i1 = new Test6(); i1.M1 += null; i1.M1 -= null; i1 = new Test7(); i1.M1 += null; i1.M1 -= null; } } "; var source5 = @" class Test8 : I2, I3 { event System.Action I1.M1 { add { System.Console.WriteLine(""Test8.I1.M1.add""); } remove { System.Console.WriteLine(""Test8.I1.M1.remove""); } } static void Main() { I1 i1 = new Test8(); i1.M1 += null; i1.M1 -= null; i1 = new Test9(); i1.M1 += null; i1.M1 -= null; i1 = new Test10(); i1.M1 += null; i1.M1 -= null; i1 = new Test11(); i1.M1 += null; i1.M1 -= null; i1 = new Test12(); i1.M1 += null; i1.M1 -= null; } } class Test9 : I7 { event System.Action I1.M1 { add { System.Console.WriteLine(""Test9.I1.M1.add""); } remove { System.Console.WriteLine(""Test9.I1.M1.remove""); } } } class Test10 : I1, I2, I3, I4 { public event System.Action M1 { add { System.Console.WriteLine(""Test10.M1.add""); } remove { System.Console.WriteLine(""Test10.M1.remove""); } } } class Test11 : I1, I2, I3, I5, I4 { public event System.Action M1 { add { System.Console.WriteLine(""Test11.M1.add""); } remove { System.Console.WriteLine(""Test11.M1.remove""); } } } class Test12 : I8 { public virtual event System.Action M1 { add { System.Console.WriteLine(""Test12.M1.add""); } remove { System.Console.WriteLine(""Test12.M1.remove""); } } } "; foreach (var ref1 in refs1) { var compilation2 = CreateCompilation(source2, new[] { ref1 }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); // According to LDM decision captured at https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-06-14.md, // we do not require interfaces to have a most specific implementation of all members. Therefore, there are no // errors in this compilation. compilation2.VerifyDiagnostics(); Validate2(compilation2.SourceModule); void Validate2(ModuleSymbol m) { Validate1(m); var i1 = FindType(m, "I1"); var i1m1 = GetSingleEvent(i1); var i7 = FindType(m, "I7"); var i8 = FindType(m, "I8"); VerifyFindImplementationForInterfaceMemberSame(null, i7, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i8, i1m1); } CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); compilation2 = CreateCompilation(source2, new[] { ref1 }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics(); Validate2(compilation2.SourceModule); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate2); var refs2 = new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }; var compilation4 = CreateCompilation(source4, new[] { ref1 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); Validate4(compilation4.SourceModule); void Validate4(ModuleSymbol m) { Validate1(m); var i1 = FindType(m, "I1"); var i1m1 = GetSingleEvent(i1); var i2 = FindType(m, "I2"); var i2m1 = GetSingleEvent(i2); var i5 = FindType(m, "I5"); var i5m1 = GetSingleEvent(i5); var test5 = FindType(m, "Test5"); var test6 = FindType(m, "Test6"); var test7 = FindType(m, "Test7"); VerifyFindImplementationForInterfaceMemberSame(i2m1, test5, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, test6, i1m1); VerifyFindImplementationForInterfaceMemberSame(i5m1, test7, i1m1); } CompileAndVerify(compilation4, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.I1.M1.add I2.I1.M1.remove I5.I1.M1.add I5.I1.M1.remove I5.I1.M1.add I5.I1.M1.remove " , verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate4); foreach (var ref2 in refs2) { var compilation3 = CreateCompilation(source3, new[] { ref1, ref2 }, options: TestOptions.DebugDll.WithConcurrentBuild(false), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(2, 15), // (5,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test2 : I7 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I7").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(5, 15), // (8,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test3 : I1, I2, I3, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(8, 15), // (11,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I5.I1.M1', nor 'I4.I1.M1' are most specific. // class Test4 : I1, I2, I3, I5, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.M1", "I5.I1.M1", "I4.I1.M1").WithLocation(11, 15), // (14,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I5.I1.M1', nor 'I4.I1.M1' are most specific. // class Test5 : I8 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I8").WithArguments("I1.M1", "I5.I1.M1", "I4.I1.M1").WithLocation(14, 15) ); Validate3(compilation3.SourceModule); void Validate3(ModuleSymbol m) { Validate1(m); Validate2(m); var i1 = FindType(m, "I1"); var i1m1 = GetSingleEvent(i1); var test1 = FindType(m, "Test1"); var test2 = FindType(m, "Test2"); var test3 = FindType(m, "Test3"); var test4 = FindType(m, "Test4"); var test5 = FindType(m, "Test5"); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test2, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test3, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test4, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test5, i1m1); } var compilation5 = CreateCompilation(source5, new[] { ref1, ref2 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation5.VerifyDiagnostics(); Validate5(compilation5.SourceModule); void Validate5(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = GetSingleEvent(i1); var test8 = FindType(m, "Test8"); var test9 = FindType(m, "Test9"); var test10 = FindType(m, "Test10"); var test11 = FindType(m, "Test11"); var test12 = FindType(m, "Test12"); VerifyFindImplementationForInterfaceMemberSame(GetSingleEvent(test8), test8, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleEvent(test9), test9, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleEvent(test10), test10, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleEvent(test11), test11, i1m1); VerifyFindImplementationForInterfaceMemberSame(GetSingleEvent(test12), test12, i1m1); } CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"Test8.I1.M1.add Test8.I1.M1.remove Test9.I1.M1.add Test9.I1.M1.remove Test10.M1.add Test10.M1.remove Test11.M1.add Test11.M1.remove Test12.M1.add Test12.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate5); } } } [Fact] public void EventImplementationInDerived_13() { var source1 = @" public interface I1 { event System.Action M1; } public interface I2 : I1 { event System.Action I1.M1 { add => throw null; remove => throw null;} } public interface I3 : I1 { event System.Action I1.M1 { add => throw null; remove => throw null;} } "; var source2 = @" class Test1 : I2, I3 { public event System.Action<object> M1 { add => throw null; remove => throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation2.VerifyDiagnostics( // (2,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(2, 15), // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.M1'. 'Test1.M1' cannot implement 'I1.M1' because it does not have the matching return type of 'Action'. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test1", "I1.M1", "Test1.M1", "System.Action").WithLocation(2, 15) ); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation3.VerifyDiagnostics( // (2,15): error CS8505: Interface member 'I1.M1' does not have a most specific implementation. Neither 'I2.I1.M1', nor 'I3.I1.M1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1", "I2.I1.M1", "I3.I1.M1").WithLocation(2, 15), // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.M1'. 'Test1.M1' cannot implement 'I1.M1' because it does not have the matching return type of 'Action'. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test1", "I1.M1", "Test1.M1", "System.Action").WithLocation(2, 15) ); } [Fact] [WorkItem(20084, "https://github.com/dotnet/roslyn/issues/20084")] public void EventImplementationInDerived_14() { var source1 = @" public interface I1<T> { event System.Action M1 { add { System.Console.WriteLine(""I1.M1.add""); } remove => System.Console.WriteLine(""I1.M1.remove""); } } public interface I2<T> : I1<T> { event System.Action I1<T>.M1 { add { System.Console.WriteLine(""I2.I1.M1.add""); } remove => System.Console.WriteLine(""I2.I1.M1.remove""); } } public interface I3<T> : I1<T> {} "; var source2 = @" class Test1 : I1<int> { static void Main() { I1<int> i1Int = new Test1(); i1Int.M1 += null; i1Int.M1 -= null; I1<long> i1Long = new Test2(); i1Long.M1 += null; i1Long.M1 -= null; } } class Test2 : I2<long> {} "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); Validate(compilation1.SourceModule); void Validate(ModuleSymbol m) { var i1 = FindType(m, "I1"); var i1m1 = GetSingleEvent(i1); var i2 = FindType(m, "I2"); var i2m1 = GetSingleEvent(i2); var i2i1 = i2.InterfacesNoUseSiteDiagnostics().Single(); var i2i1m1 = GetSingleEvent(i2i1); var i3 = FindType(m, "I3"); var i3i1 = i3.InterfacesNoUseSiteDiagnostics().Single(); var i3i1m1 = GetSingleEvent(i3i1); VerifyFindImplementationForInterfaceMemberSame(i1m1, i1, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i2, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i2, i3i1m1); VerifyFindImplementationForInterfaceMemberSame(i2m1, i2, i2i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i3, i1m1); VerifyFindImplementationForInterfaceMemberSame(null, i3, i2i1m1); VerifyFindImplementationForInterfaceMemberEqual(i3i1m1, i3, i3i1m1); ValidateExplicitImplementation(i2m1); var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test1i1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)); var test1i1m1 = GetSingleEvent(i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32))); var test2 = m.GlobalNamespace.GetTypeMember("Test2"); var test2i1 = i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)); var test2i1m1 = GetSingleEvent(i1.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64))); var test2i2 = i2.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64)); var test2i2m1 = GetSingleEvent(i2.Construct(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int64))); Assert.NotSame(test1i1, test1i1m1.ContainingType); Assert.NotSame(test2i1, test2i1m1.ContainingType); Assert.NotSame(test2i2, test2i2m1.ContainingType); VerifyFindImplementationForInterfaceMemberSame(null, test1i1, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test1i1m1, test1i1, test1i1m1); VerifyFindImplementationForInterfaceMemberEqual(test2i1m1, test2i1, test2i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test2i2, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test2i2m1, test2i2, test2i1m1); ValidateExplicitImplementation(test2i2m1); VerifyFindImplementationForInterfaceMemberSame(null, test1, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test1i1m1, test1, test1i1m1); VerifyFindImplementationForInterfaceMemberSame(null, test2, i1m1); VerifyFindImplementationForInterfaceMemberEqual(test2i2m1, test2, test2i1m1); } CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1.add I1.M1.remove I2.I1.M1.add I2.I1.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1.add I1.M1.remove I2.I1.M1.add I2.I1.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation3.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1.M1.add I1.M1.remove I2.I1.M1.add I2.I1.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); } [Fact] public void EventImplementationInDerived_15() { var source1 = @" public interface I2 { protected event System.Action M1; public static void Test(I2 i2) { i2.M1 += null; i2.M1 -= null; } } public interface I4 { event System.Action M1; } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { I2.Test(i2); i4.M1 += null; i4.M1 -= null; } } "; var source2 = @" public interface I1 : I2, I5 { event System.Action I2.M1 { add { System.Console.WriteLine(""I2.M1.add""); } remove => System.Console.WriteLine(""I2.M1.remove""); } event System.Action I4.M1 { add { System.Console.WriteLine(""I4.M1.add""); } remove => System.Console.WriteLine(""I4.M1.remove""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { TestHelper.Test(new Test1(), new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateEventImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); } var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); foreach (var reference in new[] { compilation4.ToMetadataReference(), compilation4.EmitToImageReference() }) { var compilation5 = CreateCompilation(source2 + source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics(); CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); } } [Fact] public void EventImplementationInDerived_16() { var source1 = @" public interface I2 { protected internal event System.Action M1; public static void Test(I2 i2) { i2.M1 += null; i2.M1 -= null; } } public interface I4 { event System.Action M1; } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { I2.Test(i2); i4.M1 += null; i4.M1 -= null; } } "; var source2 = @" public interface I1 : I2, I5 { event System.Action I2.M1 { add { System.Console.WriteLine(""I2.M1.add""); } remove => System.Console.WriteLine(""I2.M1.remove""); } event System.Action I4.M1 { add { System.Console.WriteLine(""I4.M1.add""); } remove => System.Console.WriteLine(""I4.M1.remove""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { TestHelper.Test(new Test1(), new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateEventImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); } var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); foreach (var reference in new[] { compilation4.ToMetadataReference(), compilation4.EmitToImageReference() }) { var compilation5 = CreateCompilation(source2 + source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics(); CompileAndVerify(compilation5, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); } } [Fact] public void EventImplementationInDerived_17() { var source1 = @" public interface I2 { private protected event System.Action M1; public static void Test(I2 i2) { i2.M1 += null; i2.M1 -= null; } } public interface I4 { event System.Action M1; } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { I2.Test(i2); i4.M1 += null; i4.M1 -= null; } } "; var source2 = @" public interface I1 : I2, I5 { event System.Action I2.M1 { add { System.Console.WriteLine(""I2.M1.add""); } remove => System.Console.WriteLine(""I2.M1.remove""); } event System.Action I4.M1 { add { System.Console.WriteLine(""I4.M1.add""); } remove => System.Console.WriteLine(""I4.M1.remove""); } } public interface I3 : I1 { } "; var source3 = @" class Test1 : I1 { static void Main() { TestHelper.Test(new Test1(), new Test1()); } } "; var compilation1 = CreateCompilation(source1 + source2 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); ValidateEventImplementationInDerived_01(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source3, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation2.SourceModule); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I2.M1.add I2.M1.remove I4.M1.add I4.M1.remove ", verify: VerifyOnMonoOrCoreClr, symbolValidator: ValidateEventImplementationInDerived_01); } var compilation4 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics(); foreach (var reference in new[] { compilation4.ToMetadataReference(), compilation4.EmitToImageReference() }) { var compilation5 = CreateCompilation(source2 + source3, new[] { reference }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation5.Assembly.RuntimeSupportsDefaultInterfaceImplementation); ValidateEventImplementationInDerived_01(compilation5.SourceModule); compilation5.VerifyDiagnostics( // (4,28): error CS0122: 'I2.M1' is inaccessible due to its protection level // event System.Action I2.M1 Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I2.M1").WithLocation(4, 28) ); } } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void IndexerImplementationInDerived_01() { var source1 = @" public interface I2 { int this[int x] {get;} } public interface I4 { int this[int x] {set;} } public interface I5 : I4 { } public interface I1 : I2, I5 { int I2.this[int x] { get { System.Console.WriteLine(""I2.M1""); return 1; } } int I4.this[int x] { set => System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source2 = @" class Test1 : I1 { static void Main() { I2 i2 = new Test1(); _ = i2[0]; I4 i4 = new Test1(); i4[0] = 0; } } "; ValidatePropertyImplementationInDerived_01(source1, source2); } [Fact] public void IndexerImplementationInDerived_02() { var source1 = @" public interface I2 { int this[int x] {get;} } public interface I4 { int this[int x] {set;} } public interface I1 : I2, I4 { int I2.this[int x] => Getter(); private int Getter() { System.Console.WriteLine(""I2.M1""); return 1; } int I4.this[int x] { set { System.Console.WriteLine(""I2.M1""); } } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_02(source1, new DiagnosticDescription[] { // (16,17): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // private int Getter() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "Getter").WithArguments("default interface implementation", "8.0").WithLocation(16, 17), // (14,27): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // int I2.this[int x] => Getter(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "Getter()").WithArguments("default interface implementation", "8.0").WithLocation(14, 27), // (24,9): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // set Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(24, 9) }, // (6,15): error CS8506: 'I1.I2.this[int].get' cannot implement interface member 'I2.this[int].get' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.this[int].get", "I2.this[int].get", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15), // (6,15): error CS8506: 'I1.I4.this[int].set' cannot implement interface member 'I4.this[int].set' in type 'Test1' because feature 'default interface implementation' is not available in C# 7.3. Please use language version '8.0' or greater. // class Test1 : I1 Diagnostic(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.this[int].set", "I4.this[int].set", "Test1", "default interface implementation", "7.3", "8.0").WithLocation(6, 15) ); } [Fact] public void IndexerImplementationInDerived_03() { var source1 = @" public interface I2 { int this[int x] {get; set;} } public interface I4 { int this[int x] {set;} } public interface I1 : I2, I4 { int I2.this[int x] { get { System.Console.WriteLine(""I2.M1""); return 1; } set { System.Console.WriteLine(""I2.M1""); } } int I4.this[int x] { set { System.Console.WriteLine(""I2.M1""); } } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_03(source1, new DiagnosticDescription[] { // (16,9): error CS8501: Target runtime doesn't support default interface implementation. // get Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(16, 9), // (21,9): error CS8501: Target runtime doesn't support default interface implementation. // set Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(21, 9), // (29,9): error CS8501: Target runtime doesn't support default interface implementation. // set Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(29, 9) }, // (6,15): error CS8502: 'I1.I2.this[int].set' cannot implement interface member 'I2.this[int].set' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.this[int].set", "I2.this[int].set", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I2.this[int].get' cannot implement interface member 'I2.this[int].get' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I2.this[int].get", "I2.this[int].get", "Test1").WithLocation(6, 15), // (6,15): error CS8502: 'I1.I4.this[int].set' cannot implement interface member 'I4.this[int].set' in type 'Test1' because the target runtime doesn't support default interface implementation. // class Test1 : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, "I1").WithArguments("I1.I4.this[int].set", "I4.this[int].set", "Test1").WithLocation(6, 15) ); } [Fact] public void IndexerImplementationInDerived_04() { var source1 = @" public interface I2 { int this[int x] {get;} } public interface I4 { int this[int x] {set;} } public interface I1 : I2, I4 { int I2.this[int x] {get;} int I4.this[int x] {set;} } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (14,25): error CS0501: 'I1.I2.this[int].get' must declare a body because it is not marked abstract, extern, or partial // int I2.this[int x] {get;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.I2.this[int].get").WithLocation(14, 25), // (15,25): error CS0501: 'I1.I4.this[int].set' must declare a body because it is not marked abstract, extern, or partial // int I4.this[int x] {set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.I4.this[int].set").WithLocation(15, 25) ); } [Fact] public void IndexerImplementationInDerived_05() { var source1 = @" public interface I2 { int this[int x] {get;} } public interface I4 { int this[int x] {set;} } public interface I1 { int I2.this[int x] {get => throw null;} int I4.this[int x] {set => throw null;} } "; ValidatePropertyImplementationInDerived_05(source1, // (14,9): error CS0540: 'I1.I2.this[int]': containing type does not implement interface 'I2' // int I2.this[int x] {get => throw null;} Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.I2.this[int]", "I2").WithLocation(14, 9), // (15,9): error CS0540: 'I1.I4.this[int]': containing type does not implement interface 'I4' // int I4.this[int x] {set => throw null;} Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I4").WithArguments("I1.I4.this[int]", "I4").WithLocation(15, 9) ); } [Fact] public void IndexerImplementationInDerived_06() { var source1 = @" public interface I2 { int this[int x] {get; set;} } public interface I4 { int this[int x] {get; set;} } public interface I1 : I2, I4 { public static int I2.this[int x] { internal get => throw null; set => throw null; } internal virtual int I4.this[int x] { public get => throw null; set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (14,26): error CS0106: The modifier 'static' is not valid for this item // public static int I2.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(14, 26), // (14,26): error CS0106: The modifier 'public' is not valid for this item // public static int I2.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("public").WithLocation(14, 26), // (16,18): error CS0106: The modifier 'internal' is not valid for this item // internal get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("internal").WithLocation(16, 18), // (19,29): error CS0106: The modifier 'internal' is not valid for this item // internal virtual int I4.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("internal").WithLocation(19, 29), // (19,29): error CS0106: The modifier 'virtual' is not valid for this item // internal virtual int I4.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("virtual").WithLocation(19, 29), // (21,16): error CS0106: The modifier 'public' is not valid for this item // public get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("public").WithLocation(21, 16) ); } [Fact] public void IndexerImplementationInDerived_07() { var source1 = @" public interface I2 { int this[int x] {get; set;} } public interface I4 { int this[int x] {get; set;} } public interface I1 : I2, I4 { private sealed int I2.this[int x] { private get => throw null; set => throw null; } protected abstract int I4.this[int x] { get => throw null; protected set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, i4M1IsAbstract: true, // (14,27): error CS0106: The modifier 'sealed' is not valid for this item // private sealed int I2.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("sealed").WithLocation(14, 27), // (14,27): error CS0106: The modifier 'private' is not valid for this item // private sealed int I2.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("private").WithLocation(14, 27), // (16,17): error CS0106: The modifier 'private' is not valid for this item // private get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("private").WithLocation(16, 17), // (19,31): error CS0106: The modifier 'protected' is not valid for this item // protected abstract int I4.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("protected").WithLocation(19, 31), // (21,9): error CS0500: 'I1.I4.this[int].get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.I4.this[int].get").WithLocation(21, 9), // (22,19): error CS0106: The modifier 'protected' is not valid for this item // protected set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("protected").WithLocation(22, 19), // (22,19): error CS0500: 'I1.I4.this[int].set' cannot declare a body because it is marked abstract // protected set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I1.I4.this[int].set").WithLocation(22, 19), // (30,15): error CS0535: 'Test1' does not implement interface member 'I4.this[int]' // class Test1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test1", "I4.this[int]").WithLocation(30, 15) ); } [Fact] public void IndexerImplementationInDerived_08() { var source1 = @" public interface I2 { int this[int x] {get; set;} } public interface I4 { int this[int x] {get; set;} } public interface I1 : I2, I4 { private protected int I2.this[int x] { private protected get => throw null; set => throw null; } internal protected override int I4.this[int x] { get => throw null; internal protected set => throw null; } } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_04(source1, // (14,30): error CS0106: The modifier 'private protected' is not valid for this item // private protected int I2.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("private protected").WithLocation(14, 30), // (16,27): error CS0106: The modifier 'private protected' is not valid for this item // private protected get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("private protected").WithLocation(16, 27), // (19,40): error CS0106: The modifier 'protected internal' is not valid for this item // internal protected override int I4.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("protected internal").WithLocation(19, 40), // (19,40): error CS0106: The modifier 'override' is not valid for this item // internal protected override int I4.this[int x] Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("override").WithLocation(19, 40), // (22,28): error CS0106: The modifier 'protected internal' is not valid for this item // internal protected set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("protected internal").WithLocation(22, 28) ); } [Fact] public void IndexerImplementationInDerived_09() { var source1 = @" public interface I2 { int this[int x] {get;} } public interface I1 : I2 { extern int I2.this[int x] {get;} } public interface I3 : I1 { } class Test1 : I1 {} "; var source2 = @" public interface I2 { int this[int x] {set;} } public interface I1 : I2 { extern int I2.this[int x] { set {}} } public interface I3 : I1 { } class Test1 : I1 {} "; ValidatePropertyImplementationInDerived_09(source1, source2, new DiagnosticDescription[] { // (9,32): warning CS0626: Method, operator, or accessor 'I1.I2.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int I2.this[int x] {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.I2.this[int].get").WithLocation(9, 32) }, new DiagnosticDescription[] { // (9,32): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // extern int I2.this[int x] {get;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(9, 32), // (9,32): warning CS0626: Method, operator, or accessor 'I1.I2.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int I2.this[int x] {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.I2.this[int].get").WithLocation(9, 32) }, new DiagnosticDescription[] { // (9,32): error CS8501: Target runtime doesn't support default interface implementation. // extern int I2.this[int x] {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(9, 32), // (9,32): warning CS0626: Method, operator, or accessor 'I1.I2.this[int].get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern int I2.this[int x] {get;} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("I1.I2.this[int].get").WithLocation(9, 32) }, // (10,7): error CS0179: 'I1.I2.this[int].set' cannot be extern and declare a body // { set {}} Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("I1.I2.this[int].set").WithLocation(10, 7) ); } [Fact] public void IndexerImplementationInDerived_10() { var source1 = @" public interface I1 { int this[int x] {get;set;} int this[long x] {get;set;} } public interface I2 : I1 { int I1.this[int x] { get => throw null; } int I1.this[long x] { set => throw null; } } class Test1 : I2 {} public interface I3 { int this[int x] {get;} int this[long x] {set;} int this[byte x] {get;set;} int this[short x] {get;set;} } public interface I4 : I3 { int I3.this[int x] { get => throw null; set => throw null; } int I3.this[long x] { get => throw null; set => throw null; } int I3.this[byte x] {get; set;} int I3.this[short x] {get; set;} = 0; } class Test2 : I4 {} "; ValidatePropertyImplementationInDerived_05(source1, // (44,38): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // int I3.this[short x] {get; set;} = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(44, 38), // (10,12): error CS0551: Explicit interface implementation 'I2.I1.this[int]' is missing accessor 'I1.this[int].set' // int I1.this[int x] Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("I2.I1.this[int]", "I1.this[int].set").WithLocation(10, 12), // (14,12): error CS0551: Explicit interface implementation 'I2.I1.this[long]' is missing accessor 'I1.this[long].get' // int I1.this[long x] Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("I2.I1.this[long]", "I1.this[long].get").WithLocation(14, 12), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.this[long]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[long]").WithLocation(20, 15), // (20,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(20, 15), // (36,9): error CS0550: 'I4.I3.this[int].set' adds an accessor not found in interface member 'I3.this[int]' // set => throw null; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I4.I3.this[int].set", "I3.this[int]").WithLocation(36, 9), // (40,9): error CS0550: 'I4.I3.this[long].get' adds an accessor not found in interface member 'I3.this[long]' // get => throw null; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I4.I3.this[long].get", "I3.this[long]").WithLocation(40, 9), // (43,26): error CS0501: 'I4.I3.this[byte].get' must declare a body because it is not marked abstract, extern, or partial // int I3.this[byte x] {get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I4.I3.this[byte].get").WithLocation(43, 26), // (43,31): error CS0501: 'I4.I3.this[byte].set' must declare a body because it is not marked abstract, extern, or partial // int I3.this[byte x] {get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I4.I3.this[byte].set").WithLocation(43, 31), // (44,27): error CS0501: 'I4.I3.this[short].get' must declare a body because it is not marked abstract, extern, or partial // int I3.this[short x] {get; set;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I4.I3.this[short].get").WithLocation(44, 27), // (44,32): error CS0501: 'I4.I3.this[short].set' must declare a body because it is not marked abstract, extern, or partial // int I3.this[short x] {get; set;} = 0; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I4.I3.this[short].set").WithLocation(44, 32) ); } [Fact] [WorkItem(32540, "https://github.com/dotnet/roslyn/issues/32540")] public void IndexerImplementationInDerived_11() { var source1 = @" public interface I2 { internal int this[int x] {get;} } public interface I4 { int this[int x] {get; internal set;} } public interface I5 : I4 { } public class TestHelper { public static void Test(I2 i2, I4 i4) { _ = i2[0]; i4[0] = i4[0]; } } "; var source2 = @" public interface I1 : I2, I5 { int I2.this[int x] => Getter(); private int Getter() { System.Console.WriteLine(""I2.M1""); return 1; } int I4.this[int x] { get { System.Console.WriteLine(""I4.M1""); return 1; } set => System.Console.WriteLine(""I4.M1.set""); } } public interface I3 : I1 { } "; ValidatePropertyImplementationInDerived_11(source1, source2, // (4,12): error CS0122: 'I2.this[int]' is inaccessible due to its protection level // int I2.this[int x] => Getter(); Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I2.this[int]").WithLocation(4, 12), // (11,12): error CS0122: 'I4.this[int].set' is inaccessible due to its protection level // int I4.this[int x] Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I4.this[int].set").WithLocation(11, 12) ); } [Fact] [WorkItem(20083, "https://github.com/dotnet/roslyn/issues/20083")] public void IndexerImplementationInDerived_12() { var source1 = @" public interface I1 { int this[int x] { get => throw null; set => throw null;} } public interface I2 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""I2.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I2.I1.M1.set""); } } } public interface I3 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""I3.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I3.I1.M1.set""); } } } public interface I4 : I1 { int I1.this[int x] { get { System.Console.WriteLine(""I4.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I4.I1.M1.set""); } } } public interface I5 : I2, I3 { int I1.this[int x] { get { System.Console.WriteLine(""I5.I1.M1.get""); return 1; } set { System.Console.WriteLine(""I5.I1.M1.set""); } } } public interface I6 : I1, I2, I3, I5 {} "; var source4 = @" class Test5 : I2 {} class Test6 : I1, I2, I3, I5 {} class Test7 : I6 { static void Main() { I1 i1 = new Test5(); i1[0] = i1[0]; i1 = new Test6(); i1[0] = i1[0]; i1 = new Test7(); i1[0] = i1[0]; } } "; var source5 = @" class Test8 : I2, I3 { int I1.this[int x] { get { System.Console.WriteLine(""Test8.I1.M1.get""); return 1; } set { System.Console.WriteLine(""Test8.I1.M1.set""); } } static void Main() { I1 i1 = new Test8(); i1[0] = i1[0]; i1 = new Test9(); i1[0] = i1[0]; i1 = new Test10(); i1[0] = i1[0]; i1 = new Test11(); i1[0] = i1[0]; i1 = new Test12(); i1[0] = i1[0]; } } class Test9 : I7 { int I1.this[int x] { get { System.Console.WriteLine(""Test9.I1.M1.get""); return 1; } set { System.Console.WriteLine(""Test9.I1.M1.set""); } } } class Test10 : I1, I2, I3, I4 { public int this[int x] { get { System.Console.WriteLine(""Test10.M1.get""); return 1; } set { System.Console.WriteLine(""Test10.M1.set""); } } } class Test11 : I1, I2, I3, I5, I4 { public int this[int x] { get { System.Console.WriteLine(""Test11.M1.get""); return 1; } set { System.Console.WriteLine(""Test11.M1.set""); } } } class Test12 : I8 { public virtual int this[int x] { get { System.Console.WriteLine(""Test12.M1.get""); return 1; } set { System.Console.WriteLine(""Test12.M1.set""); } } } "; ValidatePropertyImplementationInDerived_12(source1, source4, source5, new DiagnosticDescription[] { // (2,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15), // (5,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test2 : I7 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I7").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(5, 15), // (8,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test3 : I1, I2, I3, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(8, 15), // (11,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I5.I1.this[int]', nor 'I4.I1.this[int]' are most specific. // class Test4 : I1, I2, I3, I5, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.this[int]", "I5.I1.this[int]", "I4.I1.this[int]").WithLocation(11, 15), // (14,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I5.I1.this[int]', nor 'I4.I1.this[int]' are most specific. // class Test5 : I8 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I8").WithArguments("I1.this[int]", "I5.I1.this[int]", "I4.I1.this[int]").WithLocation(14, 15) }, new DiagnosticDescription[] { // (2,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15), // (5,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test2 : I7 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I7").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(5, 15), // (8,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test3 : I1, I2, I3, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(8, 15), // (11,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I5.I1.Item[int]', nor 'I4.I1.Item[int]' are most specific. // class Test4 : I1, I2, I3, I5, I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I1").WithArguments("I1.this[int]", "I5.I1.Item[int]", "I4.I1.Item[int]").WithLocation(11, 15), // (14,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I5.I1.Item[int]', nor 'I4.I1.Item[int]' are most specific. // class Test5 : I8 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I8").WithArguments("I1.this[int]", "I5.I1.Item[int]", "I4.I1.Item[int]").WithLocation(14, 15) } ); } [Fact] public void IndexerImplementationInDerived_13() { var source1 = @" public interface I1 { int this[int x] {get;} } public interface I2 : I1 { int I1.this[int x] => throw null; } public interface I3 : I1 { int I1.this[int x] => throw null; } "; var source2 = @" class Test1 : I2, I3 { public long this[int x] => 1; } "; ValidatePropertyImplementationInDerived_13(source1, source2, new DiagnosticDescription[] { // (2,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15), // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.this[int]'. 'Test1.this[int]' cannot implement 'I1.this[int]' because it does not have the matching return type of 'int'. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test1", "I1.this[int]", "Test1.this[int]", "int").WithLocation(2, 15) }, new DiagnosticDescription[] { // (2,15): error CS8505: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15), // (2,15): error CS0738: 'Test1' does not implement interface member 'I1.this[int]'. 'Test1.this[int]' cannot implement 'I1.this[int]' because it does not have the matching return type of 'int'. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test1", "I1.this[int]", "Test1.this[int]", "int").WithLocation(2, 15) } ); } [Fact] [WorkItem(20084, "https://github.com/dotnet/roslyn/issues/20084")] public void IndexerImplementationInDerived_14() { var source1 = @" public interface I1<T> { int this[int x] { get { System.Console.WriteLine(""I1.M1.get""); return 1; } set => System.Console.WriteLine(""I1.M1.set""); } } public interface I2<T> : I1<T> { int I1<T>.this[int x] { get { System.Console.WriteLine(""I2.I1.M1.get""); return 1; } set => System.Console.WriteLine(""I2.I1.M1.set""); } } public interface I3<T> : I1<T> {} "; var source2 = @" class Test1 : I1<int> { static void Main() { I1<int> i1Int = new Test1(); i1Int[0] = i1Int[0]; I1<long> i1Long = new Test2(); i1Long[0] = i1Long[0]; } } class Test2 : I2<long> {} "; ValidatePropertyImplementationInDerived_14(source1, source2); } [Fact] public void IndexerImplementationInDerived_15() { var source1 = @" public interface I2 { int this[int x] {get => throw null; private set => throw null;} } public interface I4 { int this[int x] {set => throw null; private get => throw null;} } public interface I5 : I4 { } public interface I1 : I2, I5 { int I2.this[int x] { get { System.Console.WriteLine(""I2.M1""); return 1; } } int I4.this[int x] { set => System.Console.WriteLine(""I4.M1""); } } public interface I3 : I1 { } "; var source2 = @" class Test1 : I1 { static void Main() { I2 i2 = new Test1(); _ = i2[0]; I4 i4 = new Test1(); i4[0] = 0; } } "; ValidatePropertyImplementationInDerived_01(source1, source2); } [Fact] public void Field_01() { var source1 = @" public interface I1 { int F1; protected static int F2; protected internal static int F3; private protected static int F4; int F5 = 5; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyEmitDiagnostics( // (4,9): error CS0525: Interfaces cannot contain instance fields // int F1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F1").WithLocation(4, 9), // (5,26): error CS8701: Target runtime doesn't support default interface implementation. // protected static int F2; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F2").WithLocation(5, 26), // (6,35): error CS8701: Target runtime doesn't support default interface implementation. // protected internal static int F3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F3").WithLocation(6, 35), // (7,34): error CS8701: Target runtime doesn't support default interface implementation. // private protected static int F4; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F4").WithLocation(7, 34), // (8,9): error CS0525: Interfaces cannot contain instance fields // int F5 = 5; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F5").WithLocation(8, 9) ); validate(compilation1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,9): error CS0525: Interfaces cannot contain instance fields // int F1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F1").WithLocation(4, 9), // (8,9): error CS0525: Interfaces cannot contain instance fields // int F5 = 5; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F5").WithLocation(8, 9) ); validate(compilation2); static void validate(CSharpCompilation compilation) { var i1 = compilation.GetTypeByMetadataName("I1"); var f1 = i1.GetMember<FieldSymbol>("F1"); var f2 = i1.GetMember<FieldSymbol>("F2"); var f3 = i1.GetMember<FieldSymbol>("F3"); var f4 = i1.GetMember<FieldSymbol>("F4"); Assert.False(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Protected, f2.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedAndInternal, f4.DeclaredAccessibility); } } [Fact] public void Field_02() { var source1 = @" public interface I1 { static int F1; public static int F2; internal static int F3; private static int F4; public class TestHelper { public static int F4Proxy { get => I1.F4; set => I1.F4 = value; } } } class Test1 : I1 { static void Main() { I1.F1 = 1; I1.F2 = 2; I1.F3 = 3; I1.TestHelper.F4Proxy = 4; System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.F3}{I1.TestHelper.F4Proxy}""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<FieldSymbol>("F1"); var f2 = i1.GetMember<FieldSymbol>("F2"); var f3 = i1.GetMember<FieldSymbol>("F3"); var f4 = i1.GetMember<FieldSymbol>("F4"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f4.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Null(cctor); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { I1.F1 = 11; I1.F2 = 22; I1.TestHelper.F4Proxy = 44; System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.TestHelper.F4Proxy}""); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "112244"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "112244"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,16): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static int F1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F1").WithArguments("default interface implementation", "8.0").WithLocation(4, 16), // (5,23): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static int F2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F2").WithArguments("default interface implementation", "8.0").WithLocation(5, 23), // (6,25): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // internal static int F3; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F3").WithArguments("default interface implementation", "8.0").WithLocation(6, 25), // (7,24): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // private static int F4; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F4").WithArguments("default interface implementation", "8.0").WithLocation(7, 24), // (9,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(9, 18) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,16): error CS8701: Target runtime doesn't support default interface implementation. // static int F1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F1").WithLocation(4, 16), // (5,23): error CS8701: Target runtime doesn't support default interface implementation. // public static int F2; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F2").WithLocation(5, 23), // (6,25): error CS8701: Target runtime doesn't support default interface implementation. // internal static int F3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F3").WithLocation(6, 25), // (7,24): error CS8701: Target runtime doesn't support default interface implementation. // private static int F4; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F4").WithLocation(7, 24) ); Validate1(compilation5.SourceModule); } [Fact] public void Field_03() { var source1 = @" public interface I1 { static readonly int F1 = 1; public static readonly int F2 = 2; internal static readonly int F3 = 3; private static readonly int F4 = 4; public class TestHelper { public static int F4Proxy { get => I1.F4; } } } class Test1 : I1 { static void Main() { System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.F3}{I1.TestHelper.F4Proxy}""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<FieldSymbol>("F1"); var f2 = i1.GetMember<FieldSymbol>("F2"); var f3 = i1.GetMember<FieldSymbol>("F3"); var f4 = i1.GetMember<FieldSymbol>("F4"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.True(f1.IsReadOnly); Assert.True(f2.IsReadOnly); Assert.True(f3.IsReadOnly); Assert.True(f4.IsReadOnly); Assert.False(f1.IsConst); Assert.False(f2.IsConst); Assert.False(f3.IsConst); Assert.False(f4.IsConst); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f4.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Equal(MethodKind.StaticConstructor, cctor.MethodKind); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.TestHelper.F4Proxy}""); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "124"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "124"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,25): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static readonly int F1 = 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F1").WithArguments("default interface implementation", "8.0").WithLocation(4, 25), // (5,32): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static readonly int F2 = 2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F2").WithArguments("default interface implementation", "8.0").WithLocation(5, 32), // (6,34): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // internal static readonly int F3 = 3; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F3").WithArguments("default interface implementation", "8.0").WithLocation(6, 34), // (7,33): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // private static readonly int F4 = 4; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F4").WithArguments("default interface implementation", "8.0").WithLocation(7, 33), // (9,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(9, 18) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,25): error CS8701: Target runtime doesn't support default interface implementation. // static readonly int F1 = 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F1").WithLocation(4, 25), // (5,32): error CS8701: Target runtime doesn't support default interface implementation. // public static readonly int F2 = 2; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F2").WithLocation(5, 32), // (6,34): error CS8701: Target runtime doesn't support default interface implementation. // internal static readonly int F3 = 3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F3").WithLocation(6, 34), // (7,33): error CS8701: Target runtime doesn't support default interface implementation. // private static readonly int F4 = 4; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F4").WithLocation(7, 33) ); Validate1(compilation5.SourceModule); } [Fact] public void Field_04() { var source1 = @" public interface I1 { const int F1 = 1; public const int F2 = 2; internal const int F3 = 3; private const int F4 = 4; public class TestHelper { public static int F4Proxy { get => I1.F4; } } } class Test1 : I1 { static void Main() { System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.F3}{I1.TestHelper.F4Proxy}""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<FieldSymbol>("F1"); var f2 = i1.GetMember<FieldSymbol>("F2"); var f3 = i1.GetMember<FieldSymbol>("F3"); var f4 = i1.GetMember<FieldSymbol>("F4"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.True(f1.IsConst); Assert.True(f2.IsConst); Assert.True(f3.IsConst); Assert.True(f4.IsConst); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f4.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Null(cctor); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.TestHelper.F4Proxy}""); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "124"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "124"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,15): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // const int F1 = 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F1").WithArguments("default interface implementation", "8.0").WithLocation(4, 15), // (5,22): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public const int F2 = 2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F2").WithArguments("default interface implementation", "8.0").WithLocation(5, 22), // (6,24): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // internal const int F3 = 3; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F3").WithArguments("default interface implementation", "8.0").WithLocation(6, 24), // (7,23): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // private const int F4 = 4; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F4").WithArguments("default interface implementation", "8.0").WithLocation(7, 23), // (9,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(9, 18) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,15): error CS8701: Target runtime doesn't support default interface implementation. // const int F1 = 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F1").WithLocation(4, 15), // (5,22): error CS8701: Target runtime doesn't support default interface implementation. // public const int F2 = 2; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F2").WithLocation(5, 22), // (6,24): error CS8701: Target runtime doesn't support default interface implementation. // internal const int F3 = 3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F3").WithLocation(6, 24), // (7,23): error CS8701: Target runtime doesn't support default interface implementation. // private const int F4 = 4; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F4").WithLocation(7, 23) ); Validate1(compilation5.SourceModule); } [Fact] public void Field_05() { var source0 = @" public interface I1 { static protected int F1; static protected internal int F2; static private protected int F3; } "; var source1 = @" class Test1 : I1 { static void Main() { I1.F1 = 1; I1.F2 = 2; I1.F3 = 3; System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.F3}""); Test2.Test(); } } class Test2 { public static void Test() { I1.F2 = -2; System.Console.WriteLine(I1.F2); } } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); validate(compilation1.SourceModule); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"123 -2 ", verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var source2 = @" class Test2 : I1 { static void Main() { I1.F1 = 11; I1.F2 = 22; System.Console.WriteLine($""{I1.F1}{I1.F2}""); } } "; var references = new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }; foreach (var reference in references) { var compilation2 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "1122" : null, verify: VerifyOnMonoOrCoreClr); } var source3 = @" class Test1 { static void Main() { I1.F1 = 1; I1.F2 = 2; I1.F3 = 3; } } "; var compilation3 = CreateCompilation(source0 + source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (13,12): error CS0122: 'I1.F1' is inaccessible due to its protection level // I1.F1 = 1; Diagnostic(ErrorCode.ERR_BadAccess, "F1").WithArguments("I1.F1").WithLocation(13, 12), // (15,12): error CS0122: 'I1.F3' is inaccessible due to its protection level // I1.F3 = 3; Diagnostic(ErrorCode.ERR_BadAccess, "F3").WithArguments("I1.F3").WithLocation(15, 12) ); var source4 = @" class Test2 : I1 { static void Test() { I1.F3 = -3; } } "; foreach (var reference in references) { var compilation2 = CreateCompilation(source3 + source4, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,12): error CS0122: 'I1.F1' is inaccessible due to its protection level // I1.F1 = 1; Diagnostic(ErrorCode.ERR_BadAccess, "F1").WithArguments("I1.F1").WithLocation(6, 12), // (7,12): error CS0122: 'I1.F2' is inaccessible due to its protection level // I1.F2 = 2; Diagnostic(ErrorCode.ERR_BadAccess, "F2").WithArguments("I1.F2").WithLocation(7, 12), // (8,12): error CS0122: 'I1.F3' is inaccessible due to its protection level // I1.F3 = 3; Diagnostic(ErrorCode.ERR_BadAccess, "F3").WithArguments("I1.F3").WithLocation(8, 12), // (16,12): error CS0122: 'I1.F3' is inaccessible due to its protection level // I1.F3 = -3; Diagnostic(ErrorCode.ERR_BadAccess, "F3").WithArguments("I1.F3").WithLocation(16, 12) ); } var compilation4 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,26): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static protected int F1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F1").WithArguments("default interface implementation", "8.0").WithLocation(4, 26), // (5,35): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static protected internal int F2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F2").WithArguments("default interface implementation", "8.0").WithLocation(5, 35), // (6,34): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static private protected int F3; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "F3").WithArguments("default interface implementation", "8.0").WithLocation(6, 34) ); validate(compilation4.SourceModule); void validate(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<FieldSymbol>("F1"); var f2 = i1.GetMember<FieldSymbol>("F2"); var f3 = i1.GetMember<FieldSymbol>("F3"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.Equal(Accessibility.Protected, f1.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, f2.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedAndInternal, f3.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Null(cctor); } } [Fact] public void Constructors_01() { var source1 = @" public interface I1 { I1(){} static I1() {} } interface I2 { I2(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,5): error CS0526: Interfaces cannot contain instance constructors // I1(){} Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I1").WithLocation(4, 5), // (10,5): error CS0501: 'I2.I2()' must declare a body because it is not marked abstract, extern, or partial // I2(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I2").WithArguments("I2.I2()").WithLocation(10, 5), // (10,5): error CS0526: Interfaces cannot contain instance constructors // I2(); Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I2").WithLocation(10, 5) ); } [Fact] public void Constructors_02() { var source1 = @" interface I1 { static I1() {} } interface I2 { static I2() => throw null; } interface I3 { I3() {} } interface I4 { I4() => throw null; } interface I5 { I5(); } interface I6 { extern static I6(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,12): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static I1() {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "I1").WithArguments("default interface implementation", "8.0").WithLocation(4, 12), // (8,12): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // static I2() => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "I2").WithArguments("default interface implementation", "8.0").WithLocation(8, 12), // (12,5): error CS0526: Interfaces cannot contain instance constructors // I3() {} Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I3").WithLocation(12, 5), // (16,5): error CS0526: Interfaces cannot contain instance constructors // I4() => throw null; Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I4").WithLocation(16, 5), // (20,5): error CS0501: 'I5.I5()' must declare a body because it is not marked abstract, extern, or partial // I5(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I5").WithArguments("I5.I5()").WithLocation(20, 5), // (20,5): error CS0526: Interfaces cannot contain instance constructors // I5(); Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I5").WithLocation(20, 5), // (24,19): error CS8703: The modifier 'extern' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // extern static I6(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I6").WithArguments("extern", "7.3", "8.0").WithLocation(24, 19), // (24,19): warning CS0824: Constructor 'I6.I6()' is marked external // extern static I6(); Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "I6").WithArguments("I6.I6()").WithLocation(24, 19) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (4,12): error CS8701: Target runtime doesn't support default interface implementation. // static I1() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "I1").WithLocation(4, 12), // (8,12): error CS8701: Target runtime doesn't support default interface implementation. // static I2() => throw null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "I2").WithLocation(8, 12), // (12,5): error CS0526: Interfaces cannot contain instance constructors // I3() {} Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I3").WithLocation(12, 5), // (16,5): error CS0526: Interfaces cannot contain instance constructors // I4() => throw null; Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I4").WithLocation(16, 5), // (20,5): error CS0501: 'I5.I5()' must declare a body because it is not marked abstract, extern, or partial // I5(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I5").WithArguments("I5.I5()").WithLocation(20, 5), // (20,5): error CS0526: Interfaces cannot contain instance constructors // I5(); Diagnostic(ErrorCode.ERR_InterfacesCantContainConstructors, "I5").WithLocation(20, 5), // (24,19): error CS8701: Target runtime doesn't support default interface implementation. // extern static I6(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "I6").WithLocation(24, 19), // (24,19): warning CS0824: Constructor 'I6.I6()' is marked external // extern static I6(); Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "I6").WithArguments("I6.I6()").WithLocation(24, 19) ); } [Fact] public void Constructors_03() { var source1 = @" interface I1 { static I1(int i) {} } interface I2 { static void I2() {} } interface I3 { void I3() {} } interface I4 { public static I4() {} } interface I5 { internal static I5() {} } interface I6 { private static I6() {} } interface I7 { static I7(); } interface I8 { static I8(){} static void M1() { I8(); } void M2() { I8.I8(); } } interface I9 { static I9() {} => throw null; } interface I10 { abstract static I10(); } interface I11 { virtual static I11(); } interface I12 { abstract static I12() {} } interface I13 { virtual static I13() => throw null; } interface I14 { partial static I14(); } interface I15 { static partial I15(); } interface I16 { partial static I16() {} } interface I17 { static partial I17() => throw null; } interface I18 { extern static I18() {} } interface I19 { static extern I19() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,12): error CS0132: 'I1.I1(int)': a static constructor must be parameterless // static I1(int i) {} Diagnostic(ErrorCode.ERR_StaticConstParam, "I1").WithArguments("I1.I1(int)").WithLocation(4, 12), // (8,17): error CS0542: 'I2': member names cannot be the same as their enclosing type // static void I2() {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I2").WithArguments("I2").WithLocation(8, 17), // (16,19): error CS0515: 'I4.I4()': access modifiers are not allowed on static constructors // public static I4() {} Diagnostic(ErrorCode.ERR_StaticConstructorWithAccessModifiers, "I4").WithArguments("I4.I4()").WithLocation(16, 19), // (20,21): error CS0515: 'I5.I5()': access modifiers are not allowed on static constructors // internal static I5() {} Diagnostic(ErrorCode.ERR_StaticConstructorWithAccessModifiers, "I5").WithArguments("I5.I5()").WithLocation(20, 21), // (24,20): error CS0515: 'I6.I6()': access modifiers are not allowed on static constructors // private static I6() {} Diagnostic(ErrorCode.ERR_StaticConstructorWithAccessModifiers, "I6").WithArguments("I6.I6()").WithLocation(24, 20), // (28,12): error CS0501: 'I7.I7()' must declare a body because it is not marked abstract, extern, or partial // static I7(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I7").WithArguments("I7.I7()").WithLocation(28, 12), // (36,9): error CS1955: Non-invocable member 'I8' cannot be used like a method. // I8(); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "I8").WithArguments("I8").WithLocation(36, 9), // (41,12): error CS0117: 'I8' does not contain a definition for 'I8' // I8.I8(); Diagnostic(ErrorCode.ERR_NoSuchMember, "I8").WithArguments("I8", "I8").WithLocation(41, 12), // (46,5): error CS8057: Block bodies and expression bodies cannot both be provided. // static I9() {} => throw null; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "static I9() {} => throw null;").WithLocation(46, 5), // (50,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I10(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I10").WithArguments("abstract").WithLocation(50, 21), // (54,20): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I11(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I11").WithArguments("virtual").WithLocation(54, 20), // (58,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I12() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I12").WithArguments("abstract").WithLocation(58, 21), // (62,20): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I13() => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "I13").WithArguments("virtual").WithLocation(62, 20), // (66,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I14(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(66, 5), // (66,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I14(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(66, 5), // (70,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I15(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(70, 12), // (70,20): error CS0501: 'I15.I15()' must declare a body because it is not marked abstract, extern, or partial // static partial I15(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I15").WithArguments("I15.I15()").WithLocation(70, 20), // (70,20): error CS0542: 'I15': member names cannot be the same as their enclosing type // static partial I15(); Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I15").WithArguments("I15").WithLocation(70, 20), // (74,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I16() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(74, 5), // (74,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I16() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(74, 5), // (78,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I17() => throw null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(78, 12), // (78,20): error CS0542: 'I17': member names cannot be the same as their enclosing type // static partial I17() => throw null; Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I17").WithArguments("I17").WithLocation(78, 20), // (82,19): error CS0179: 'I18.I18()' cannot be extern and declare a body // extern static I18() {} Diagnostic(ErrorCode.ERR_ExternHasBody, "I18").WithArguments("I18.I18()").WithLocation(82, 19), // (86,19): error CS0179: 'I19.I19()' cannot be extern and declare a body // static extern I19() => throw null; Diagnostic(ErrorCode.ERR_ExternHasBody, "I19").WithArguments("I19.I19()").WithLocation(86, 19) ); } [Fact] public void Constructors_04() { var source1 = @" interface I1 { static I1() { System.Console.WriteLine(""I1""); } static void Main() { System.Console.WriteLine(""Main""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); ValidateConstructor(compilation1.SourceModule); Assert.Empty(compilation1.GetTypeByMetadataName("I1").GetMembers("I1")); CompileAndVerify(compilation1, symbolValidator: ValidateConstructor, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1 Main "); } private static void ValidateConstructor(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(cctor.IsAbstract); Assert.False(cctor.IsVirtual); Assert.False(cctor.IsMetadataVirtual()); Assert.False(cctor.IsSealed); Assert.True(cctor.IsStatic); Assert.False(cctor.IsExtern); Assert.False(cctor.IsAsync); Assert.False(cctor.IsOverride); Assert.Equal(Accessibility.Private, cctor.DeclaredAccessibility); Assert.Equal(MethodKind.StaticConstructor, cctor.MethodKind); } [Fact] public void Constructors_05() { var source1 = @" interface I1 { static string F = ""F""; static void Main() { System.Console.WriteLine(F); System.Console.WriteLine(""Main""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); ValidateConstructor(compilation1.SourceModule); CompileAndVerify(compilation1, symbolValidator: ValidateConstructor, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"F Main "); } [Fact] public void Constructors_06() { var source1 = @" interface I1 { static string F = ""F""; static I1() { System.Console.WriteLine(F); System.Console.WriteLine(""I1""); } static void Main() { System.Console.WriteLine(""Main""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); ValidateConstructor(compilation1.SourceModule); CompileAndVerify(compilation1, symbolValidator: ValidateConstructor, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"F I1 Main "); } [Fact] public void Constructors_07() { var source1 = @" interface I1 { extern static I1(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,19): warning CS0824: Constructor 'I1.I1()' is marked external // extern static I1(); Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "I1").WithArguments("I1.I1()").WithLocation(4, 19) ); var i1 = compilation1.SourceModule.GlobalNamespace.GetTypeMember("I1"); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(cctor.IsAbstract); Assert.False(cctor.IsVirtual); Assert.False(cctor.IsMetadataVirtual()); Assert.False(cctor.IsSealed); Assert.True(cctor.IsStatic); Assert.True(cctor.IsExtern); Assert.False(cctor.IsAsync); Assert.False(cctor.IsOverride); Assert.Equal(Accessibility.Private, cctor.DeclaredAccessibility); Assert.Equal(MethodKind.StaticConstructor, cctor.MethodKind); CompileAndVerify(compilation1, symbolValidator: ValidateConstructor, verify: Verification.Skipped); } [Fact] public void Constructors_08() { var source1 = @" interface I1 { void I1(); } class Test : I1 { void I1.I1() { System.Console.WriteLine(""Test.I1""); } static void Main() { I1 x = new Test(); x.I1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: "Test.I1"); } [Fact] public void Constructors_09() { var source1 = @" interface I1 { void I1(); static I1() { System.Console.WriteLine(""I1..cctor""); } static void M1() { System.Console.WriteLine(""I1.M1""); } } class Test : I1 { void I1.I1() { System.Console.WriteLine(""Test.I1""); } static void Main() { I1.M1(); I1 x = new Test(); x.I1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1..cctor I1.M1 Test.I1 "); } [Fact] public void Constructors_10() { var source1 = @" interface I1 { void I1() { System.Console.WriteLine(""I1.I1""); } static I1() { System.Console.WriteLine(""I1..cctor""); } static void M1() { System.Console.WriteLine(""I1.M1""); } } class Test : I1 { static void Main() { I1.M1(); I1 x = new Test(); x.I1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I1..cctor I1.M1 I1.I1 ", verify: VerifyOnMonoOrCoreClr); } [Fact] public void Constructors_11() { var source1 = @" interface I1 { void I1() { System.Console.WriteLine(""I1.I1""); } } class Test : I1 { static void Main() { I1 x = new Test(); x.I1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "I1.I1", verify: VerifyOnMonoOrCoreClr); } /// <summary> /// Make sure runtime handles cycles in static constructors. /// </summary> [Fact] public void Constructors_12() { var source0 = @" interface I1 { public static int F1; static I1() { F1 = I2.F2; } } interface I2 { public static int F2; static I2() { F2 = I1.F1 + 1; } } "; var source1 = @" class Test { static void Main() { System.Console.WriteLine(I1.F1 + I2.F2); } } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "2"); var source2 = @" class Test { static void Main() { System.Console.WriteLine(I2.F2 + I1.F1); } } "; var compilation2 = CreateCompilation(source0 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1"); } [Fact] public void AutoProperty_01() { var source1 = @" public interface I1 { private int F1 {get; set;} private int F5 {get;} = 5; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyEmitDiagnostics( // (4,21): error CS0501: 'I1.F1.get' must declare a body because it is not marked abstract, extern, or partial // private int F1 {get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.F1.get").WithLocation(4, 21), // (4,26): error CS0501: 'I1.F1.set' must declare a body because it is not marked abstract, extern, or partial // private int F1 {get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("I1.F1.set").WithLocation(4, 26), // (5,17): error CS8053: Instance properties in interfaces cannot have initializers. // private int F5 {get;} = 5; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "F5").WithArguments("I1.F5").WithLocation(5, 17), // (5,21): error CS0501: 'I1.F5.get' must declare a body because it is not marked abstract, extern, or partial // private int F5 {get;} = 5; Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I1.F5.get").WithLocation(5, 21) ); } [Fact] public void AutoProperty_02() { var source1 = @" public interface I1 { static int F1 {get; set;} public static int F2 {get; set;} internal static int F3 {get; set;} private static int F4 {get; set;} public class TestHelper { public static int F4Proxy { get => I1.F4; set => I1.F4 = value; } } } class Test1 : I1 { static void Main() { I1.F1 = 1; I1.F2 = 2; I1.F3 = 3; I1.TestHelper.F4Proxy = 4; System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.F3}{I1.TestHelper.F4Proxy}""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<PropertySymbol>("F1"); var f2 = i1.GetMember<PropertySymbol>("F2"); var f3 = i1.GetMember<PropertySymbol>("F3"); var f4 = i1.GetMember<PropertySymbol>("F4"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f4.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Null(cctor); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { I1.F1 = 11; I1.F2 = 22; I1.TestHelper.F4Proxy = 44; System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.TestHelper.F4Proxy}""); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "112244"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "112244"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,16): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static int F1 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F1").WithArguments("static", "7.3", "8.0").WithLocation(4, 16), // (5,23): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static int F2 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("static", "7.3", "8.0").WithLocation(5, 23), // (5,23): error CS8703: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static int F2 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("public", "7.3", "8.0").WithLocation(5, 23), // (6,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static int F3 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("static", "7.3", "8.0").WithLocation(6, 25), // (6,25): error CS8703: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static int F3 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("internal", "7.3", "8.0").WithLocation(6, 25), // (7,24): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static int F4 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("static", "7.3", "8.0").WithLocation(7, 24), // (7,24): error CS8703: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static int F4 {get; set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("private", "7.3", "8.0").WithLocation(7, 24), // (9,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(9, 18) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,20): error CS8701: Target runtime doesn't support default interface implementation. // static int F1 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(4, 20), // (4,25): error CS8701: Target runtime doesn't support default interface implementation. // static int F1 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(4, 25), // (5,27): error CS8701: Target runtime doesn't support default interface implementation. // public static int F2 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(5, 27), // (5,32): error CS8701: Target runtime doesn't support default interface implementation. // public static int F2 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(5, 32), // (6,29): error CS8701: Target runtime doesn't support default interface implementation. // internal static int F3 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(6, 29), // (6,34): error CS8701: Target runtime doesn't support default interface implementation. // internal static int F3 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(6, 34), // (7,28): error CS8701: Target runtime doesn't support default interface implementation. // private static int F4 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(7, 28), // (7,33): error CS8701: Target runtime doesn't support default interface implementation. // private static int F4 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(7, 33) ); Validate1(compilation5.SourceModule); } [Fact] public void AutoProperty_03() { var source1 = @" public interface I1 { static int F1 {get;} = 1; public static int F2 {get;} = 2; internal static int F3 {get;} = 3; private static int F4 {get;} = 4; public class TestHelper { public static int F4Proxy { get => I1.F4; } } } class Test1 : I1 { static void Main() { System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.F3}{I1.TestHelper.F4Proxy}""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<PropertySymbol>("F1"); var f2 = i1.GetMember<PropertySymbol>("F2"); var f3 = i1.GetMember<PropertySymbol>("F3"); var f4 = i1.GetMember<PropertySymbol>("F4"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.True(f1.IsReadOnly); Assert.True(f2.IsReadOnly); Assert.True(f3.IsReadOnly); Assert.True(f4.IsReadOnly); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f4.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Equal(MethodKind.StaticConstructor, cctor.MethodKind); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.TestHelper.F4Proxy}""); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "124"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "124"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,16): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static int F1 {get;} = 1; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F1").WithArguments("static", "7.3", "8.0").WithLocation(4, 16), // (5,23): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static int F2 {get;} = 2; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("static", "7.3", "8.0").WithLocation(5, 23), // (5,23): error CS8703: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static int F2 {get;} = 2; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("public", "7.3", "8.0").WithLocation(5, 23), // (6,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static int F3 {get;} = 3; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("static", "7.3", "8.0").WithLocation(6, 25), // (6,25): error CS8703: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static int F3 {get;} = 3; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("internal", "7.3", "8.0").WithLocation(6, 25), // (7,24): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static int F4 {get;} = 4; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("static", "7.3", "8.0").WithLocation(7, 24), // (7,24): error CS8703: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static int F4 {get;} = 4; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("private", "7.3", "8.0").WithLocation(7, 24), // (9,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(9, 18) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,20): error CS8701: Target runtime doesn't support default interface implementation. // static int F1 {get;} = 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(4, 20), // (5,27): error CS8701: Target runtime doesn't support default interface implementation. // public static int F2 {get;} = 2; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(5, 27), // (6,29): error CS8701: Target runtime doesn't support default interface implementation. // internal static int F3 {get;} = 3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(6, 29), // (7,28): error CS8701: Target runtime doesn't support default interface implementation. // private static int F4 {get;} = 4; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(7, 28) ); Validate1(compilation5.SourceModule); } [Fact] public void AutoProperty_04() { var source1 = @" public interface I1 { static int F1 {get; private set;} public static int F2 {get; private set;} internal static int F3 {get; private set;} public class TestHelper { public static void F4Proxy(int f1, int f2, int f3) { F1 = f1; F2 = f2; F3 = f3; } } } class Test1 : I1 { static void Main() { I1.TestHelper.F4Proxy(1,2,3); System.Console.WriteLine($""{I1.F1}{I1.F2}{I1.F3}""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<PropertySymbol>("F1"); var f2 = i1.GetMember<PropertySymbol>("F2"); var f3 = i1.GetMember<PropertySymbol>("F3"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f1.SetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f2.SetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f3.SetMethod.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Null(cctor); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "123", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { I1.TestHelper.F4Proxy(11,22,3); System.Console.WriteLine($""{I1.F1}{I1.F2}""); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1122"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1122"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,16): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static int F1 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F1").WithArguments("static", "7.3", "8.0").WithLocation(4, 16), // (4,33): error CS8703: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static int F1 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("private", "7.3", "8.0").WithLocation(4, 33), // (5,23): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static int F2 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("static", "7.3", "8.0").WithLocation(5, 23), // (5,23): error CS8703: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static int F2 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("public", "7.3", "8.0").WithLocation(5, 23), // (5,40): error CS8703: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static int F2 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("private", "7.3", "8.0").WithLocation(5, 40), // (6,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static int F3 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("static", "7.3", "8.0").WithLocation(6, 25), // (6,25): error CS8703: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static int F3 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("internal", "7.3", "8.0").WithLocation(6, 25), // (6,42): error CS8703: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static int F3 {get; private set;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("private", "7.3", "8.0").WithLocation(6, 42), // (8,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(8, 18) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,20): error CS8701: Target runtime doesn't support default interface implementation. // static int F1 {get; private set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(4, 20), // (4,33): error CS8701: Target runtime doesn't support default interface implementation. // static int F1 {get; private set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(4, 33), // (5,27): error CS8701: Target runtime doesn't support default interface implementation. // public static int F2 {get; private set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(5, 27), // (5,40): error CS8701: Target runtime doesn't support default interface implementation. // public static int F2 {get; private set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(5, 40), // (6,29): error CS8701: Target runtime doesn't support default interface implementation. // internal static int F3 {get; private set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(6, 29), // (6,42): error CS8701: Target runtime doesn't support default interface implementation. // internal static int F3 {get; private set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(6, 42) ); Validate1(compilation5.SourceModule); } [Fact] public void FieldLikeEvent_01() { var source1 = @" public interface I1 { private event System.Action F1; private event System.Action F5 = null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyEmitDiagnostics( // (4,33): error CS0065: 'I1.F1': event property must have both add and remove accessors // private event System.Action F1; Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "F1").WithArguments("I1.F1").WithLocation(4, 33), // (5,33): error CS0068: 'I1.F5': instance event in interface cannot have initializer // private event System.Action F5 = null; Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "F5").WithArguments("I1.F5").WithLocation(5, 33), // (5,33): error CS0065: 'I1.F5': event property must have both add and remove accessors // private event System.Action F5 = null; Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "F5").WithArguments("I1.F5").WithLocation(5, 33), // (5,33): warning CS0067: The event 'I1.F5' is never used // private event System.Action F5 = null; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "F5").WithArguments("I1.F5").WithLocation(5, 33), // (4,33): warning CS0067: The event 'I1.F1' is never used // private event System.Action F1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "F1").WithArguments("I1.F1").WithLocation(4, 33) ); } [Fact] public void FieldLikeEvent_02() { var source1 = @" public interface I1 { static event System.Action F1; public static event System.Action F2; internal static event System.Action F3; private static event System.Action F4; public class TestHelper { public static System.Action F4Proxy { set => I1.F4 += value; } public static void Raise() { F1(); F2(); F3?.Invoke(); F4(); } } } class Test1 : I1 { static void Main() { I1.F1 += () => System.Console.Write(1); I1.F2 += () => System.Console.Write(2); I1.F3 += () => System.Console.Write(3); I1.TestHelper.F4Proxy = () => System.Console.Write(4); I1.TestHelper.Raise(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<EventSymbol>("F1"); var f2 = i1.GetMember<EventSymbol>("F2"); var f3 = i1.GetMember<EventSymbol>("F3"); var f4 = i1.GetMember<EventSymbol>("F4"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f4.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Null(cctor); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { I1.F1 += () => System.Console.Write(11); I1.F2 += () => System.Console.Write(22); I1.TestHelper.F4Proxy = () => System.Console.Write(44); I1.TestHelper.Raise(); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "112244"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "112244"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (9,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(9, 18), // (4,32): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static event System.Action F1; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F1").WithArguments("static", "7.3", "8.0").WithLocation(4, 32), // (5,39): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static event System.Action F2; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("static", "7.3", "8.0").WithLocation(5, 39), // (5,39): error CS8503: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static event System.Action F2; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("public", "7.3", "8.0").WithLocation(5, 39), // (6,41): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static event System.Action F3; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("static", "7.3", "8.0").WithLocation(6, 41), // (6,41): error CS8503: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static event System.Action F3; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("internal", "7.3", "8.0").WithLocation(6, 41), // (7,40): error CS8503: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static event System.Action F4; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("static", "7.3", "8.0").WithLocation(7, 40), // (7,40): error CS8503: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static event System.Action F4; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("private", "7.3", "8.0").WithLocation(7, 40) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,32): error CS8701: Target runtime doesn't support default interface implementation. // static event System.Action F1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F1").WithLocation(4, 32), // (5,39): error CS8701: Target runtime doesn't support default interface implementation. // public static event System.Action F2; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F2").WithLocation(5, 39), // (6,41): error CS8701: Target runtime doesn't support default interface implementation. // internal static event System.Action F3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F3").WithLocation(6, 41), // (7,40): error CS8701: Target runtime doesn't support default interface implementation. // private static event System.Action F4; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F4").WithLocation(7, 40) ); Validate1(compilation5.SourceModule); } [Fact] public void FieldLikeEvent_03() { var source1 = @" public interface I1 { static event System.Action F1 = () => System.Console.Write(1); public static event System.Action F2 = () => System.Console.Write(2); internal static event System.Action F3 = () => System.Console.Write(3); private static event System.Action F4 = () => System.Console.Write(4); public class TestHelper { public static void Raise() { F1(); F2(); F3(); F4(); } } } class Test1 : I1 { static void Main() { I1.TestHelper.Raise(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); void Validate1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var f1 = i1.GetMember<EventSymbol>("F1"); var f2 = i1.GetMember<EventSymbol>("F2"); var f3 = i1.GetMember<EventSymbol>("F3"); var f4 = i1.GetMember<EventSymbol>("F4"); Assert.True(f1.IsStatic); Assert.True(f2.IsStatic); Assert.True(f3.IsStatic); Assert.True(f4.IsStatic); Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, f2.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, f3.DeclaredAccessibility); Assert.Equal(Accessibility.Private, f4.DeclaredAccessibility); var cctor = i1.GetMember<MethodSymbol>(".cctor"); Assert.Equal(MethodKind.StaticConstructor, cctor.MethodKind); } Validate1(compilation1.SourceModule); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", symbolValidator: Validate1); var source2 = @" class Test2 : I1 { static void Main() { I1.TestHelper.Raise(); } } "; var compilation2 = CreateCompilation(source2, new[] { compilation1.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234"); var compilation3 = CreateCompilation(source2, new[] { compilation1.EmitToImageReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234"); var compilation4 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (9,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public class TestHelper Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "TestHelper").WithArguments("default interface implementation", "8.0").WithLocation(9, 18), // (4,32): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // static event System.Action F1 = () => System.Console.Write(1); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F1").WithArguments("static", "7.3", "8.0").WithLocation(4, 32), // (5,39): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static event System.Action F2 = () => System.Console.Write(2); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("static", "7.3", "8.0").WithLocation(5, 39), // (5,39): error CS8703: The modifier 'public' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // public static event System.Action F2 = () => System.Console.Write(2); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F2").WithArguments("public", "7.3", "8.0").WithLocation(5, 39), // (6,41): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static event System.Action F3 = () => System.Console.Write(3); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("static", "7.3", "8.0").WithLocation(6, 41), // (6,41): error CS8703: The modifier 'internal' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // internal static event System.Action F3 = () => System.Console.Write(3); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F3").WithArguments("internal", "7.3", "8.0").WithLocation(6, 41), // (7,40): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static event System.Action F4 = () => System.Console.Write(4); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("static", "7.3", "8.0").WithLocation(7, 40), // (7,40): error CS8703: The modifier 'private' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // private static event System.Action F4 = () => System.Console.Write(4); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "F4").WithArguments("private", "7.3", "8.0").WithLocation(7, 40) ); Validate1(compilation4.SourceModule); var compilation5 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation5.VerifyDiagnostics( // (4,32): error CS8701: Target runtime doesn't support default interface implementation. // static event System.Action F1 = () => System.Console.Write(1); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F1").WithLocation(4, 32), // (5,39): error CS8701: Target runtime doesn't support default interface implementation. // public static event System.Action F2 = () => System.Console.Write(2); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F2").WithLocation(5, 39), // (6,41): error CS8701: Target runtime doesn't support default interface implementation. // internal static event System.Action F3 = () => System.Console.Write(3); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F3").WithLocation(6, 41), // (7,40): error CS8701: Target runtime doesn't support default interface implementation. // private static event System.Action F4 = () => System.Console.Write(4); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "F4").WithLocation(7, 40) ); Validate1(compilation5.SourceModule); } [Fact] public void UnsupportedMemberAccess_01() { var source0 = @" public delegate void D0(); public interface I0 { static readonly int F1 = 1; static int P2 {get {System.Console.WriteLine(""P2""); return 2;} set {System.Console.WriteLine(""set_P2"");}} static void M3() {System.Console.WriteLine(""M3"");} static event D0 E4 { add {System.Console.WriteLine(""add E4"");value();} remove {System.Console.WriteLine(""remove E4"");value();} } class C6 { public static void M() {System.Console.WriteLine(""C6.M"");} } } "; var source1 = @" public delegate void D1(); public interface I1 { int P20 {get {System.Console.WriteLine(""P20""); return 20;}} int this[int P50] {set {System.Console.WriteLine(""P50"");}} void M30() {System.Console.WriteLine(""M30"");} event D1 E40 { add {System.Console.WriteLine(""add E40"");value();} remove {System.Console.WriteLine(""remove E40"");value();} } sealed int P200 {get {System.Console.WriteLine(""P200""); return 200;}} sealed int this[string P500] {set {System.Console.WriteLine(""P500"");}} sealed void M300() {System.Console.WriteLine(""M300"");} sealed event D1 E400 { add {System.Console.WriteLine(""add E400"");value();} remove {System.Console.WriteLine(""remove E400"");value();} } } public class Test1 : I1 { } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source2 = @" class Test2 { static void Main() { System.Console.WriteLine(I0.F1); System.Console.WriteLine(I0.P2); I0.M3(); I0.E4 += I0.M3; I0.E4 -= new D0(I0.M3); I0.P2 = 3; I0.C6.M(); } } "; var source3 = @" class Test3 { static void Main() { I1 i1 = new Test1(); System.Console.WriteLine(i1.P20); i1.M30(); i1.E40 += i1.M30; i1.E40 -= new D1(i1.M30); i1[50] = default; } } "; var source4 = @" class Test4 : Test1 { static void Main() { I1 i1 = new Test1(); System.Console.WriteLine(i1.P200); i1.M300(); i1.E400 += i1.M300; i1.E400 -= new D1(i1.M300); i1[""500""] = default; } } "; foreach (var refs in new[] { (comp0:compilation0.ToMetadataReference(), comp1:compilation1.ToMetadataReference()), (comp0:compilation0.EmitToImageReference(), comp1:compilation1.EmitToImageReference()) }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.StandardLatest); compilation2 = compilation2.AddReferences(refs.comp0); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"1 P2 2 M3 add E4 M3 remove E4 M3 set_P2 C6.M "); var compilation3 = CreateCompilation(source3, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.StandardLatest); compilation3 = compilation3.AddReferences(refs.comp1); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"P20 20 M30 add E40 M30 remove E40 M30 P50 "); var compilation4 = CreateCompilation(source4, options: TestOptions.DebugExe, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); compilation4 = compilation4.AddReferences(refs.comp1); Assert.False(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics( // (7,34): error CS8501: Target runtime doesn't support default interface implementation. // System.Console.WriteLine(i1.P200); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.P200").WithLocation(7, 34), // (8,9): error CS8501: Target runtime doesn't support default interface implementation. // i1.M300(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.M300").WithLocation(8, 9), // (9,9): error CS8501: Target runtime doesn't support default interface implementation. // i1.E400 += i1.M300; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.E400 += i1.M300").WithLocation(9, 9), // (9,20): error CS8501: Target runtime doesn't support default interface implementation. // i1.E400 += i1.M300; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.M300").WithLocation(9, 20), // (10,9): error CS8501: Target runtime doesn't support default interface implementation. // i1.E400 -= new D1(i1.M300); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.E400 -= new D1(i1.M300)").WithLocation(10, 9), // (10,27): error CS8501: Target runtime doesn't support default interface implementation. // i1.E400 -= new D1(i1.M300); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.M300").WithLocation(10, 27), // (11,9): error CS8701: Target runtime doesn't support default interface implementation. // i1["500"] = default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, @"i1[""500""]").WithLocation(11, 9) ); } } [Fact] public void UnsupportedMemberAccess_02() { var source0 = @" public delegate void D0(); public interface I0 { static protected readonly int F1 = 1; static protected internal int P2 {get {System.Console.WriteLine(""P2""); return 2;} set {System.Console.WriteLine(""set_P2"");}} static protected void M3() {System.Console.WriteLine(""M3"");} static protected internal event D0 E4 { add {System.Console.WriteLine(""add E4"");value();} remove {System.Console.WriteLine(""remove E4"");value();} } protected internal class C6 { public static void M() {System.Console.WriteLine(""C6.M"");} } protected class C7<T> { } static int P8 {protected internal get {System.Console.WriteLine(""P8""); return 8;} set {System.Console.WriteLine(""set_P8"");}} static int P9 {get {System.Console.WriteLine(""P9""); return 9;} protected set {System.Console.WriteLine(""set_P9"");}} } public class Test1 : I0 { } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var source2 = @" using static I0; class Test2 : Test1 { static void Main() { System.Console.WriteLine(I0.F1); System.Console.WriteLine(I0.P2); I0.M3(); I0.E4 += I0.M3; I0.E4 -= new D0(I0.M3); I0.P2 = 3; I0.C6.M(); _ = new C7<int>(); _ = I0.P8; _ = I0.P9; I0.P8 = 12; I0.P9 = 13; } } "; foreach (var reference in new[] { compilation0.ToMetadataReference(), compilation0.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { reference }, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics( // (9,34): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // System.Console.WriteLine(I0.F1); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.F1").WithLocation(9, 34), // (10,34): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // System.Console.WriteLine(I0.P2); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.P2").WithLocation(10, 34), // (11,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.M3(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.M3").WithLocation(11, 9), // (12,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.E4 += I0.M3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.E4 += I0.M3").WithLocation(12, 9), // (12,18): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.E4 += I0.M3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.M3").WithLocation(12, 18), // (13,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.E4 -= new D0(I0.M3); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.E4 -= new D0(I0.M3)").WithLocation(13, 9), // (13,25): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.E4 -= new D0(I0.M3); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.M3").WithLocation(13, 25), // (14,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.P2 = 3; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.P2").WithLocation(14, 9), // (15,12): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.C6.M(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "C6").WithLocation(15, 12), // (16,17): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // _ = new C7<int>(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "C7<int>").WithLocation(16, 17), // (17,13): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // _ = I0.P8; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.P8").WithLocation(17, 13), // (20,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // I0.P9 = 13; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I0.P9").WithLocation(20, 9) ); } } [Fact] public void UnsupportedMemberAccess_03() { var source1 = @" public delegate void D1(); public interface I1 { protected int P20 {get {System.Console.WriteLine(""P20""); return 20;}} protected internal int this[int P50] {set {System.Console.WriteLine(""P50"");}} protected void M30() {System.Console.WriteLine(""M30"");} protected internal event D1 E40 { add {System.Console.WriteLine(""add E40"");value();} remove {System.Console.WriteLine(""remove E40"");value();} } int P50 {protected get {System.Console.WriteLine(""P50""); return 50;} set {}} int P60 {get {System.Console.WriteLine(""P60""); return 60;} protected internal set {}} protected internal sealed int P200 {get {System.Console.WriteLine(""P200""); return 200;}} protected sealed int this[string P500] {set {System.Console.WriteLine(""P500"");}} protected internal sealed void M300() {System.Console.WriteLine(""M300"");} protected sealed event D1 E400 { add {System.Console.WriteLine(""add E400"");value();} remove {System.Console.WriteLine(""remove E400"");value();} } sealed int P500 {protected get {System.Console.WriteLine(""P500""); return 500;} set {}} sealed int P600 {get {System.Console.WriteLine(""P600""); return 600;} protected internal set {}} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source3 = @" interface Test3 : I1 { static void Main() { Test3 i1 = null; System.Console.WriteLine(i1.P20); i1.M30(); i1.E40 += i1.M30; i1.E40 -= new D1(i1.M30); i1[50] = default; _ = i1.P50; _ = i1.P60; i1.P50 = 12; i1.P60 = 13; } } "; var source4 = @" interface Test4 : I1 { static void Main() { Test4 i1 = null; System.Console.WriteLine(i1.P200); i1.M300(); i1.E400 += i1.M300; i1.E400 -= new D1(i1.M300); i1[""500""] = default; _ = i1.P500; _ = i1.P600; i1.P500 = 12; i1.P600 = 13; } } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation3 = CreateCompilation(source3, options: TestOptions.DebugExe, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { reference }, parseOptions: TestOptions.Regular); compilation3.VerifyDiagnostics( // (4,17): error CS8701: Target runtime doesn't support default interface implementation. // static void Main() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "Main").WithLocation(4, 17), // (7,34): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // System.Console.WriteLine(i1.P20); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.P20").WithLocation(7, 34), // (8,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // i1.M30(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.M30").WithLocation(8, 9), // (9,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // i1.E40 += i1.M30; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.E40 += i1.M30").WithLocation(9, 9), // (9,19): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // i1.E40 += i1.M30; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.M30").WithLocation(9, 19), // (10,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // i1.E40 -= new D1(i1.M30); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.E40 -= new D1(i1.M30)").WithLocation(10, 9), // (10,26): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // i1.E40 -= new D1(i1.M30); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.M30").WithLocation(10, 26), // (11,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // i1[50] = default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1[50]").WithLocation(11, 9), // (12,13): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // _ = i1.P50; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.P50").WithLocation(12, 13), // (15,9): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // i1.P60 = 13; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "i1.P60").WithLocation(15, 9) ); var compilation4 = CreateCompilation(source4, options: TestOptions.DebugExe, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { reference }, parseOptions: TestOptions.Regular); Assert.False(compilation4.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation4.VerifyDiagnostics( // (4,17): error CS8701: Target runtime doesn't support default interface implementation. // static void Main() Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "Main").WithLocation(4, 17), // (7,34): error CS8701: Target runtime doesn't support default interface implementation. // System.Console.WriteLine(i1.P200); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.P200").WithLocation(7, 34), // (8,9): error CS8701: Target runtime doesn't support default interface implementation. // i1.M300(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.M300").WithLocation(8, 9), // (9,9): error CS8701: Target runtime doesn't support default interface implementation. // i1.E400 += i1.M300; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.E400 += i1.M300").WithLocation(9, 9), // (9,20): error CS8701: Target runtime doesn't support default interface implementation. // i1.E400 += i1.M300; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.M300").WithLocation(9, 20), // (10,9): error CS8701: Target runtime doesn't support default interface implementation. // i1.E400 -= new D1(i1.M300); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.E400 -= new D1(i1.M300)").WithLocation(10, 9), // (10,27): error CS8701: Target runtime doesn't support default interface implementation. // i1.E400 -= new D1(i1.M300); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.M300").WithLocation(10, 27), // (11,9): error CS8701: Target runtime doesn't support default interface implementation. // i1["500"] = default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, @"i1[""500""]").WithLocation(11, 9), // (12,13): error CS8701: Target runtime doesn't support default interface implementation. // _ = i1.P500; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.P500").WithLocation(12, 13), // (13,13): error CS8701: Target runtime doesn't support default interface implementation. // _ = i1.P600; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.P600").WithLocation(13, 13), // (14,9): error CS8701: Target runtime doesn't support default interface implementation. // i1.P500 = 12; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.P500").WithLocation(14, 9), // (15,9): error CS8701: Target runtime doesn't support default interface implementation. // i1.P600 = 13; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "i1.P600").WithLocation(15, 9) ); } } [Fact] public void UnsupportedMemberAccess_04() { var source1 = @" public interface I1 { protected interface I2 {} protected internal interface I3 {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics(); var source3 = @" interface Test3 : I1 { class C { static void M1(I1.I2 x) { System.Console.WriteLine(""M1""); } static void M2(I1.I3 x) { System.Console.WriteLine(""M2""); } static void Main() { M1(null); M2(null); } } } "; var source4 = @" class Test4 : I1 { interface Test5 : I1.I2 { } interface Test6 : I1.I3 { } } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation3 = CreateCompilation(source3, options: TestOptions.DebugExe, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { reference }, parseOptions: TestOptions.Regular); compilation3.VerifyDiagnostics( // (6,27): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // static void M1(I1.I2 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I2").WithLocation(6, 27), // (11,27): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // static void M2(I1.I3 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I3").WithLocation(11, 27) ); var compilation4 = CreateCompilation(source4, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { reference }, parseOptions: TestOptions.Regular); compilation4.VerifyDiagnostics( // (4,26): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // interface Test5 : I1.I2 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I2").WithLocation(4, 26), // (8,26): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. // interface Test6 : I1.I3 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "I3").WithLocation(8, 26) ); } } [Fact] public void EntryPoint_01() { var source1 = @" public interface I1 { static void Main() { System.Console.WriteLine(""I1.Main""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "I1.Main"); } [Fact] public void EntryPoint_02() { var source1 = @" public interface I1 { static void Main() { System.Console.WriteLine(""I1.Main""); } } public interface I2 { static void Main() { System.Console.WriteLine(""I2.Main""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe.WithMainTypeName("I2"), parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "I2.Main"); } [Fact] public void Operators_01() { var source1 = @" public interface I1 { public static I1 operator +(I1 x) { System.Console.WriteLine(""+""); return x; } public static I1 operator -(I1 x) { System.Console.WriteLine(""-""); return x; } public static I1 operator !(I1 x) { System.Console.WriteLine(""!""); return x; } public static I1 operator ~(I1 x) { System.Console.WriteLine(""~""); return x; } public static I1 operator ++(I1 x) { System.Console.WriteLine(""++""); return x; } public static I1 operator --(I1 x) { System.Console.WriteLine(""--""); return x; } public static bool operator true(I1 x) { System.Console.WriteLine(""true""); return true; } public static bool operator false(I1 x) { System.Console.WriteLine(""false""); return false; } public static I1 operator +(I1 x, I1 y) { System.Console.WriteLine(""+2""); return x; } public static I1 operator -(I1 x, I1 y) { System.Console.WriteLine(""-2""); return x; } public static I1 operator *(I1 x, I1 y) { System.Console.WriteLine(""*""); return x; } public static I1 operator /(I1 x, I1 y) { System.Console.WriteLine(""/""); return x; } public static I1 operator %(I1 x, I1 y) { System.Console.WriteLine(""%""); return x; } public static I1 operator &(I1 x, I1 y) { System.Console.WriteLine(""&""); return x; } public static I1 operator |(I1 x, I1 y) { System.Console.WriteLine(""|""); return x; } public static I1 operator ^(I1 x, I1 y) { System.Console.WriteLine(""^""); return x; } public static I1 operator <<(I1 x, int y) { System.Console.WriteLine(""<<""); return x; } public static I1 operator >>(I1 x, int y) { System.Console.WriteLine("">>""); return x; } public static I1 operator >(I1 x, I1 y) { System.Console.WriteLine("">""); return x; } public static I1 operator <(I1 x, I1 y) { System.Console.WriteLine(""<""); return x; } public static I1 operator >=(I1 x, I1 y) { System.Console.WriteLine("">=""); return x; } public static I1 operator <=(I1 x, I1 y) { System.Console.WriteLine(""<=""); return x; } } "; var source2 = @" class Test2 : I1 { static void Main() { I1 x = new Test2(); I1 y = new Test2(); x = +x; x = -x; x = !x; x = ~x; x = ++x; x = x--; x = x + y; x = x - y; x = x * y; x = x / y; x = x % y; if (x && y) { } x = x | y; x = x ^ y; x = x << 1; x = x >> 2; x = x > y; x = x < y; x = x >= y; x = x <= y; } } "; var expectedOutput = @" + - ! ~ ++ -- +2 -2 * / % false & true | ^ << >> > < >= <= "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr); var compilation6 = CreateCompilation(source1 + source2, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular7_3); compilation6.VerifyDiagnostics( // (4,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator +(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "+").WithArguments("default interface implementation", "8.0").WithLocation(4, 31), // (10,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator -(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(10, 31), // (16,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator !(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "!").WithArguments("default interface implementation", "8.0").WithLocation(16, 31), // (22,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator ~(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "~").WithArguments("default interface implementation", "8.0").WithLocation(22, 31), // (28,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator ++(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "++").WithArguments("default interface implementation", "8.0").WithLocation(28, 31), // (34,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator --(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "--").WithArguments("default interface implementation", "8.0").WithLocation(34, 31), // (40,33): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static bool operator true(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "true").WithArguments("default interface implementation", "8.0").WithLocation(40, 33), // (46,33): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static bool operator false(I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "false").WithArguments("default interface implementation", "8.0").WithLocation(46, 33), // (52,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator +(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "+").WithArguments("default interface implementation", "8.0").WithLocation(52, 31), // (58,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator -(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(58, 31), // (64,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator *(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "*").WithArguments("default interface implementation", "8.0").WithLocation(64, 31), // (70,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator /(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "/").WithArguments("default interface implementation", "8.0").WithLocation(70, 31), // (76,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator %(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "%").WithArguments("default interface implementation", "8.0").WithLocation(76, 31), // (82,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator &(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "&").WithArguments("default interface implementation", "8.0").WithLocation(82, 31), // (88,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator |(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "|").WithArguments("default interface implementation", "8.0").WithLocation(88, 31), // (94,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator ^(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "^").WithArguments("default interface implementation", "8.0").WithLocation(94, 31), // (100,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator <<(I1 x, int y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "<<").WithArguments("default interface implementation", "8.0").WithLocation(100, 31), // (106,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator >>(I1 x, int y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, ">>").WithArguments("default interface implementation", "8.0").WithLocation(106, 31), // (112,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator >(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, ">").WithArguments("default interface implementation", "8.0").WithLocation(112, 31), // (118,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator <(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "<").WithArguments("default interface implementation", "8.0").WithLocation(118, 31), // (124,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator >=(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, ">=").WithArguments("default interface implementation", "8.0").WithLocation(124, 31), // (130,31): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // public static I1 operator <=(I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "<=").WithArguments("default interface implementation", "8.0").WithLocation(130, 31) ); var compilation61 = CreateCompilation(source1 + source2, options: TestOptions.DebugDll, targetFramework: TargetFramework.DesktopLatestExtended, parseOptions: TestOptions.Regular); compilation61.VerifyDiagnostics( // (4,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator +(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "+").WithLocation(4, 31), // (10,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator -(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "-").WithLocation(10, 31), // (16,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator !(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "!").WithLocation(16, 31), // (22,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator ~(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "~").WithLocation(22, 31), // (28,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator ++(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "++").WithLocation(28, 31), // (34,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator --(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "--").WithLocation(34, 31), // (40,33): error CS8701: Target runtime doesn't support default interface implementation. // public static bool operator true(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "true").WithLocation(40, 33), // (46,33): error CS8701: Target runtime doesn't support default interface implementation. // public static bool operator false(I1 x) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "false").WithLocation(46, 33), // (52,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator +(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "+").WithLocation(52, 31), // (58,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator -(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "-").WithLocation(58, 31), // (64,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator *(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "*").WithLocation(64, 31), // (70,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator /(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "/").WithLocation(70, 31), // (76,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator %(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "%").WithLocation(76, 31), // (82,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator &(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "&").WithLocation(82, 31), // (88,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator |(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "|").WithLocation(88, 31), // (94,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator ^(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "^").WithLocation(94, 31), // (100,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator <<(I1 x, int y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "<<").WithLocation(100, 31), // (106,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator >>(I1 x, int y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, ">>").WithLocation(106, 31), // (112,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator >(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, ">").WithLocation(112, 31), // (118,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator <(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "<").WithLocation(118, 31), // (124,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator >=(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, ">=").WithLocation(124, 31), // (130,31): error CS8701: Target runtime doesn't support default interface implementation. // public static I1 operator <=(I1 x, I1 y) Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "<=").WithLocation(130, 31) ); var compilation7 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular7_3); var expected7 = new DiagnosticDescription[] { // (9,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = +x; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "+x").WithArguments("default interface implementation", "8.0").WithLocation(9, 13), // (10,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = -x; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-x").WithArguments("default interface implementation", "8.0").WithLocation(10, 13), // (11,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = !x; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "!x").WithArguments("default interface implementation", "8.0").WithLocation(11, 13), // (12,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = ~x; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "~x").WithArguments("default interface implementation", "8.0").WithLocation(12, 13), // (13,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = ++x; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "++x").WithArguments("default interface implementation", "8.0").WithLocation(13, 13), // (14,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x--; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x--").WithArguments("default interface implementation", "8.0").WithLocation(14, 13), // (16,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x + y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x + y").WithArguments("default interface implementation", "8.0").WithLocation(16, 13), // (17,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x - y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x - y").WithArguments("default interface implementation", "8.0").WithLocation(17, 13), // (18,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x * y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x * y").WithArguments("default interface implementation", "8.0").WithLocation(18, 13), // (19,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x / y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x / y").WithArguments("default interface implementation", "8.0").WithLocation(19, 13), // (20,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x % y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x % y").WithArguments("default interface implementation", "8.0").WithLocation(20, 13), // (21,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // if (x && y) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x && y").WithArguments("default interface implementation", "8.0").WithLocation(21, 13), // (21,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // if (x && y) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x && y").WithArguments("default interface implementation", "8.0").WithLocation(21, 13), // (22,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x | y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x | y").WithArguments("default interface implementation", "8.0").WithLocation(22, 13), // (23,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x ^ y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x ^ y").WithArguments("default interface implementation", "8.0").WithLocation(23, 13), // (24,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x << 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x << 1").WithArguments("default interface implementation", "8.0").WithLocation(24, 13), // (25,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x >> 2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x >> 2").WithArguments("default interface implementation", "8.0").WithLocation(25, 13), // (26,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x > y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x > y").WithArguments("default interface implementation", "8.0").WithLocation(26, 13), // (27,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x < y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x < y").WithArguments("default interface implementation", "8.0").WithLocation(27, 13), // (28,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x >= y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x >= y").WithArguments("default interface implementation", "8.0").WithLocation(28, 13), // (29,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x <= y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x <= y").WithArguments("default interface implementation", "8.0").WithLocation(29, 13) }; compilation7.VerifyDiagnostics(expected7); var compilation8 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular7_3); compilation8.VerifyDiagnostics(expected7); var source3 = @" class Test3 : I1 { static void Main() { I1 x = new Test3(); I1 y = new Test3(); if (x) { } x = x & y; } } "; var compilation9 = CreateCompilation(source3, new[] { compilationReference }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular7_3); var expected9 = new DiagnosticDescription[] { // (8,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // if (x) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x").WithArguments("default interface implementation", "8.0").WithLocation(8, 13), // (9,13): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // x = x & y; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "x & y").WithArguments("default interface implementation", "8.0").WithLocation(9, 13) }; compilation9.VerifyDiagnostics(expected9); var compilation10 = CreateCompilation(source3, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation10.VerifyDiagnostics(expected9); } [Fact] public void Operators_02() { var source1 = @" public class C1 { public static int operator +(C1 x, I1 y) { System.Console.WriteLine(""C1.+""); return 0; } public static int operator -(I1 x, C1 y) { System.Console.WriteLine(""C1.-""); return 0; } } public class C2 : C1 {} class Test : I1 { static void Main() { I1 x = new Test(); C2 y = new C2(); var r = y + x; r = x - y; } } "; var source2 = @" public interface I1 { } "; var source3 = @" public interface I1 { public static int operator +(C2 x, I1 y) { System.Console.WriteLine(""I1.+""); return 0; } public static int operator -(I1 x, C2 y) { System.Console.WriteLine(""I1.-""); return 0; } } "; var expectedOutput = @" C1.+ C1.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr); var compilation2 = CreateCompilation(source1 + source3, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr); } [Fact] public void Operators_03() { var source1 = @" public interface I1 { public static I1 operator ==(I1 x, I1 y) { System.Console.WriteLine(""==""); return x; } public static I1 operator !=(I1 x, I1 y) { System.Console.WriteLine(""!=""); return x; } } "; var source2 = @" class Test2 : I1 { static void Main() { I1 x = new Test2(); I1 y = new Test2(); x = x == y; x = x != y; } } "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular9); compilation1.VerifyDiagnostics( // (4,31): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // public static I1 operator ==(I1 x, I1 y) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(4, 31), // (10,31): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // public static I1 operator !=(I1 x, I1 y) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(10, 31), // (24,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x = x == y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x == y").WithArguments("static abstract members in interfaces").WithLocation(24, 13), // (25,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x = x != y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x != y").WithArguments("static abstract members in interfaces").WithLocation(25, 13) ); CreateCompilation(source1 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (4,31): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // public static I1 operator ==(I1 x, I1 y) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(4, 31), // (10,31): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // public static I1 operator !=(I1 x, I1 y) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(10, 31) ); CompilationReference compilationReference = compilation1.ToMetadataReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (9,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x = x == y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x == y").WithArguments("static abstract members in interfaces").WithLocation(9, 13), // (10,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x = x != y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x != y").WithArguments("static abstract members in interfaces").WithLocation(10, 13) ); var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig specialname static class I1 op_Equality(class I1 x, class I1 y) cil managed { // Code size 18 (0x12) .maxstack 1 .locals init (class I1 V_0) IL_0000: nop IL_0001: ldstr ""=="" IL_0006: call void [mscorlib]System.Console::WriteLine(string) IL_000b: nop IL_000c: ldarg.0 IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } // end of method I1::op_Equality .method public hidebysig specialname static class I1 op_Inequality(class I1 x, class I1 y) cil managed { // Code size 18 (0x12) .maxstack 1 .locals init (class I1 V_0) IL_0000: nop IL_0001: ldstr ""!="" IL_0006: call void [mscorlib]System.Console::WriteLine(string) IL_000b: nop IL_000c: ldarg.0 IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } // end of method I1::op_Inequality } // end of class I1 "; var compilation3 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" == != ").VerifyDiagnostics(); CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (9,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x = x == y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x == y").WithArguments("static abstract members in interfaces").WithLocation(9, 13), // (10,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x = x != y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x != y").WithArguments("static abstract members in interfaces").WithLocation(10, 13) ); var source3 = @" class Test2 : I1 { static void Main() { I1 x = new Test2(); I1 y = new Test2(); System.Console.WriteLine(x == y); System.Console.WriteLine(x != y); } } "; var compilation4 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); compilation4.VerifyDiagnostics(); CompileAndVerify(compilation4, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @" == Test2 != Test2 "); CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (9,34): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // System.Console.WriteLine(x == y); Diagnostic(ErrorCode.ERR_FeatureInPreview, "x == y").WithArguments("static abstract members in interfaces").WithLocation(9, 34), // (10,34): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // System.Console.WriteLine(x != y); Diagnostic(ErrorCode.ERR_FeatureInPreview, "x != y").WithArguments("static abstract members in interfaces").WithLocation(10, 34) ); } [Fact] public void Operators_04() { var source1 = @" public interface I1 { public static implicit operator int(I1 x) { return 0; } public static explicit operator byte(I1 x) { return 0; } public static void Test(I1 x) { int y = x; y = (int)x; var z = (byte)x; z = x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (4,37): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // public static implicit operator int(I1 x) Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 37), // (4,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // public static implicit operator int(I1 x) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(4, 37), // (8,37): error CS0552: 'I1.explicit operator byte(I1)': user-defined conversions to or from an interface are not allowed // public static explicit operator byte(I1 x) Diagnostic(ErrorCode.ERR_ConversionWithInterface, "byte").WithArguments("I1.explicit operator byte(I1)").WithLocation(8, 37), // (8,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // public static explicit operator byte(I1 x) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "byte").WithLocation(8, 37), // (15,17): error CS0029: Cannot implicitly convert type 'I1' to 'int' // int y = x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("I1", "int").WithLocation(15, 17), // (16,13): error CS0030: Cannot convert type 'I1' to 'int' // y = (int)x; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int)x").WithArguments("I1", "int").WithLocation(16, 13), // (17,17): error CS0030: Cannot convert type 'I1' to 'byte' // var z = (byte)x; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(byte)x").WithArguments("I1", "byte").WithLocation(17, 17), // (18,13): error CS0029: Cannot implicitly convert type 'I1' to 'byte' // z = x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("I1", "byte").WithLocation(18, 13) ); } [Fact] public void Operators_05() { var source1 = @" public interface I1 { public static I1 operator -(I1 x) { System.Console.WriteLine(""-""); return x; } } public interface I2 : I1 {} "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); I1 y = -x; } } "; var expectedOutput = @" - "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var source3 = @" class Test2 : I2 { static void Main() { Test2 x = new Test2(); I1 y = -x; } } "; var compilation9 = CreateCompilation(source3, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); var expected9 = new DiagnosticDescription[] { // (8,16): error CS0023: Operator '-' cannot be applied to operand of type 'Test2' // I1 y = -x; Diagnostic(ErrorCode.ERR_BadUnaryOp, "-x").WithArguments("-", "Test2").WithLocation(8, 16) }; compilation9.VerifyDiagnostics(expected9); var compilation10 = CreateCompilation(source3, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation10.VerifyDiagnostics(expected9); } [Fact] public void Operators_06() { var source1 = @" public interface I1 { public static I1 operator -(I1 x) { System.Console.WriteLine(""I1.-""); return x; } } public interface I2 : I1 { public static I2 operator -(I2 x) { System.Console.WriteLine(""I2.-""); return x; } } "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); var y = -x; } } "; var expectedOutput = @" I2.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_07() { var source1 = @" public interface I1 { public static I1 operator -(I1 x) { System.Console.WriteLine(""I1.-""); return x; } } public interface I3 { public static I3 operator -(I3 x) { System.Console.WriteLine(""I3.-""); return x; } } public interface I4 : I1, I3 { public static I4 operator -(I4 x) { System.Console.WriteLine(""I4.-""); return x; } } public interface I2 : I4 { } "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); var y = -x; } } "; var expectedOutput = @" I4.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_08() { var source1 = @" public interface I1 { public static I1 operator -(I1 x) { System.Console.WriteLine(""I1.-""); return x; } } public interface I3 { public static I3 operator -(I3 x) { System.Console.WriteLine(""I3.-""); return x; } } public interface I4 : I1, I3 { } public interface I2 : I4 { } "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); var y = -x; } } "; var expected = new DiagnosticDescription[] { // (7,17): error CS0035: Operator '-' is ambiguous on an operand of type 'I2' // var y = -x; Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "-x").WithArguments("-", "I2").WithLocation(7, 17) }; var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(expected); CompilationReference compilationReference = compilation1.ToMetadataReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); } [Fact] public void Operators_09() { var source1 = @" public interface I1 { public static I1 operator -(I1 x) { System.Console.WriteLine(""I1.-""); return x; } } "; var source2 = @" class Test1 : Test2, I1 {} class Test2 { static void Main() { Test(new Test1()); } static void Test<T>(T x) where T : Test2, I1 { var y = -x; } public static Test2 operator -(Test2 x) { System.Console.WriteLine(""Test2.-""); return x; } } "; var expectedOutput = @" Test2.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_10() { var source1 = @" public interface I1 { public static I1 operator -(I1 x) { System.Console.WriteLine(""I1.-""); return x; } } public interface I3 { public static I3 operator -(I3 x) { System.Console.WriteLine(""I3.-""); return x; } } public interface I4 : I1, I3 { public static I4 operator -(I4 x) { System.Console.WriteLine(""I4.-""); return x; } } public interface I2 : I4 { }"; var source2 = @" class Test1 : Test2, I2 {} class Test2 { static void Main() { Test(new Test1()); } static void Test<T>(T x) where T : Test2, I2 { var y = -x; } } "; var expectedOutput = @" I4.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_11() { var source0 = @" public interface I1 { } public interface I2 { } "; var source1 = @" public class C1 { public static C1 operator +(C1 x, I2 y) { System.Console.WriteLine(""C1.+1""); return x; } public static C1 operator +(C1 x, I1 y) { System.Console.WriteLine(""C1.+2""); return x; } } "; var source2 = @" public interface I3 : I1, I2 { } "; var source3 = @" class Test2 : I3 { static void Main() { I3 x = new Test2(); var y = new C1() + x; } } "; var expected = new DiagnosticDescription[] { // (7,17): error CS0034: Operator '+' is ambiguous on operands of type 'C1' and 'I3' // var y = new C1() + x; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "new C1() + x").WithArguments("+", "C1", "I3").WithLocation(7, 17) }; var compilation0 = CreateCompilation(source0 + source1 + source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); CompilationReference compilationReference0 = compilation0.ToMetadataReference(); MetadataReference metadataReference0 = compilation0.EmitToImageReference(); var compilation1 = CreateCompilation(source3, new[] { compilationReference0 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source3, new[] { metadataReference0 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); var source4 = @" public interface I1 { public static C1 operator +(C1 x, I1 y) { System.Console.WriteLine(""I1.+""); return x; } } public interface I2 { } "; var compilation3 = CreateCompilation(source4 + source1 + source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompilationReference compilationReference3 = compilation3.ToMetadataReference(); MetadataReference metadataReference3 = compilation3.EmitToImageReference(); var compilation4 = CreateCompilation(source3, new[] { compilationReference3 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics(expected); var compilation5 = CreateCompilation(source3, new[] { metadataReference3 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics(expected); var source5 = @" public interface I3 : I1, I2 { public static C1 operator +(C1 x, I3 y) { System.Console.WriteLine(""I3.+""); return x; } } "; var compilation6 = CreateCompilation(source4 + source1 + source5, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics(); CompilationReference compilationReference6 = compilation6.ToMetadataReference(); MetadataReference metadataReference6 = compilation6.EmitToImageReference(); var compilation7 = CreateCompilation(source3, new[] { compilationReference6 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics(expected); var compilation8 = CreateCompilation(source3, new[] { metadataReference6 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation8.VerifyDiagnostics(expected); } [Fact] public void Operators_12() { var source0 = @" public interface I1 { } public interface I2 { } "; var source1 = @" public class C1 { public static C1 operator +(I2 x, C1 y) { System.Console.WriteLine(""C1.+1""); return y; } public static C1 operator +(I1 x, C1 y) { System.Console.WriteLine(""C1.+2""); return y; } } "; var source2 = @" public interface I3 : I1, I2 { } "; var source3 = @" class Test2 : I3 { static void Main() { I3 x = new Test2(); var y = x + new C1(); } } "; var expected = new DiagnosticDescription[] { // (7,17): error CS0034: Operator '+' is ambiguous on operands of type 'I3' and 'C1' // var y = x + new C1(); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x + new C1()").WithArguments("+", "I3", "C1").WithLocation(7, 17) }; var compilation0 = CreateCompilation(source0 + source1 + source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); CompilationReference compilationReference0 = compilation0.ToMetadataReference(); MetadataReference metadataReference0 = compilation0.EmitToImageReference(); var compilation1 = CreateCompilation(source3, new[] { compilationReference0 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source3, new[] { metadataReference0 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); var source4 = @" public interface I1 { public static C1 operator +(I1 x, C1 y) { System.Console.WriteLine(""I1.+""); return y; } } public interface I2 { } "; var compilation3 = CreateCompilation(source4 + source1 + source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompilationReference compilationReference3 = compilation3.ToMetadataReference(); MetadataReference metadataReference3 = compilation3.EmitToImageReference(); var compilation4 = CreateCompilation(source3, new[] { compilationReference3 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics(expected); var compilation5 = CreateCompilation(source3, new[] { metadataReference3 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics(expected); var source5 = @" public interface I3 : I1, I2 { public static C1 operator +(I3 x, C1 y) { System.Console.WriteLine(""I3.+""); return y; } } "; var compilation6 = CreateCompilation(source4 + source1 + source5, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics(); CompilationReference compilationReference6 = compilation6.ToMetadataReference(); MetadataReference metadataReference6 = compilation6.EmitToImageReference(); var compilation7 = CreateCompilation(source3, new[] { compilationReference6 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics(expected); var compilation8 = CreateCompilation(source3, new[] { metadataReference6 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation8.VerifyDiagnostics(expected); } [Fact] public void Operators_13() { var source1 = @" public interface I1 { public static int operator +(I1 x, I2 y) { System.Console.WriteLine(""I1.+""); return 1; } } public interface I2 { public static int operator +(I1 x, I2 y) { System.Console.WriteLine(""I2.+""); return 2; } } "; var source2 = @" class Test2: I1, I2 { static void Main() { I1 x = new Test2(); I2 y = new Test2(); var z = x + y; z = y + x; } } "; var expected = new DiagnosticDescription[] { // (8,17): error CS0034: Operator '+' is ambiguous on operands of type 'I1' and 'I2' // var z = x + y; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x + y").WithArguments("+", "I1", "I2").WithLocation(8, 17), // (9,13): error CS0019: Operator '+' cannot be applied to operands of type 'I2' and 'I1' // z = y + x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "y + x").WithArguments("+", "I2", "I1").WithLocation(9, 13) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(expected); } [Fact] public void Operators_14() { var source1 = @" public interface I1 { public static int operator +(I2 x, I1 y) { System.Console.WriteLine(""I1.+""); return 1; } } public interface I2 : I1 { public static int operator +(I2 x, I1 y) { System.Console.WriteLine(""I2.+""); return 2; } } "; var source2 = @" class Test2 : I2 { static void Main() { I1 x = new Test2(); I2 y = new Test2(); var z = y + x; z = x + y; } } "; var expected = new DiagnosticDescription[] { // (8,17): error CS0034: Operator '+' is ambiguous on operands of type 'I2' and 'I1' // var z = y + x; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "y + x").WithArguments("+", "I2", "I1").WithLocation(8, 17), // (9,13): error CS0019: Operator '+' cannot be applied to operands of type 'I1' and 'I2' // z = x + y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x + y").WithArguments("+", "I1", "I2").WithLocation(9, 13) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(expected); } [Fact] public void Operators_15() { var source1 = @" public class I1 { public static int operator +(I1 x, C2 y) { System.Console.WriteLine(""I1.+1""); return 1; } public static int operator +(C2 x, I1 y) { System.Console.WriteLine(""I1.+2""); return 1; } } public class I2 : I1 { public static int operator +(I2 x, C1 y) { System.Console.WriteLine(""I2.+1""); return 1; } public static int operator +(C1 x, I2 y) { System.Console.WriteLine(""I2.+2""); return 1; } } public class C1 { } public class C2 : C1 { } "; var source2 = @" class Test2: I2 { static void Main() { I2 x = new Test2(); C2 y = new C2(); var z = x + y; z = y + x; } } "; var expectedOutput = @" I2.+1 I2.+2 "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_16() { var source1 = @" public interface I1<T> { public static int operator +(I1<T> x, I1<T> y) { System.Console.WriteLine(""I1.+""); return 1; } } "; var source2 = @" class Test2: I1<object> { static void Main() { I1<object> x = new Test2(); I1<dynamic> y = new Test2(); var z = x + y; z = y + x; } } "; var expectedOutput = @" I1.+ I1.+ "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_17() { var source1 = @" public interface I1 { public static I1 operator +(I1 x, C1 y) { System.Console.WriteLine(""I1.+1""); return x; } public static I1 operator +(C1 x, I1 y) { System.Console.WriteLine(""I1.+2""); return y; } } public interface I2 : I1 {} public class C1{} "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); C1 y = new C1(); var z = x + y; z = y + x; } } "; var expectedOutput = @" I1.+1 I1.+2 "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var source3 = @" class Test2 : I2 { static void Main() { Test2 x = new Test2(); C1 y = new C1(); var z = x + y; z = y + x; } } "; var compilation9 = CreateCompilation(source3, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); var expected9 = new DiagnosticDescription[] { // (8,17): error CS0019: Operator '+' cannot be applied to operands of type 'Test2' and 'C1' // var z = x + y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x + y").WithArguments("+", "Test2", "C1").WithLocation(8, 17), // (9,13): error CS0019: Operator '+' cannot be applied to operands of type 'C1' and 'Test2' // z = y + x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "y + x").WithArguments("+", "C1", "Test2").WithLocation(9, 13) }; compilation9.VerifyDiagnostics(expected9); var compilation10 = CreateCompilation(source3, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation10.VerifyDiagnostics(expected9); } [Fact] public void Operators_18() { var source1 = @" public interface I1 { public static int operator +(I1 x, I1 y) { System.Console.WriteLine(""I1.+""); return 1; } } public interface I2 : I1 {} "; var source2 = @" class Test2: I2 { static void Main() { I2 x = new Test2(); I1 y = new Test2(); var z = x + y; z = y + x; z = x + x; z = y + y; } } "; var expectedOutput = @" I1.+ I1.+ I1.+ I1.+ "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_19() { var source1 = @" public interface I1<T> { public static int operator +(I1<T> x, I1<T> y) { System.Console.WriteLine(""I1.+""); return 1; } } public interface I2<T> : I1<T> {} "; var source2 = @" class Test2: I2<object> { static void Main() { I2<object> x = new Test2(); I2<dynamic> y = new Test2(); var z = x + y; z = y + x; I1<object> u = x; I1<dynamic> v = y; z = y + u; z = u + y; z = x + v; z = v + x; } } "; var expectedOutput = @" I1.+ I1.+ I1.+ I1.+ I1.+ I1.+ "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_20() { var source1 = @" public interface I1 { public static I1 operator -(I1 x, I2 y) { System.Console.WriteLine(""I1.-""); return x; } } public interface I2 : I1 { public static I2 operator -(I1 x, I2 y) { System.Console.WriteLine(""I2.-""); return y; } } "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); I2 y = new Test2(); var z = x - y; } } "; var expectedOutput = @" I2.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_21() { var source1 = @" public interface I1 { public static I1 operator -(I1 x, I2 y) { System.Console.WriteLine(""I1.-""); return x; } } public interface I2 : I1 { public static I2 operator -(I1 x, I2 y) { System.Console.WriteLine(""I2.-""); return y; } } public interface I3 : I2 {} public interface I4 : I2, I1 {} public interface I5 : I1, I2 {} "; var source2 = @" class Test2 : I3, I4, I5 { static void Main() { I3 x3 = new Test2(); I3 y3 = new Test2(); var z = x3 - y3; I4 x4 = new Test2(); I4 y4 = new Test2(); z = x4 - y4; I5 x5 = new Test2(); I5 y5 = new Test2(); z = x5 - y5; } } "; var expectedOutput = @" I2.- I2.- I2.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_22() { var source1 = @" public interface I1 { public static I1 operator -(I1 x, I2 y) { System.Console.WriteLine(""I1.-""); return x; } } public interface I2 : I1 { public static I2 operator -(I1 x, I2 y) { System.Console.WriteLine(""I2.-""); return y; } } public interface I3 : I2 {} public interface I4 : I3 {} "; var source2 = @" class Test2 : I3, I4 { static void Main() { I3 x = new Test2(); I4 y = new Test2(); var z = x - y; z = y - x; } } "; var expectedOutput = @" I2.- I2.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_23() { var source1 = @" public interface I1 { public static int operator +(I1 x, I2 y) { System.Console.WriteLine(""I1.+""); return 1; } } public interface I2 : I1 { public static int operator +(I1 x, I2 y) { System.Console.WriteLine(""I2.+""); return 2; } } public interface I3 : I2 {} "; var source2 = @" class Test2 : I3 { static void Main() { I1 x = new Test2(); I3 y = new Test2(); var z = x + y; z = y + x; } } "; var expected = new DiagnosticDescription[] { // (8,17): error CS0034: Operator '+' is ambiguous on operands of type 'I1' and 'I3' // var z = x + y; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x + y").WithArguments("+", "I1", "I3").WithLocation(8, 17), // (9,13): error CS0019: Operator '+' cannot be applied to operands of type 'I3' and 'I1' // z = y + x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "y + x").WithArguments("+", "I3", "I1").WithLocation(9, 13) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(expected); } [Fact] public void Operators_24() { var source1 = @" public interface I1 { public static int operator +(I2 x, I1 y) { System.Console.WriteLine(""I1.+""); return 1; } } public interface I2 : I1 { public static int operator +(I2 x, I1 y) { System.Console.WriteLine(""I2.+""); return 2; } } public interface I3 : I2 {} "; var source2 = @" class Test2 : I3 { static void Main() { I1 x = new Test2(); I3 y = new Test2(); var z = y + x; z = x + y; } } "; var expected = new DiagnosticDescription[] { // (8,17): error CS0034: Operator '+' is ambiguous on operands of type 'I3' and 'I1' // var z = y + x; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "y + x").WithArguments("+", "I3", "I1").WithLocation(8, 17), // (9,13): error CS0019: Operator '+' cannot be applied to operands of type 'I1' and 'I3' // z = x + y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x + y").WithArguments("+", "I1", "I3").WithLocation(9, 13) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(expected); } [Fact] public void Operators_25() { var source1 = @" public interface I1 { public static I1 operator -(I1 x, I1 y) { System.Console.WriteLine(""I1.-""); return x; } } public interface I3 { public static I3 operator -(I3 x, I3 y) { System.Console.WriteLine(""I3.-""); return x; } } public interface I4 : I1, I3 { } public interface I2 : I4 { } "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); var y = x - x; } } "; var expected = new DiagnosticDescription[] { // (7,17): error CS0034: Operator '-' is ambiguous on operands of type 'I2' and 'I2' // var y = x - x; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x - x").WithArguments("-", "I2", "I2").WithLocation(7, 17) }; var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(expected); CompilationReference compilationReference = compilation1.ToMetadataReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(expected); } [Fact] public void Operators_26() { var source1 = @" public interface I1 { public static I1 operator -(I1 x, C1 y) { System.Console.WriteLine(""I1.-1""); return x; } public static I1 operator -(C1 x, I1 y) { System.Console.WriteLine(""I1.-2""); return y; } } public interface I3 { public static I3 operator -(I3 x, C2 y) { System.Console.WriteLine(""I3.-1""); return x; } public static I3 operator -(C2 x, I3 y) { System.Console.WriteLine(""I3.-2""); return y; } } public interface I4 { public static I4 operator -(I4 x, C1 y) { System.Console.WriteLine(""I4.-1""); return x; } public static I4 operator -(C1 x, I4 y) { System.Console.WriteLine(""I4.-2""); return y; } } public interface I5 : I1, I3, I4 { } public interface I2 : I5 { } public class C1{} public class C2 : C1{} "; var source2 = @" class Test2 : I2 { static void Main() { I2 x = new Test2(); var c = new C2(); var y = x - c; y = c - x; } } "; var expectedOutput = @" I3.-1 I3.-2 "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_27() { var source1 = @" public interface I1 { public static I1 operator -(I1 x, I1 y) { System.Console.WriteLine(""I1.-""); return x; } } "; var source2 = @" class Test1 : Test2, I1 {} class Test2 { static void Main() { Test(new Test1()); } static void Test<T>(T x) where T : Test2, I1 { var y = x - x; } public static Test2 operator -(Test2 x, Test2 y) { System.Console.WriteLine(""Test2.-""); return x; } } "; var expectedOutput = @" Test2.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_28() { var source1 = @" public interface I1 { public static I1 operator -(I1 x, C1 y) { System.Console.WriteLine(""I1.-1""); return x; } public static I1 operator -(C1 x, I1 y) { System.Console.WriteLine(""I1.-2""); return y; } } public interface I3 { public static I3 operator -(I3 x, C2 y) { System.Console.WriteLine(""I3.-1""); return x; } public static I3 operator -(C2 x, I3 y) { System.Console.WriteLine(""I3.-2""); return y; } } public interface I4 { public static I4 operator -(I4 x, C1 y) { System.Console.WriteLine(""I4.-1""); return x; } public static I4 operator -(C1 x, I4 y) { System.Console.WriteLine(""I4.-2""); return y; } } public interface I5 : I1, I3, I4 { } public interface I2 : I5 { } public class C1{} public class C2 : C1{} "; var source2 = @" class Test1 : Test2, I2 {} class Test2 { static void Main() { Test(new Test1()); } static void Test<T>(T x) where T : Test2, I2 { var c = new C2(); var y = c - x; y = x - c; } } "; var expectedOutput = @" I3.-2 I3.-1 "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] public void Operators_29() { var source1 = @" public interface I1 { public static I1 operator +(int x) => throw null; public static I1 operator -(int x) => throw null; public static I1 operator !(int x) => throw null; public static I1 operator ~(int x) => throw null; public static I1 operator ++(int x) => throw null; public static I1 operator --(int x) => throw null; public static bool operator true(int x) => throw null; public static bool operator false(int x) => throw null; public static I1 operator +(int x, int y) => throw null; public static I1 operator -(int x, int y) => throw null; public static I1 operator *(int x, int y) => throw null; public static I1 operator /(int x, int y) => throw null; public static I1 operator %(int x, int y) => throw null; public static I1 operator &(int x, int y) => throw null; public static I1 operator |(int x, int y) => throw null; public static I1 operator ^(int x, int y) => throw null; public static I1 operator <<(int x, int y) => throw null; public static I1 operator >>(int x, int y) => throw null; public static I1 operator >(int x, int y) => throw null; public static I1 operator <(int x, int y) => throw null; public static I1 operator >=(int x, int y) => throw null; public static I1 operator <=(int x, int y) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,31): error CS0562: The parameter of a unary operator must be the containing type // public static I1 operator +(int x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "+").WithLocation(4, 31), // (5,31): error CS0562: The parameter of a unary operator must be the containing type // public static I1 operator -(int x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "-").WithLocation(5, 31), // (6,31): error CS0562: The parameter of a unary operator must be the containing type // public static I1 operator !(int x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "!").WithLocation(6, 31), // (7,31): error CS0562: The parameter of a unary operator must be the containing type // public static I1 operator ~(int x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "~").WithLocation(7, 31), // (8,31): error CS0559: The parameter type for ++ or -- operator must be the containing type // public static I1 operator ++(int x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, "++").WithLocation(8, 31), // (9,31): error CS0559: The parameter type for ++ or -- operator must be the containing type // public static I1 operator --(int x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, "--").WithLocation(9, 31), // (10,33): error CS0562: The parameter of a unary operator must be the containing type // public static bool operator true(int x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "true").WithLocation(10, 33), // (11,33): error CS0562: The parameter of a unary operator must be the containing type // public static bool operator false(int x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "false").WithLocation(11, 33), // (12,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator +(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "+").WithLocation(12, 31), // (13,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator -(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "-").WithLocation(13, 31), // (14,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator *(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "*").WithLocation(14, 31), // (15,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator /(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "/").WithLocation(15, 31), // (16,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator %(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "%").WithLocation(16, 31), // (17,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator &(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "&").WithLocation(17, 31), // (18,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator |(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "|").WithLocation(18, 31), // (19,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator ^(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "^").WithLocation(19, 31), // (20,31): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static I1 operator <<(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, "<<").WithLocation(20, 31), // (21,31): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static I1 operator >>(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, ">>").WithLocation(21, 31), // (22,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator >(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, ">").WithLocation(22, 31), // (23,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator <(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "<").WithLocation(23, 31), // (24,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator >=(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, ">=").WithLocation(24, 31), // (25,31): error CS0563: One of the parameters of a binary operator must be the containing type // public static I1 operator <=(int x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "<=").WithLocation(25, 31) ); } [Fact] public void Operators_30() { var source1 = @" public interface I1 { public static I1 operator <<(I1 x, I1 y) => throw null; public static I1 operator >>(I1 x, I1 y) => throw null; } public interface I2 { public static bool operator true(I2 x) => throw null; } public interface I3 { public static bool operator false(I3 x) => throw null; } public interface I4 { public static int operator true(I4 x) => throw null; public static int operator false(I4 x) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,31): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static I1 operator <<(I1 x, I1 y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, "<<").WithLocation(4, 31), // (5,31): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static I1 operator >>(I1 x, I1 y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, ">>").WithLocation(5, 31), // (10,33): error CS0216: The operator 'I2.operator true(I2)' requires a matching operator 'false' to also be defined // public static bool operator true(I2 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "true").WithArguments("I2.operator true(I2)", "false").WithLocation(10, 33), // (15,33): error CS0216: The operator 'I3.operator false(I3)' requires a matching operator 'true' to also be defined // public static bool operator false(I3 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "false").WithArguments("I3.operator false(I3)", "true").WithLocation(15, 33), // (20,32): error CS0215: The return type of operator True or False must be bool // public static int operator true(I4 x) => throw null; Diagnostic(ErrorCode.ERR_OpTFRetType, "true").WithLocation(20, 32), // (21,32): error CS0215: The return type of operator True or False must be bool // public static int operator false(I4 x) => throw null; Diagnostic(ErrorCode.ERR_OpTFRetType, "false").WithLocation(21, 32) ); } [Fact] public void Operators_31() { var source1 = @" public interface I1 { public static I1 operator -(I1 x) { System.Console.WriteLine(""I1.-""); return x; } } public interface I2 : I1 { public static I2 operator -(I2 x) { System.Console.WriteLine(""I2.-""); return x; } } public interface I3 : I2 {} public interface I4 : I2, I1 {} public interface I5 : I1, I2 {} "; var source2 = @" class Test2 : I3, I4, I5 { static void Main() { I3 x3 = new Test2(); var y = -x3; I4 x4 = new Test2(); y = -x4; I5 x5 = new Test2(); y = -x5; } } "; var expectedOutput = @" I2.- I2.- I2.- "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput); } [Fact] [WorkItem(52202, "https://github.com/dotnet/roslyn/issues/52202")] public void Operators_32() { var source1 = @" public interface I1 { static I1 operator +(I1 x) { System.Console.WriteLine(""+""); return x; } static I1 operator -(I1 x) { System.Console.WriteLine(""-""); return x; } static I1 operator !(I1 x) { System.Console.WriteLine(""!""); return x; } static I1 operator ~(I1 x) { System.Console.WriteLine(""~""); return x; } static I1 operator ++(I1 x) { System.Console.WriteLine(""++""); return x; } static I1 operator --(I1 x) { System.Console.WriteLine(""--""); return x; } static bool operator true(I1 x) { System.Console.WriteLine(""true""); return true; } static bool operator false(I1 x) { System.Console.WriteLine(""false""); return false; } static I1 operator +(I1 x, I1 y) { System.Console.WriteLine(""+2""); return x; } static I1 operator -(I1 x, I1 y) { System.Console.WriteLine(""-2""); return x; } static I1 operator *(I1 x, I1 y) { System.Console.WriteLine(""*""); return x; } static I1 operator /(I1 x, I1 y) { System.Console.WriteLine(""/""); return x; } static I1 operator %(I1 x, I1 y) { System.Console.WriteLine(""%""); return x; } static I1 operator &(I1 x, I1 y) { System.Console.WriteLine(""&""); return x; } static I1 operator |(I1 x, I1 y) { System.Console.WriteLine(""|""); return x; } static I1 operator ^(I1 x, I1 y) { System.Console.WriteLine(""^""); return x; } static I1 operator <<(I1 x, int y) { System.Console.WriteLine(""<<""); return x; } static I1 operator >>(I1 x, int y) { System.Console.WriteLine("">>""); return x; } static I1 operator >(I1 x, I1 y) { System.Console.WriteLine("">""); return x; } static I1 operator <(I1 x, I1 y) { System.Console.WriteLine(""<""); return x; } static I1 operator >=(I1 x, I1 y) { System.Console.WriteLine("">=""); return x; } static I1 operator <=(I1 x, I1 y) { System.Console.WriteLine(""<=""); return x; } } "; var source2 = @" class Test2 : I1 { static void Main() { I1 x = new Test2(); I1 y = new Test2(); x = +x; x = -x; x = !x; x = ~x; x = ++x; x = x--; x = x + y; x = x - y; x = x * y; x = x / y; x = x % y; if (x && y) { } x = x | y; x = x ^ y; x = x << 1; x = x >> 2; x = x > y; x = x < y; x = x >= y; x = x <= y; } } "; var expectedOutput = @" + - ! ~ ++ -- +2 -2 * / % false & true | ^ << >> > < >= <= "; var compilation1 = CreateCompilation(source1 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); var i1 = compilation1.GlobalNamespace.GetTypeMember("I1"); foreach (var member in i1.GetMembers()) { Assert.Equal(Accessibility.Public, member.DeclaredAccessibility); } CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); CompilationReference compilationReference = compilation1.ToMetadataReference(); MetadataReference metadataReference = compilation1.EmitToImageReference(); var compilation2 = CreateCompilation(source2, new[] { compilationReference }, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); CompileAndVerify(compilation2, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); var compilation3 = CreateCompilation(source2, new[] { metadataReference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation3, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : expectedOutput, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(52202, "https://github.com/dotnet/roslyn/issues/52202")] public void Operators_33() { var source1 = @" public interface I1 { static implicit operator int(I1 x) { return 0; } static explicit operator byte(I1 x) { return 0; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular); var i1 = compilation1.GlobalNamespace.GetTypeMember("I1"); foreach (var member in i1.GetMembers()) { Assert.Equal(Accessibility.Public, member.DeclaredAccessibility); } compilation1.VerifyDiagnostics( // (4,30): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // static implicit operator int(I1 x) Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 30), // (4,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static implicit operator int(I1 x) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(4, 30), // (9,30): error CS0552: 'I1.explicit operator byte(I1)': user-defined conversions to or from an interface are not allowed // static explicit operator byte(I1 x) Diagnostic(ErrorCode.ERR_ConversionWithInterface, "byte").WithArguments("I1.explicit operator byte(I1)").WithLocation(9, 30), // (9,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static explicit operator byte(I1 x) Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "byte").WithLocation(9, 30) ); } [Fact] public void RuntimeFeature_01() { var compilation1 = CreateCompilation("", options: TestOptions.DebugDll, references: new[] { TestMetadata.Net461.mscorlib }, targetFramework: TargetFramework.Empty); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.False(compilation1.Assembly.CorLibrary.RuntimeSupportsDefaultInterfaceImplementation); } [Fact] public void RuntimeFeature_02() { var compilation1 = CreateCompilation("", options: TestOptions.DebugDll, references: new[] { NetCoreApp.SystemRuntime }, targetFramework: TargetFramework.Empty); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.True(compilation1.Assembly.CorLibrary.RuntimeSupportsDefaultInterfaceImplementation); } [Fact] public void RuntimeFeature_03() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { public static class RuntimeFeature { public const string DefaultImplementationsOfInterfaces = ""DefaultImplementationsOfInterfaces""; } } } "; AssertRuntimeFeatureTrue(source); } private static void AssertRuntimeFeatureTrue(string source) { var compilation1 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.Empty); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.Same(compilation1.Assembly, compilation1.Assembly.CorLibrary); foreach (var reference in new[] { compilation1.EmitToImageReference(), compilation1.ToMetadataReference() }) { var compilation2 = CreateCompilation("", options: TestOptions.DebugDll, references: new[] { reference }, targetFramework: TargetFramework.Empty); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.True(compilation2.Assembly.CorLibrary.RuntimeSupportsDefaultInterfaceImplementation); } } [Fact] public void RuntimeFeature_04() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { public static class RuntimeFeature { public const string DefaultImplementationsOfInterfaces = """"; } } } "; AssertRuntimeFeatureTrue(source); } [Fact] public void RuntimeFeature_05() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { public static class RuntimeFeature { public static string DefaultImplementationsOfInterfaces; } } } "; AssertRuntimeFeatureTrue(source); } [Fact] public void RuntimeFeature_06() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { public class RuntimeFeature { public const string DefaultImplementationsOfInterfaces = ""DefaultImplementationsOfInterfaces""; } } } "; AssertRuntimeFeatureFalse(source); } [Fact] public void RuntimeFeature_07() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { public static class RuntimeFeature { static string DefaultImplementationsOfInterfaces; } } } "; AssertRuntimeFeatureFalse(source); } private static void AssertRuntimeFeatureFalse(string source) { var compilation1 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.Empty); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.Same(compilation1.Assembly, compilation1.Assembly.CorLibrary); foreach (var reference in new[] { compilation1.EmitToImageReference(), compilation1.ToMetadataReference() }) { var compilation2 = CreateCompilation("", options: TestOptions.DebugDll, references: new[] { reference }, targetFramework: TargetFramework.Empty); Assert.False(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.False(compilation2.Assembly.CorLibrary.RuntimeSupportsDefaultInterfaceImplementation); } } [Fact] public void RuntimeFeature_08() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { public class RuntimeFeature { public string DefaultImplementationsOfInterfaces; } } } "; AssertRuntimeFeatureFalse(source); } [Fact] public void RuntimeFeature_09() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} public struct Int32 {} namespace Runtime.CompilerServices { public static class RuntimeFeature { public const int DefaultImplementationsOfInterfaces = 0; } } } "; AssertRuntimeFeatureFalse(source); } [Fact] public void RuntimeFeature_10() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { public static class RuntimeFeature { } } } "; AssertRuntimeFeatureFalse(source); } [Fact] public void RuntimeFeature_11() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { } } "; AssertRuntimeFeatureFalse(source); } [Fact] public void RuntimeFeature_12() { var source = @" namespace System { public class Object {} public class String {} public struct Void {} public class ValueType {} namespace Runtime.CompilerServices { static class RuntimeFeature { public const string DefaultImplementationsOfInterfaces = ""DefaultImplementationsOfInterfaces""; } } } "; AssertRuntimeFeatureFalse(source); } [Fact] public void RuntimeFeature_13() { var source = @" namespace System { namespace Runtime.CompilerServices { public static class RuntimeFeature { public const string DefaultImplementationsOfInterfaces = ""DefaultImplementationsOfInterfaces""; } } } "; var compilation1 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { TestMetadata.Net461.mscorlib }, targetFramework: TargetFramework.Empty); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.False(compilation1.Assembly.CorLibrary.RuntimeSupportsDefaultInterfaceImplementation); } [Fact] public void ProtectedAccessibility_01() { var source0 = @" interface I1 { sealed protected void M1() { System.Console.WriteLine(""M1""); } } "; var source1 = @" interface I2 : I1 { static void Test<T>(T x) where T : I2 { x.M1(); } } class A : I2 { static void Main() { I2.Test(new A()); } } "; var compilation0 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); var source2 = @" interface I2 : I1 { static void Test<T>(T x) where T : I1, I3 { x.M1(); } } interface I3 : I2 {} class A : I3 { static void Main() { I2.Test(new A()); } } "; var compilation1 = CreateCompilation(source0 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var verifier = CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); verifier.VerifyIL("I2.Test<T>", @" { // Code size 16 (0x10) .maxstack 1 IL_0000: nop IL_0001: ldarga.s V_0 IL_0003: constrained. ""T"" IL_0009: callvirt ""void I1.M1()"" IL_000e: nop IL_000f: ret } "); var source3 = @" interface I2 : I1 { static void Test<T>(T x) where T : I1 { x.M1(); } } "; var compilation2 = CreateCompilation(source0 + source3, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (14,11): error CS1540: Cannot access protected member 'I1.M1()' via a qualifier of type 'T'; the qualifier must be of type 'I2' (or derived from it) // x.M1(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M1").WithArguments("I1.M1()", "T", "I2").WithLocation(14, 11) ); } [Fact] public void ProtectedAccessibility_02() { var source0 = @" interface I1<T> { sealed protected void M1() { System.Console.WriteLine(""M1""); } static void Test(I1<int> x) { x.M1(); } } class A : I1<int> { static void Main() { I1<byte>.Test(new A()); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); } [Fact] public void ProtectedAccessibility_03() { var source0 = @" interface I1<T> { sealed protected void M1() { System.Console.WriteLine(""M1""); } } interface I3<T> : I1<T> {} "; var source1 = @" interface I2<T> : I3<T> { static void Test(I2<int> x) { x.M1(); } } class A : I2<int> { static void Main() { I2<byte>.Test(new A()); } } "; var compilation0 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); var source2 = @" interface I2<T> : I3<T> { static void Test(I4 x) { x.M1(); } } interface I4 : I2<int> {} class A : I4 { static void Main() { I2<byte>.Test(new A()); } } "; var compilation1 = CreateCompilation(source0 + source2, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); var source3 = @" interface I2<T> : I3<T> { static void Test(I3<int> x) { x.M1(); } static void Test(I1<int> y) { y.M1(); } } "; var compilation2 = CreateCompilation(source0 + source3, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (17,11): error CS1540: Cannot access protected member 'I1<int>.M1()' via a qualifier of type 'I3<int>'; the qualifier must be of type 'I2<T>' (or derived from it) // x.M1(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M1").WithArguments("I1<int>.M1()", "I3<int>", "I2<T>").WithLocation(17, 11), // (22,11): error CS1540: Cannot access protected member 'I1<int>.M1()' via a qualifier of type 'I1<int>'; the qualifier must be of type 'I2<T>' (or derived from it) // y.M1(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M1").WithArguments("I1<int>.M1()", "I1<int>", "I2<T>").WithLocation(22, 11) ); } [Fact] public void ProtectedAccessibility_04() { var source0 = @" interface I1 : I2 { sealed protected void M1() { } static void Test(I1 x) { x.M1(); } } interface I2 : I1 { static void Test(I2 y) { y.M1(); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(2, 11), // (13,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(13, 11), // (17,11): error CS1061: 'I2' does not contain a definition for 'M1' and no accessible extension method 'M1' accepting a first argument of type 'I2' could be found (are you missing a using directive or an assembly reference?) // y.M1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("I2", "M1").WithLocation(17, 11) ); } [Fact] public void ProtectedAccessibility_05() { var source0 = @" interface I1 : I2 { static protected void M2() { } static void Test() { I1.M2(); } } interface I2 : I1 { static void Test() { I1.M2(); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(2, 11), // (13,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(13, 11) ); } [Fact] public void ProtectedAccessibility_06() { var source0 = @" interface I1<T> { static protected void M1() { System.Console.WriteLine(""M1""); } } interface I3<T> : I1<T> {} "; var source1 = @" class I2<T> : I3<T> { public static void Test() { I1<int>.M1(); } } class A { static void Main() { I2<byte>.Test(); } } "; var compilation0 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); var source3 = @" class I2<T> { static void Test() { I3<T>.M1(); I1<T>.M1(); } } "; var compilation2 = CreateCompilation(source0 + source3, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (17,15): error CS0122: 'I1<T>.M1()' is inaccessible due to its protection level // I3<T>.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1<T>.M1()").WithLocation(17, 15), // (18,15): error CS0122: 'I1<T>.M1()' is inaccessible due to its protection level // I1<T>.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("I1<T>.M1()").WithLocation(18, 15) ); } [Fact] public void ProtectedAccessibility_07() { var source0 = @" interface I1<T> { static protected void M1() { System.Console.WriteLine(""M1""); } } class I3<T> : I1<T> {} "; var source1 = @" class I2<T> : I3<T> { public static void Test() { I1<int>.M1(); } } class A { static void Main() { I2<byte>.Test(); } } "; var compilation0 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); } private const string NoPiaAttributes = @" namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] public sealed class GuidAttribute : Attribute { public GuidAttribute(string guid){} } [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)] public sealed class PrimaryInteropAssemblyAttribute : Attribute { public PrimaryInteropAssemblyAttribute(int major, int minor){} } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false)] public sealed class ComImportAttribute : Attribute { public ComImportAttribute(){} } [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class TypeIdentifierAttribute : Attribute { public TypeIdentifierAttribute(){} public TypeIdentifierAttribute(string scope, string identifier){} } } "; [Fact] public void NoPia_01() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia7 : ITest33 { } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,17): error CS8711: Type 'ITest33' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. // class UsePia7 : ITest33 Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType, "ITest33").WithArguments("ITest33").WithLocation(2, 17) ); } } [Fact] public void NoPia_02() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main(ITest33 x) { x.M1(); } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (4,29): error CS8711: Type 'ITest33' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. // public static void Main(ITest33 x) Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType, "ITest33").WithArguments("ITest33").WithLocation(4, 29) ); } } [Fact] public void NoPia_03() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(){} void M2(); } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main(ITest33 x) { x.M2(); } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (4,29): error CS8711: Type 'ITest33' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. // public static void Main(ITest33 x) Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType, "ITest33").WithArguments("ITest33").WithLocation(4, 29) ); } } [Fact] public void NoPia_04() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { sealed void M1(){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main(ITest33 x) { x.M1(); } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (4,29): error CS8711: Type 'ITest33' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. // public static void Main(ITest33 x) Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType, "ITest33").WithArguments("ITest33").WithLocation(4, 29) ); } } [Fact] public void NoPia_05() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { static void M1(){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main() { ITest33.M1(); } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (6,9): error CS8711: Type 'ITest33' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. // ITest33.M1(); Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType, "ITest33").WithArguments("ITest33").WithLocation(6, 9) ); } } [Fact] public void NoPia_06() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface I1 { } } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main(ITest33.I1 x) { } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (4,37): error CS1754: Type 'ITest33.I1' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // public static void Main(ITest33.I1 x) Diagnostic(ErrorCode.ERR_NoPIANestedType, "I1").WithArguments("ITest33.I1").WithLocation(4, 37) ); } } [Fact] public void NoPia_07() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { public static int F1; } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main() { _ = ITest33.F1; } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (6,13): error CS8711: Type 'ITest33' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. // _ = ITest33.F1; Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType, "ITest33").WithArguments("ITest33").WithLocation(6, 13) ); } } [Fact] public void NoPia_08() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest44 : ITest33 { void ITest33.M1(){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main(ITest44 x) { x.M1(); } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (4,29): error CS8711: Type 'ITest44' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. // public static void Main(ITest44 x) Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType, "ITest44").WithArguments("ITest44").WithLocation(4, 29) ); } } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPia_09() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(); public interface ITest55 { void M2(); } } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest44 : ITest33 { void ITest33.M1(){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer1 = @" public class UsePia { public static void Test(ITest33 x) { x.M1(); } } "; string consumer2 = @" class Test : ITest33 { public static void Main() { UsePia.Test(new Test()); } void ITest33.M1() { System.Console.WriteLine(""Test.M1""); } } "; string pia2 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(); } " + NoPiaAttributes; var pia2Compilation = CreateCompilation(pia2, options: TestOptions.ReleaseDll); var pia2Reference = pia2Compilation.EmitToImageReference(); foreach (var reference1 in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer1, options: TestOptions.ReleaseDll, references: new[] { reference1, attributesRef }, targetFramework: TargetFramework.StandardLatest); foreach (var reference2 in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(consumer2, options: TestOptions.ReleaseExe, references: new[] { reference2, pia2Reference }, targetFramework: TargetFramework.StandardLatest); CompileAndVerify(compilation2, expectedOutput: "Test.M1"); } } } [Fact] [WorkItem(35911, "https://github.com/dotnet/roslyn/issues/35911")] public void NoPia_10() { var attributes = CreateCompilation(NoPiaAttributes, options: TestOptions.ReleaseDll, targetFramework: TargetFramework.NetCoreApp); var attributesRef = attributes.EmitToImageReference(); string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest44 : ITest33 { abstract void ITest33.M1(); } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll, references: new[] { attributesRef }, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(piaCompilation, verify: VerifyOnMonoOrCoreClr); string consumer = @" class UsePia { public static void Main(ITest44 x) { x.M1(); } } "; foreach (var reference in new[] { piaCompilation.ToMetadataReference(embedInteropTypes: true), piaCompilation.EmitToImageReference(embedInteropTypes: true) }) { var compilation1 = CreateCompilation(consumer, options: TestOptions.ReleaseDll, references: new[] { reference, attributesRef }, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (4,29): error CS8750: Type 'ITest44' cannot be embedded because it has a re-abstraction of a member from base interface. Consider setting the 'Embed Interop Types' property to false. // public static void Main(ITest44 x) Diagnostic(ErrorCode.ERR_ReAbstractionInNoPIAType, "ITest44").WithArguments("ITest44").WithLocation(4, 29) ); } } [Fact] public void LambdaCaching_01() { var source0 = @" interface I1 { static void M1() { M2(() => System.Console.WriteLine(""M1"")); } static void M2(System.Action d) { d(); } } class A { static void Main() { I1.M1(); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var verifier = CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); verifier.VerifyIL("I1.M1", @" { // Code size 39 (0x27) .maxstack 2 IL_0000: nop IL_0001: ldsfld ""System.Action I1.<>c.<>9__0_0"" IL_0006: dup IL_0007: brtrue.s IL_0020 IL_0009: pop IL_000a: ldsfld ""I1.<>c I1.<>c.<>9"" IL_000f: ldftn ""void I1.<>c.<M1>b__0_0()"" IL_0015: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_001a: dup IL_001b: stsfld ""System.Action I1.<>c.<>9__0_0"" IL_0020: call ""void I1.M2(System.Action)"" IL_0025: nop IL_0026: ret } "); } [Fact] public void LambdaCaching_02() { var source0 = @" interface I1 { void M1() { M2(() => System.Console.WriteLine(""M1"")); } static void M2(System.Action d) { d(); } } class A : I1 { static void Main() { ((I1)new A()).M1(); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var verifier = CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1", verify: VerifyOnMonoOrCoreClr); verifier.VerifyIL("I1.M1", @" { // Code size 39 (0x27) .maxstack 2 IL_0000: nop IL_0001: ldsfld ""System.Action I1.<>c.<>9__0_0"" IL_0006: dup IL_0007: brtrue.s IL_0020 IL_0009: pop IL_000a: ldsfld ""I1.<>c I1.<>c.<>9"" IL_000f: ldftn ""void I1.<>c.<M1>b__0_0()"" IL_0015: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_001a: dup IL_001b: stsfld ""System.Action I1.<>c.<>9__0_0"" IL_0020: call ""void I1.M2(System.Action)"" IL_0025: nop IL_0026: ret } "); } [Fact] public void LambdaCaching_03() { var source0 = @" interface I1 { void M1() { M2(() => System.Console.WriteLine(this.ToString())); } static void M2(System.Action d) { d(); } } class A : I1 { static void Main() { ((I1)new A()).M1(); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var verifier = CompileAndVerify(compilation0, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"A", verify: VerifyOnMonoOrCoreClr); verifier.VerifyIL("I1.M1", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldftn ""void I1.<M1>b__0_0()"" IL_0008: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_000d: call ""void I1.M2(System.Action)"" IL_0012: nop IL_0013: ret } "); } [Fact] public void MemberwiseClone_01() { var source0 = @" interface I1 { object M1(I2 x, I3 y) { x.MemberwiseClone(); y.MemberwiseClone(); this.MemberwiseClone(); return ((I1)this).MemberwiseClone(); } } interface I2 { } interface I3 : I1 { } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics( // (6,11): error CS0122: 'object.MemberwiseClone()' is inaccessible due to its protection level // x.MemberwiseClone(); Diagnostic(ErrorCode.ERR_BadAccess, "MemberwiseClone").WithArguments("object.MemberwiseClone()").WithLocation(6, 11), // (7,11): error CS0122: 'object.MemberwiseClone()' is inaccessible due to its protection level // y.MemberwiseClone(); Diagnostic(ErrorCode.ERR_BadAccess, "MemberwiseClone").WithArguments("object.MemberwiseClone()").WithLocation(7, 11), // (8,14): error CS0122: 'object.MemberwiseClone()' is inaccessible due to its protection level // this.MemberwiseClone(); Diagnostic(ErrorCode.ERR_BadAccess, "MemberwiseClone").WithArguments("object.MemberwiseClone()").WithLocation(8, 14), // (9,27): error CS0122: 'object.MemberwiseClone()' is inaccessible due to its protection level // return ((I1)this).MemberwiseClone(); Diagnostic(ErrorCode.ERR_BadAccess, "MemberwiseClone").WithArguments("object.MemberwiseClone()").WithLocation(9, 27) ); } [Fact] public void MethodReAbstraction_01() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { abstract void I1.M1(); } "; var source2 = @" class Test1 : I2 { } "; ValidateMethodReAbstraction_01(source1, source2); } private static void ValidateMethodReAbstraction_01(string source1, string source2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); var expected = new DiagnosticDescription[] { // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1()").WithLocation(2, 15) }; compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); ValidateReabstraction(i2m1); var i1m1 = i2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } private static void ValidateReabstraction(MethodSymbol m) { Assert.True(m.IsMetadataVirtual()); Assert.True(m.IsMetadataFinal); Assert.False(m.IsMetadataNewSlot()); Assert.True(m.IsAbstract); Assert.False(m.IsVirtual); Assert.True(m.IsSealed); Assert.False(m.IsStatic); Assert.False(m.IsExtern); Assert.False(m.IsAsync); Assert.False(m.IsOverride); Assert.Equal(Accessibility.Private, m.DeclaredAccessibility); } [Fact] public void MethodReAbstraction_02() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } "; var source2 = @" class Test1 : I2 { } "; ValidateMethodReAbstraction_01(source1, source2); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void MethodReAbstraction_03() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { abstract void I1.M1(); } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1.M1(); } void I1.M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodReAbstraction_03(source1, source2); } private void ValidateMethodReAbstraction_03(string source1, string source2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test1.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "Test1.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); var i1m1 = i2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Equal("void Test1.I1.M1()", test1.FindImplementationForInterfaceMember(i1m1).ToTestDisplayString()); } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void MethodReAbstraction_04() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1.M1(); } void I1.M1() { System.Console.WriteLine(""Test1.M1""); } } "; ValidateMethodReAbstraction_03(source1, source2); } [Fact] public void MethodReAbstraction_05() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidateMethodReAbstraction_05(source1, source2); } private static void ValidateMethodReAbstraction_05(string source1, string source2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); var expected = new DiagnosticDescription[] { // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.M1()").WithLocation(2, 15) }; compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i3 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I3", i3.Name); var i1m1 = i3.ContainingNamespace.GetTypeMember("I1").GetMember<MethodSymbol>("M1"); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i3.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_06() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidateMethodReAbstraction_05(source1, source2); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void MethodReAbstraction_07() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I2 { void I1.M1() { System.Console.WriteLine(""I3.M1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1.M1(); } } "; ValidateMethodReAbstraction_07(source1, source2); } private void ValidateMethodReAbstraction_07(string source1, string source2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "I3.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "I3.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i3 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I3", i3.Name); var i1m1 = i3.ContainingNamespace.GetTypeMember("I1").GetMember<MethodSymbol>("M1"); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Equal("void I3.I1.M1()", i3.FindImplementationForInterfaceMember(i1m1).ToTestDisplayString()); Assert.Equal("void I3.I1.M1()", test1.FindImplementationForInterfaceMember(i1m1).ToTestDisplayString()); } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void MethodReAbstraction_08() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I2 { void I1.M1() { System.Console.WriteLine(""I3.M1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1.M1(); } } "; ValidateMethodReAbstraction_07(source1, source2); } [Fact] public void MethodReAbstraction_09() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I1 { abstract void I1.M1(); } "; var source2 = @" class Test1 : I2, I3 { } "; ValidateMethodReAbstraction_09(source1, source2); } private void ValidateMethodReAbstraction_09(string source1, string source2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); var expected = new DiagnosticDescription[] { // (2,15): error CS8705: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I2.I1.M1()', nor 'I3.I1.M1()' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.M1()", "I2.I1.M1()", "I3.I1.M1()").WithLocation(2, 15) }; compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1m1 = test1.InterfacesNoUseSiteDiagnostics().First().ContainingNamespace.GetTypeMember("I1").GetMember<MethodSymbol>("M1"); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_10() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { void I1.M1() {} } public interface I3 : I1 { abstract void I1.M1(); } "; var source2 = @" class Test1 : I2, I3 { } "; ValidateMethodReAbstraction_09(source1, source2); } [Fact] public void MethodReAbstraction_11() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I1 { void I1.M1() {} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidateMethodReAbstraction_09(source1, source2); } [Fact] public void MethodReAbstraction_12() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I1 { abstract void I1.M1(); } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); var expected = new DiagnosticDescription[] { // (2,15): error CS8705: Interface member 'I1.M1()' does not have a most specific implementation. Neither 'I2.I1.M1()', nor 'I3.I1.M1()' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.M1()", "I2.I1.M1()", "I3.I1.M1()").WithLocation(2, 15) }; compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i4 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I4", i4.Name); var i1m1 = i4.ContainingNamespace.GetTypeMember("I1").GetMember<MethodSymbol>("M1"); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i4.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void MethodReAbstraction_13() { var source1 = @" public interface I1 { void M1() {} } public interface I2 : I1 { abstract void I1.M1(); } public interface I3 : I1 { abstract void I1.M1(); } public interface I4 : I2, I3 { void I1.M1() { System.Console.WriteLine(""I4.M1""); } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); i1.M1(); } } "; var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "I4.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "I4.M1" : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i4 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I4", i4.Name); var i1m1 = i4.ContainingNamespace.GetTypeMember("I1").GetMember<MethodSymbol>("M1"); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Equal("void I4.I1.M1()", i4.FindImplementationForInterfaceMember(i1m1).ToTestDisplayString()); Assert.Equal("void I4.I1.M1()", test1.FindImplementationForInterfaceMember(i1m1).ToTestDisplayString()); } } [Fact] public void MethodReAbstraction_14() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { abstract void I1.M1() {} } class Test1 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics( // (9,22): error CS0500: 'I2.I1.M1()' cannot declare a body because it is marked abstract // abstract void I1.M1() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M1").WithArguments("I2.I1.M1()").WithLocation(9, 22), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1()").WithLocation(12, 15) ); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); ValidateReabstraction(i2m1); var i1m1 = i2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_15() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { abstract extern void I1.M1(); } class Test1 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics( // (9,29): error CS0180: 'I2.I1.M1()' cannot be both extern and abstract // abstract extern void I1.M1(); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M1").WithArguments("I2.I1.M1()").WithLocation(9, 29), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1()").WithLocation(12, 15) ); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); Assert.True(i2m1.IsMetadataVirtual()); Assert.True(i2m1.IsMetadataFinal); Assert.False(i2m1.IsMetadataNewSlot()); Assert.True(i2m1.IsAbstract); Assert.False(i2m1.IsVirtual); Assert.True(i2m1.IsSealed); Assert.False(i2m1.IsStatic); Assert.True(i2m1.IsExtern); Assert.False(i2m1.IsAsync); Assert.False(i2m1.IsOverride); Assert.Equal(Accessibility.Private, i2m1.DeclaredAccessibility); var i1m1 = i2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_16() { var source1 = @" public interface I1 { void M1(); } public partial interface I2 : I1 { abstract partial void I1.M1(); } class Test1 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularWithExtendedPartialMethods, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics( // (9,30): error CS0754: A partial method may not explicitly implement an interface method // abstract partial void I1.M1(); Diagnostic(ErrorCode.ERR_PartialMethodNotExplicit, "M1").WithLocation(9, 30), // (9,30): error CS0750: A partial method cannot have the 'abstract' modifier // abstract partial void I1.M1(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M1").WithLocation(9, 30), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1()").WithLocation(12, 15) ); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); ValidateReabstraction(i2m1); var i1m1 = i2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_17() { var source1 = @" public interface I1 { void M1(); } public partial interface I2 : I1 { abstract async void I1.M1(); } class Test1 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics( // (9,28): error CS1994: The 'async' modifier can only be used in methods that have a body. // abstract async void I1.M1(); Diagnostic(ErrorCode.ERR_BadAsyncLacksBody, "M1").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1()").WithLocation(12, 15) ); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); Assert.True(i2m1.IsMetadataVirtual()); Assert.True(i2m1.IsMetadataFinal); Assert.False(i2m1.IsMetadataNewSlot()); Assert.True(i2m1.IsAbstract); Assert.False(i2m1.IsVirtual); Assert.True(i2m1.IsSealed); Assert.False(i2m1.IsStatic); Assert.False(i2m1.IsExtern); Assert.True(i2m1.IsAsync); Assert.False(i2m1.IsOverride); Assert.Equal(Accessibility.Private, i2m1.DeclaredAccessibility); var i1m1 = i2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_18() { var source1 = @" public interface I1 { void M1(); } public partial interface I2 : I1 { abstract public void I1.M1(); } class Test1 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics( // (9,29): error CS0106: The modifier 'public' is not valid for this item // abstract public void I1.M1(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("public").WithLocation(9, 29), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.M1()' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.M1()").WithLocation(12, 15) ); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); ValidateReabstraction(i2m1); var i1m1 = i2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Null(i2.FindImplementationForInterfaceMember(i1m1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_19() { var source1 = @" public interface I1 { void M1(); } public class C2 : I1 { abstract void I1.M1(); } "; ValidateMethodReAbstraction_19(source1); } private static void ValidateMethodReAbstraction_19(string source1) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics( // (9,22): error CS0106: The modifier 'abstract' is not valid for this item // abstract void I1.M1(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M1").WithArguments("abstract").WithLocation(9, 22), // (9,22): error CS0501: 'C2.I1.M1()' must declare a body because it is not marked abstract, extern, or partial // abstract void I1.M1(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M1").WithArguments("C2.I1.M1()").WithLocation(9, 22) ); static void validate(ModuleSymbol m) { var c2 = m.GlobalNamespace.GetTypeMember("C2"); var c2m1 = c2.GetMember<MethodSymbol>("I1.M1"); Assert.False(c2m1.IsAbstract); Assert.False(c2m1.IsSealed); var i1m1 = c2m1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I1.M1()", i1m1.ToTestDisplayString()); Assert.Same(c2m1, c2.FindImplementationForInterfaceMember(i1m1)); } } [Fact] public void MethodReAbstraction_20() { var source1 = @" public interface I1 { void M1(); } public struct C2 : I1 { abstract void I1.M1(); } "; ValidateMethodReAbstraction_19(source1); } [Fact] public void MethodReAbstraction_21() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract void I1.M1(); } class Test1 : I2 { } "; ValidateMethodReAbstraction_21(source1, // (8,22): error CS0539: 'I2.M1()' in explicit interface declaration is not found among members of the interface that can be implemented // abstract void I1.M1(); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M1").WithArguments("I2.M1()").WithLocation(8, 22) ); } private static void ValidateMethodReAbstraction_21(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2m1 = i2.GetMember<MethodSymbol>("I1.M1"); ValidateReabstraction(i2m1); Assert.Empty(i2m1.ExplicitInterfaceImplementations); } } [Fact] public void MethodReAbstraction_22() { var source1 = @" public interface I2 : I1 { abstract void I1.M1(); } class Test1 : I2 { } "; ValidateMethodReAbstraction_21(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,19): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract void I1.M1(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 19), // (4,19): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract void I1.M1(); Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 19) ); } [Fact] public void MethodReAbstraction_23() { var source1 = @" public interface I1 { void M1(); } public interface I2 : I1 { abstract void I1.M1(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,22): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract void I1.M1(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M1").WithArguments("default interface implementation", "8.0").WithLocation(9, 22) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,22): error CS8701: Target runtime doesn't support default interface implementation. // abstract void I1.M1(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "M1").WithLocation(9, 22) ); } [Fact] public void PropertyReAbstraction_001() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 {get; set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } private static void ValidatePropertyReAbstraction_001(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<PropertySymbol>().Single(); ValidateReabstraction(i2p1); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Same(i1p1.GetMethod, i2p1.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } else if (i2p1.GetMethod is object) { Assert.Empty(i2p1.GetMethod.ExplicitInterfaceImplementations); } if (i1p1.SetMethod is object) { Assert.Same(i1p1.SetMethod, i2p1.SetMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } else if (i2p1.SetMethod is object) { Assert.Empty(i2p1.SetMethod.ExplicitInterfaceImplementations); } } } private static void ValidateReabstraction(PropertySymbol reabstracting) { Assert.True(reabstracting.IsAbstract); Assert.False(reabstracting.IsVirtual); Assert.True(reabstracting.IsSealed); Assert.False(reabstracting.IsStatic); Assert.False(reabstracting.IsExtern); Assert.False(reabstracting.IsOverride); Assert.Equal(Accessibility.Private, reabstracting.DeclaredAccessibility); if (reabstracting.GetMethod is object) { ValidateReabstraction(reabstracting.GetMethod); } if (reabstracting.SetMethod is object) { ValidateReabstraction(reabstracting.SetMethod); } } [Fact] public void PropertyReAbstraction_002() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_003() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 {get; set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; i1.P1 = 1; } int I1.P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set => System.Console.WriteLine(""Test1.set_P1""); } } "; ValidatePropertyReAbstraction_003(source1, source2, @" Test1.get_P1 Test1.set_P1 "); } private void ValidatePropertyReAbstraction_003(string source1, string source2, string expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test12p1 = test1.GetMembers().OfType<PropertySymbol>().Single(); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<PropertySymbol>().Single(); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Same(test12p1, test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Same(test12p1.GetMethod, test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } if (i1p1.SetMethod is object) { Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Same(test12p1.SetMethod, test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_004() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; i1.P1 = 1; } int I1.P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set => System.Console.WriteLine(""Test1.set_P1""); } } "; ValidatePropertyReAbstraction_003(source1, source2, @" Test1.get_P1 Test1.set_P1 "); } [Fact] public void PropertyReAbstraction_005() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } private static void ValidatePropertyReAbstraction_005(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i3 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I3", i3.Name); var i1p1 = i3.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(i3.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Null(i3.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } if (i1p1.SetMethod is object) { Assert.Null(i3.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } } } [Fact] public void PropertyReAbstraction_006() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_007() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I2 { int I1.P1 { get { System.Console.WriteLine(""I3.get_P1""); return 0; } set => System.Console.WriteLine(""I3.set_P1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; i1.P1 = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, @" I3.get_P1 I3.set_P1 "); } private void ValidatePropertyReAbstraction_007(string source1, string source2, string expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i3 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I3", i3.Name); var i3p1 = i3.GetMembers().OfType<PropertySymbol>().Single(); var i1p1 = i3.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(i3p1, i3.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i3p1, test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Same(i3p1.GetMethod, i3.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Same(i3p1.GetMethod, test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } if (i1p1.SetMethod is object) { Assert.Same(i3p1.SetMethod, i3.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Same(i3p1.SetMethod, test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_008() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I2 { int I1.P1 { get { System.Console.WriteLine(""I3.get_P1""); return 0; } set => System.Console.WriteLine(""I3.set_P1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; i1.P1 = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, @" I3.get_P1 I3.set_P1 "); } [Fact] public void PropertyReAbstraction_009() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I1 { abstract int I1.P1 {get; set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } private static void ValidatePropertyReAbstraction_009(string source1, string source2, params DiagnosticDescription[] expected) { ValidatePropertyReAbstraction_009(source1, source2, expected, expected); } private static void ValidatePropertyReAbstraction_009(string source1, string source2, DiagnosticDescription[] expected1, params DiagnosticDescription[] expected2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); var expected = expected1; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); expected = expected2; } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1p1 = test1.InterfacesNoUseSiteDiagnostics().First().ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } if (i1p1.SetMethod is object) { Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } } } [Fact] public void PropertyReAbstraction_010() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { int I1.P1 { get => throw null; set => throw null; } } public interface I3 : I1 { abstract int I1.P1 {get; set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_011() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I1 { int I1.P1 { get => throw null; set => throw null; } } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_012() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I1 { abstract int I1.P1 {get; set;} } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; ValidatePropertyReAbstraction_012(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } private static void ValidatePropertyReAbstraction_012(string source1, string source2, params DiagnosticDescription[] expected) { ValidatePropertyReAbstraction_012(source1, source2, expected, expected); } private static void ValidatePropertyReAbstraction_012(string source1, string source2, DiagnosticDescription[] expected1, params DiagnosticDescription[] expected2) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected1); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); var expected = expected1; foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); expected = expected2; } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i4 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I4", i4.Name); var i1p1 = i4.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(i4.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Null(i4.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } if (i1p1.SetMethod is object) { Assert.Null(i4.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_013() { var source1 = @" public interface I1 { int P1 { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get; set;} } public interface I3 : I1 { abstract int I1.P1 {get; set;} } public interface I4 : I2, I3 { int I1.P1 { get { System.Console.WriteLine(""I4.get_P1""); return 0; } set => System.Console.WriteLine(""I4.set_P1""); } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; i1.P1 = 1; } } "; ValidatePropertyReAbstraction_013(source1, source2, @" I4.get_P1 I4.set_P1 "); } private void ValidatePropertyReAbstraction_013(string source1, string source2, string expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i4 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I4", i4.Name); var i4p1 = i4.GetMembers().OfType<PropertySymbol>().Single(); var i1p1 = i4.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(i4p1, i4.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i4p1, test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Same(i4p1.GetMethod, i4.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Same(i4p1.GetMethod, test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } if (i1p1.SetMethod is object) { Assert.Same(i4p1.SetMethod, i4.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Same(i4p1.SetMethod, test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } } } [Fact] public void PropertyReAbstraction_014() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 { get { throw null; } set { throw null; } } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.P1.get' cannot declare a body because it is marked abstract // get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.P1.get").WithLocation(11, 9), // (15,9): error CS0500: 'I2.I1.P1.set' cannot declare a body because it is marked abstract // set Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.P1.set").WithLocation(15, 9), // (22,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(22, 15) ); } private static void ValidatePropertyReAbstraction_014(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<PropertySymbol>().Single(); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); ValidateReabstraction(i2p1); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { if (i2p1.GetMethod is object) { Assert.Same(i1p1.GetMethod, i2p1.GetMethod.ExplicitInterfaceImplementations.Single()); } Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } else if (i2p1.GetMethod is object) { Assert.Empty(i2p1.GetMethod.ExplicitInterfaceImplementations); } if (i1p1.SetMethod is object) { if (i2p1.SetMethod is object) { Assert.Same(i1p1.SetMethod, i2p1.SetMethod.ExplicitInterfaceImplementations.Single()); } Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } else if (i2p1.SetMethod is object) { Assert.Empty(i2p1.SetMethod.ExplicitInterfaceImplementations); } } } [Fact] public void PropertyReAbstraction_015() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 { get => throw null; set => throw null; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.P1.get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.P1.get").WithLocation(11, 9), // (12,9): error CS0500: 'I2.I1.P1.set' cannot declare a body because it is marked abstract // set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.P1.set").WithLocation(12, 9), // (16,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(16, 15) ); } [Fact] public void PropertyReAbstraction_016() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { extern abstract int I1.P1 {get; set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_016(source1, // (9,28): error CS0180: 'I2.I1.P1' cannot be both extern and abstract // extern abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P1").WithArguments("I2.I1.P1").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } private static void ValidatePropertyReAbstraction_016(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<PropertySymbol>().Single(); Assert.True(i2p1.IsAbstract); Assert.False(i2p1.IsVirtual); Assert.True(i2p1.IsSealed); Assert.False(i2p1.IsStatic); Assert.True(i2p1.IsExtern); Assert.False(i2p1.IsOverride); Assert.Equal(Accessibility.Private, i2p1.DeclaredAccessibility); var i2p1Get = i2p1.GetMethod; if (i2p1Get is object) { Assert.True(i2p1Get.IsMetadataVirtual()); Assert.True(i2p1Get.IsMetadataFinal); Assert.False(i2p1Get.IsMetadataNewSlot()); Assert.True(i2p1Get.IsAbstract); Assert.False(i2p1Get.IsVirtual); Assert.True(i2p1Get.IsSealed); Assert.False(i2p1Get.IsStatic); Assert.True(i2p1Get.IsExtern); Assert.False(i2p1Get.IsAsync); Assert.False(i2p1Get.IsOverride); Assert.Equal(Accessibility.Private, i2p1Get.DeclaredAccessibility); } var i2p1Set = i2p1.SetMethod; if (i2p1Set is object) { Assert.True(i2p1Set.IsMetadataVirtual()); Assert.True(i2p1Set.IsMetadataFinal); Assert.False(i2p1Set.IsMetadataNewSlot()); Assert.True(i2p1Set.IsAbstract); Assert.False(i2p1Set.IsVirtual); Assert.True(i2p1Set.IsSealed); Assert.False(i2p1Set.IsStatic); Assert.True(i2p1Set.IsExtern); Assert.False(i2p1Set.IsAsync); Assert.False(i2p1Set.IsOverride); Assert.Equal(Accessibility.Private, i2p1Set.DeclaredAccessibility); } var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Same(i1p1.GetMethod, i2p1.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } else if (i2p1.GetMethod is object) { Assert.Empty(i2p1.GetMethod.ExplicitInterfaceImplementations); } if (i1p1.SetMethod is object) { Assert.Same(i1p1.SetMethod, i2p1.SetMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } else if (i2p1.SetMethod is object) { Assert.Empty(i2p1.SetMethod.ExplicitInterfaceImplementations); } } } [Fact] public void PropertyReAbstraction_017() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract public int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,28): error CS0106: The modifier 'public' is not valid for this item // abstract public int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("public").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_018() { var source1 = @" public interface I1 { int P1 {get; set;} } public class C2 : I1 { abstract int I1.P1 { get; set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 21) ); } private static void ValidatePropertyReAbstraction_018(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var c2 = m.GlobalNamespace.GetTypeMember("C2"); var c2p1 = c2.GetMembers().OfType<PropertySymbol>().Single(); Assert.False(c2p1.IsAbstract); Assert.False(c2p1.IsSealed); var c2p1Get = c2p1.GetMethod; if (c2p1Get is object) { Assert.False(c2p1Get.IsAbstract); Assert.False(c2p1Get.IsSealed); } var c2p1Set = c2p1.SetMethod; if (c2p1Set is object) { Assert.False(c2p1Set.IsAbstract); Assert.False(c2p1Set.IsSealed); } var i1p1 = c2p1.ExplicitInterfaceImplementations.Single(); Assert.Same(c2p1, c2.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Same(i1p1.GetMethod, c2p1.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(c2p1Get, c2.FindImplementationForInterfaceMember(i1p1.GetMethod)); } else if (c2p1.GetMethod is object) { Assert.Empty(c2p1.GetMethod.ExplicitInterfaceImplementations); } if (i1p1.SetMethod is object) { Assert.Same(i1p1.SetMethod, c2p1.SetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(c2p1Set, c2.FindImplementationForInterfaceMember(i1p1.SetMethod)); } else if (c2p1.SetMethod is object) { Assert.Empty(c2p1.SetMethod.ExplicitInterfaceImplementations); } } } [Fact] public void PropertyReAbstraction_019() { var source1 = @" public interface I1 { int P1 {get; set;} } public struct C2 : I1 { abstract int I1.P1 { get; set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 21) ); } [Fact] public void PropertyReAbstraction_020() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 { get; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.P1' is missing accessor 'I1.P1.set' // abstract int I1.P1 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P1").WithArguments("I2.I1.P1", "I1.P1.set").WithLocation(9, 21), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_021() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 { set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.P1' is missing accessor 'I1.P1.get' // abstract int I1.P1 { set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P1").WithArguments("I2.I1.P1", "I1.P1.get").WithLocation(9, 21), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_022() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,31): error CS0550: 'I2.I1.P1.set' adds an accessor not found in interface member 'I1.P1' // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.I1.P1.set", "I1.P1").WithLocation(9, 31), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_023() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,26): error CS0550: 'I2.I1.P1.get' adds an accessor not found in interface member 'I1.P1' // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.I1.P1.get", "I1.P1").WithLocation(9, 26), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_024() { var source1 = @" public interface I1 { int P1 {get => throw null; private set => throw null;} } public interface I2 : I1 { abstract int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,31): error CS0550: 'I2.I1.P1.set' adds an accessor not found in interface member 'I1.P1' // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.I1.P1.set", "I1.P1").WithLocation(9, 31), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_025() { var source1 = @" public interface I1 { int P1 {private get => throw null; set => throw null;} } public interface I2 : I1 { abstract int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,26): error CS0550: 'I2.I1.P1.get' adds an accessor not found in interface member 'I1.P1' // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.I1.P1.get", "I1.P1").WithLocation(9, 26), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_026() { var source1 = @" public interface I1 { internal int P1 {get => throw null; set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.P1' is inaccessible due to its protection level // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); } private static void ValidatePropertyReAbstraction_026(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, references: new[] { reference }, targetFramework: TargetFramework.NetCoreApp); validate(compilation2.SourceModule); compilation2.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<PropertySymbol>().Single(); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); ValidateReabstraction(i2p1); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.GetMethod is object) { Assert.Same(i1p1.GetMethod, i2p1.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.GetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.GetMethod)); } else if (i2p1.GetMethod is object) { Assert.Empty(i2p1.GetMethod.ExplicitInterfaceImplementations); } if (i1p1.SetMethod is object) { Assert.Same(i1p1.SetMethod, i2p1.SetMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.SetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.SetMethod)); } else if (i2p1.SetMethod is object) { Assert.Empty(i2p1.SetMethod.ExplicitInterfaceImplementations); } } } [Fact] public void PropertyReAbstraction_027() { var source1 = @" public interface I1 { int P1 {internal get => throw null; set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.P1.get' is inaccessible due to its protection level // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1.get").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); } [Fact] public void PropertyReAbstraction_028() { var source1 = @" public interface I1 { int P1 {get => throw null; internal set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.P1 { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.P1.set' is inaccessible due to its protection level // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1.set").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_029() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 // Code size 3 (0x3) .maxstack 8 IL_0000: ldc.i4.s 65 IL_0002: ret } // end of method I2::I1.get_F1 .method private hidebysig specialname abstract virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 } // end of method I2::I1.set_F1 .property instance char I1.F1() { .get instance char I2::I1.get_F1() .set instance void I2::I1.set_F1(char) } // end of property I2::I1.F1 } // end of class I2 "; var source1 = @" class Test2 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.F1' // class Test2 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.SetMethod)); Assert.Equal("System.Char I2.I1.get_F1()", test2.FindImplementationForInterfaceMember(i1F1.GetMethod).ToTestDisplayString()); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_030() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname abstract virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 } // end of method I2::I1.get_F1 .method private hidebysig specialname virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 IL_0002: ret } // end of method I2::I1.set_F1 .property instance char I1.F1() { .get instance char I2::I1.get_F1() .set instance void I2::I1.set_F1(char) } // end of property I2::I1.F1 } // end of class I2 "; var source1 = @" class Test2 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.F1' // class Test2 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Equal("void I2.I1.set_F1(System.Char value)", test2.FindImplementationForInterfaceMember(i1F1.SetMethod).ToTestDisplayString()); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.GetMethod)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_031() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 // Code size 3 (0x3) .maxstack 8 IL_0000: ldc.i4.s 65 IL_0002: ret } // end of method I2::I1.get_F1 .method private hidebysig specialname abstract virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 } // end of method I2::I1.set_F1 .property instance char I1.F1() { .get instance char I2::I1.get_F1() .set instance void I2::I1.set_F1(char) } // end of property I2::I1.F1 } // end of class I2 .class interface public abstract auto ansi I3 implements I1 { .method private hidebysig specialname abstract virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 } // end of method I3::I1.get_F1 .method private hidebysig specialname virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 IL_0002: ret } // end of method I3::I1.set_F1 .property instance char I1.F1() { .get instance char I3::I1.get_F1() .set instance void I3::I1.set_F1(char) } // end of property I3::I1.F1 } // end of class I3 "; var source1 = @" class Test2 : I2, I3 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS8705: Interface member 'I1.F1' does not have a most specific implementation. Neither 'I2.I1.F1', nor 'I3.I1.F1' are most specific. // class Test2 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.F1", "I2.I1.F1", "I3.I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.GetMethod)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_032() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 // Code size 3 (0x3) .maxstack 8 IL_0000: ldc.i4.s 65 IL_0002: ret } // end of method I2::I1.get_F1 .method private hidebysig specialname abstract virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 } // end of method I2::I1.set_F1 } // end of class I2 "; var source1 = @" class Test2 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.F1' // class Test2 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.SetMethod)); Assert.Equal("System.Char I2.I1.get_F1()", test2.FindImplementationForInterfaceMember(i1F1.GetMethod).ToTestDisplayString()); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_033() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname abstract virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 } // end of method I2::I1.get_F1 .method private hidebysig specialname virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 IL_0002: ret } // end of method I2::I1.set_F1 } // end of class I2 "; var source1 = @" class Test2 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.F1' // class Test2 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Equal("void I2.I1.set_F1(System.Char value)", test2.FindImplementationForInterfaceMember(i1F1.SetMethod).ToTestDisplayString()); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.GetMethod)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_034() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 // Code size 3 (0x3) .maxstack 8 IL_0000: ldc.i4.s 65 IL_0002: ret } // end of method I2::I1.get_F1 .method private hidebysig specialname abstract virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 } // end of method I2::I1.set_F1 } // end of class I2 .class interface public abstract auto ansi I3 implements I1 { .method private hidebysig specialname abstract virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 } // end of method I3::I1.get_F1 .method private hidebysig specialname virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 IL_0002: ret } // end of method I3::I1.set_F1 .property instance char I1.F1() { .get instance char I3::I1.get_F1() .set instance void I3::I1.set_F1(char) } // end of property I3::I1.F1 } // end of class I3 "; var source1 = @" class Test2 : I2, I3 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.F1' // class Test2 : I2, I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.GetMethod)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_035() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 // Code size 3 (0x3) .maxstack 8 IL_0000: ldc.i4.s 65 IL_0002: ret } // end of method I2::I1.get_F1 .method private hidebysig specialname abstract virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 } // end of method I2::I1.set_F1 .property instance char I1.F1() { .get instance char I2::I1.get_F1() .set instance void I2::I1.set_F1(char) } // end of property I2::I1.F1 } // end of class I2 .class interface public abstract auto ansi I3 implements I1 { .method private hidebysig specialname abstract virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 } // end of method I3::I1.get_F1 .method private hidebysig specialname virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 IL_0002: ret } // end of method I3::I1.set_F1 } // end of class I3 "; var source1 = @" class Test2 : I2, I3 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.F1' // class Test2 : I2, I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.GetMethod)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void PropertyReAbstraction_036() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance char get_F1() cil managed { } // end of method I1::get_F1 .method public hidebysig newslot specialname abstract virtual instance void set_F1(char 'value') cil managed { } // end of method I1::set_F1 .property instance char F1() { .get instance char I1::get_F1() .set instance void I1::set_F1(char) } // end of property I1::F1 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 // Code size 3 (0x3) .maxstack 8 IL_0000: ldc.i4.s 65 IL_0002: ret } // end of method I2::I1.get_F1 .method private hidebysig specialname abstract virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 } // end of method I2::I1.set_F1 } // end of class I2 .class interface public abstract auto ansi I3 implements I1 { .method private hidebysig specialname abstract virtual final instance char I1.get_F1() cil managed { .override I1::get_F1 } // end of method I3::I1.get_F1 .method private hidebysig specialname virtual final instance void I1.set_F1(char 'value') cil managed { .override I1::set_F1 IL_0002: ret } // end of method I3::I1.set_F1 } // end of class I3 "; var source1 = @" class Test2 : I2, I3 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,15): error CS0535: 'Test2' does not implement interface member 'I1.F1' // class Test2 : I2, I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test2", "I1.F1").WithLocation(2, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i1F1 = i1.GetMember<PropertySymbol>("F1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1F1.GetMethod)); } [Fact] public void PropertyReAbstraction_037() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 {get;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_038() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_039() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 {get;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; } int I1.P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.get_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_040() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; } int I1.P1 { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.get_P1"); } [Fact] public void PropertyReAbstraction_041() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_042() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_043() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I2 { int I1.P1 { get { System.Console.WriteLine(""I3.get_P1""); return 0; } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.get_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_044() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I2 { int I1.P1 { get { System.Console.WriteLine(""I3.get_P1""); return 0; } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.get_P1"); } [Fact] public void PropertyReAbstraction_045() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I1 { abstract int I1.P1 {get;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_046() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { int I1.P1 { get => throw null; } } public interface I3 : I1 { abstract int I1.P1 {get;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_047() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I1 { int I1.P1 { get => throw null; } } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_048() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I1 { abstract int I1.P1 {get;} } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; ValidatePropertyReAbstraction_012(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_049() { var source1 = @" public interface I1 { int P1 { get => throw null; } } public interface I2 : I1 { abstract int I1.P1 {get;} } public interface I3 : I1 { abstract int I1.P1 {get;} } public interface I4 : I2, I3 { int I1.P1 { get { System.Console.WriteLine(""I4.get_P1""); return 0; } } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); _ = i1.P1; } } "; ValidatePropertyReAbstraction_013(source1, source2, "I4.get_P1"); } [Fact] public void PropertyReAbstraction_050() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 { get { throw null; } } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.P1.get' cannot declare a body because it is marked abstract // get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.P1.get").WithLocation(11, 9), // (18,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(18, 15) ); } [Fact] public void PropertyReAbstraction_051() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 { get => throw null; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.P1.get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.P1.get").WithLocation(11, 9), // (15,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(15, 15) ); } [Fact] public void PropertyReAbstraction_052() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 => throw null; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,27): error CS0500: 'I2.I1.P1.get' cannot declare a body because it is marked abstract // abstract int I1.P1 => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "throw null").WithArguments("I2.I1.P1.get").WithLocation(9, 27), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_053() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { extern abstract int I1.P1 {get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_016(source1, // (9,28): error CS0180: 'I2.I1.P1' cannot be both extern and abstract // extern abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P1").WithArguments("I2.I1.P1").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_054() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract public int I1.P1 { get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,28): error CS0106: The modifier 'public' is not valid for this item // abstract public int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("public").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_055() { var source1 = @" public interface I1 { int P1 {get;} } public class C2 : I1 { abstract int I1.P1 { get; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 21) ); } [Fact] public void PropertyReAbstraction_056() { var source1 = @" public interface I1 { int P1 {get;} } public struct C2 : I1 { abstract int I1.P1 { get; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 21) ); } [Fact] public void PropertyReAbstraction_057() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 { get; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.P1' is missing accessor 'I1.P1.set' // abstract int I1.P1 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P1").WithArguments("I2.I1.P1", "I1.P1.set").WithLocation(9, 21), // (9,26): error CS0550: 'I2.I1.P1.get' adds an accessor not found in interface member 'I1.P1' // abstract int I1.P1 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.I1.P1.get", "I1.P1").WithLocation(9, 26), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_058() { var source1 = @" public interface I1 { internal int P1 {get => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.P1 { get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.P1' is inaccessible due to its protection level // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); } [Fact] public void PropertyReAbstraction_059() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 {set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_060() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_061() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 {set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } int I1.P1 { set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.set_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_062() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } int I1.P1 { set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.set_P1"); } [Fact] public void PropertyReAbstraction_063() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_064() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_065() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I2 { int I1.P1 { set { System.Console.WriteLine(""I3.set_P1""); } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.set_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_066() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I2 { int I1.P1 { set { System.Console.WriteLine(""I3.set_P1""); } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.set_P1"); } [Fact] public void PropertyReAbstraction_067() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I1 { abstract int I1.P1 {set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_068() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { int I1.P1 { set => throw null; } } public interface I3 : I1 { abstract int I1.P1 {set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_069() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I1 { int I1.P1 { set => throw null; } } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void PropertyReAbstraction_070() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I1 { abstract int I1.P1 {set;} } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; ValidatePropertyReAbstraction_012(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void PropertyReAbstraction_071() { var source1 = @" public interface I1 { int P1 { set => throw null; } } public interface I2 : I1 { abstract int I1.P1 {set;} } public interface I3 : I1 { abstract int I1.P1 {set;} } public interface I4 : I2, I3 { int I1.P1 { set { System.Console.WriteLine(""I4.set_P1""); } } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); i1.P1 = 1; } } "; ValidatePropertyReAbstraction_013(source1, source2, "I4.set_P1"); } [Fact] public void PropertyReAbstraction_072() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 { set { throw null; } } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.P1.set' cannot declare a body because it is marked abstract // set Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.P1.set").WithLocation(11, 9), // (18,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(18, 15) ); } [Fact] public void PropertyReAbstraction_073() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 { set => throw null; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.P1.set' cannot declare a body because it is marked abstract // set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.P1.set").WithLocation(11, 9), // (15,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(15, 15) ); } [Fact] public void PropertyReAbstraction_074() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { extern abstract int I1.P1 {set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_016(source1, // (9,28): error CS0180: 'I2.I1.P1' cannot be both extern and abstract // extern abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P1").WithArguments("I2.I1.P1").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_075() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract public int I1.P1 { set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,28): error CS0106: The modifier 'public' is not valid for this item // abstract public int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("public").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_076() { var source1 = @" public interface I1 { int P1 {set;} } public class C2 : I1 { abstract int I1.P1 { set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.P1 { set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 21), // (9,26): error CS8051: Auto-implemented properties must have get accessors. // abstract int I1.P1 { set; } Diagnostic(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, "set").WithArguments("C2.I1.P1.set").WithLocation(9, 26) ); } [Fact] public void PropertyReAbstraction_077() { var source1 = @" public interface I1 { int P1 {set;} } public struct C2 : I1 { abstract int I1.P1 { set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.P1 { set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 21), // (9,26): error CS8051: Auto-implemented properties must have get accessors. // abstract int I1.P1 { set; } Diagnostic(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, "set").WithArguments("C2.I1.P1.set").WithLocation(9, 26) ); } [Fact] public void PropertyReAbstraction_078() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 { set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.P1' is missing accessor 'I1.P1.get' // abstract int I1.P1 { set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P1").WithArguments("I2.I1.P1", "I1.P1.get").WithLocation(9, 21), // (9,26): error CS0550: 'I2.I1.P1.set' adds an accessor not found in interface member 'I1.P1' // abstract int I1.P1 { set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.I1.P1.set", "I1.P1").WithLocation(9, 26), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_079() { var source1 = @" public interface I1 { internal int P1 {set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.P1 { set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.P1' is inaccessible due to its protection level // abstract int I1.P1 { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); } [Fact] public void PropertyReAbstraction_080() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 { get; set; } = 0; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS8053: Instance properties in interfaces cannot have initializers. // abstract int I1.P1 { get; set; } = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P1").WithArguments("I2.I1.P1").WithLocation(9, 21), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_081() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 { get; } = 0; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS8053: Instance properties in interfaces cannot have initializers. // abstract int I1.P1 { get; } = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P1").WithArguments("I2.I1.P1").WithLocation(9, 21), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_082() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 { set; } = 0; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS8053: Instance properties in interfaces cannot have initializers. // abstract int I1.P1 { set; } = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P1").WithArguments("I2.I1.P1").WithLocation(9, 21), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void PropertyReAbstraction_083() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract int I1.P1 {get; set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (8,21): error CS0539: 'I2.P1' in explicit interface declaration is not found among members of the interface that can be implemented // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("I2.P1").WithLocation(8, 21) ); } private static void ValidatePropertyReAbstraction_083(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<PropertySymbol>().Single(); ValidateReabstraction(i2p1); Assert.Empty(i2p1.ExplicitInterfaceImplementations); if (i2p1.GetMethod is object) { Assert.Empty(i2p1.GetMethod.ExplicitInterfaceImplementations); } if (i2p1.SetMethod is object) { Assert.Empty(i2p1.SetMethod.ExplicitInterfaceImplementations); } } } [Fact] public void PropertyReAbstraction_084() { var source1 = @" public interface I2 : I1 { abstract int I1.P1 {get; set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,18): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 18), // (4,18): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 18) ); } [Fact] public void PropertyReAbstraction_085() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract int I1.P1 {get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (8,21): error CS0539: 'I2.P1' in explicit interface declaration is not found among members of the interface that can be implemented // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("I2.P1").WithLocation(8, 21) ); } [Fact] public void PropertyReAbstraction_086() { var source1 = @" public interface I2 : I1 { abstract int I1.P1 {get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,18): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract int I1.P1 {get;} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 18), // (4,18): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract int I1.P1 {get;} Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 18) ); } [Fact] public void PropertyReAbstraction_087() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract int I1.P1 {set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (8,21): error CS0539: 'I2.P1' in explicit interface declaration is not found among members of the interface that can be implemented // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("I2.P1").WithLocation(8, 21) ); } [Fact] public void PropertyReAbstraction_088() { var source1 = @" public interface I2 : I1 { abstract int I1.P1 {set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,18): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract int I1.P1 {set;} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 18), // (4,18): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract int I1.P1 {set;} Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 18) ); } [Fact] public void PropertyReAbstraction_089() { var source1 = @" public interface I1 { int P1 {get; set;} } public interface I2 : I1 { abstract int I1.P1 {get; set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,25): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(9, 25), // (9,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(9, 30) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,25): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(9, 25), // (9,30): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.P1 {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(9, 30) ); } [Fact] public void PropertyReAbstraction_090() { var source1 = @" public interface I1 { int P1 {get;} } public interface I2 : I1 { abstract int I1.P1 {get;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,25): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.P1 {get;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(9, 25) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,25): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.P1 {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(9, 25) ); } [Fact] public void PropertyReAbstraction_091() { var source1 = @" public interface I1 { int P1 {set;} } public interface I2 : I1 { abstract int I1.P1 {set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,25): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.P1 {set;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(9, 25) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,25): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.P1 {set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(9, 25) ); } [Fact] public void EventReAbstraction_001() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1; } "; var source2 = @" class Test1 : I2 { } "; ValidateEventReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } private static void ValidateEventReAbstraction_001(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<EventSymbol>().Single(); ValidateReabstraction(i2p1); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i1p1.AddMethod, i2p1.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Same(i1p1.RemoveMethod, i2p1.RemoveMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } private static void ValidateReabstraction(EventSymbol reabstracting) { Assert.True(reabstracting.IsAbstract); Assert.False(reabstracting.IsVirtual); Assert.True(reabstracting.IsSealed); Assert.False(reabstracting.IsStatic); Assert.False(reabstracting.IsExtern); Assert.False(reabstracting.IsOverride); Assert.Equal(Accessibility.Private, reabstracting.DeclaredAccessibility); if (reabstracting.AddMethod is object) { ValidateReabstraction(reabstracting.AddMethod); } if (reabstracting.RemoveMethod is object) { ValidateReabstraction(reabstracting.RemoveMethod); } } [Fact] public void EventReAbstraction_002() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } "; var source2 = @" class Test1 : I2 { } "; ValidateEventReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void EventReAbstraction_003() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1; } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1.P1 += null; i1.P1 -= null; } event System.Action I1.P1 { add { System.Console.WriteLine(""Test1.add_P1""); } remove => System.Console.WriteLine(""Test1.remove_P1""); } } "; ValidateEventReAbstraction_003(source1, source2, @" Test1.add_P1 Test1.remove_P1 "); } private void ValidateEventReAbstraction_003(string source1, string source2, string expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var test12p1 = test1.GetMembers().OfType<EventSymbol>().Single(); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<EventSymbol>().Single(); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Same(test12p1, test1.FindImplementationForInterfaceMember(i1p1)); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Same(test12p1.AddMethod, test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Same(test12p1.RemoveMethod, test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void EventReAbstraction_004() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1.P1 += null; i1.P1 -= null; } event System.Action I1.P1 { add { System.Console.WriteLine(""Test1.add_P1""); } remove => System.Console.WriteLine(""Test1.remove_P1""); } } "; ValidateEventReAbstraction_003(source1, source2, @" Test1.add_P1 Test1.remove_P1 "); } [Fact] public void EventReAbstraction_005() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidateEventReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } private static void ValidateEventReAbstraction_005(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i3 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I3", i3.Name); var i1p1 = i3.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.Null(i3.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); Assert.Null(i3.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(i3.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } [Fact] public void EventReAbstraction_006() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidateEventReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.P1").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void EventReAbstraction_007() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I2 { event System.Action I1.P1 { add { System.Console.WriteLine(""I3.add_P1""); } remove => System.Console.WriteLine(""I3.remove_P1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1.P1 += null; i1.P1 -= null; } } "; ValidateEventReAbstraction_007(source1, source2, @" I3.add_P1 I3.remove_P1 "); } private void ValidateEventReAbstraction_007(string source1, string source2, string expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i3 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I3", i3.Name); var i3p1 = i3.GetMembers().OfType<EventSymbol>().Single(); var i1p1 = i3.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.Same(i3p1, i3.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i3p1, test1.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i3p1.AddMethod, i3.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Same(i3p1.AddMethod, test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Same(i3p1.RemoveMethod, i3.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Same(i3p1.RemoveMethod, test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void EventReAbstraction_008() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I2 { event System.Action I1.P1 { add { System.Console.WriteLine(""I3.add_P1""); } remove => System.Console.WriteLine(""I3.remove_P1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1.P1 += null; i1.P1 -= null; } } "; ValidateEventReAbstraction_007(source1, source2, @" I3.add_P1 I3.remove_P1 "); } [Fact] public void EventReAbstraction_009() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I1 { abstract event System.Action I1.P1; } "; var source2 = @" class Test1 : I2, I3 { } "; ValidateEventReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } private static void ValidateEventReAbstraction_009(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i1p1 = test1.InterfacesNoUseSiteDiagnostics().First().ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } [Fact] public void EventReAbstraction_010() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { event System.Action I1.P1 { add => throw null; remove => throw null; } } public interface I3 : I1 { abstract event System.Action I1.P1; } "; var source2 = @" class Test1 : I2, I3 { } "; ValidateEventReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void EventReAbstraction_011() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I1 { event System.Action I1.P1 { add => throw null; remove => throw null; } } "; var source2 = @" class Test1 : I2, I3 { } "; ValidateEventReAbstraction_009(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } [Fact] public void EventReAbstraction_012() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I1 { abstract event System.Action I1.P1; } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; ValidateEventReAbstraction_012(source1, source2, // (2,15): error CS8705: Interface member 'I1.P1' does not have a most specific implementation. Neither 'I2.I1.P1', nor 'I3.I1.P1' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.P1", "I2.I1.P1", "I3.I1.P1").WithLocation(2, 15) ); } private static void ValidateEventReAbstraction_012(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i4 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I4", i4.Name); var i1p1 = i4.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.Null(i4.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); Assert.Null(i4.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(i4.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void EventReAbstraction_013() { var source1 = @" public interface I1 { event System.Action P1 { add => throw null; remove => throw null; } } public interface I2 : I1 { abstract event System.Action I1.P1; } public interface I3 : I1 { abstract event System.Action I1.P1; } public interface I4 : I2, I3 { event System.Action I1.P1 { add { System.Console.WriteLine(""I4.add_P1""); } remove => System.Console.WriteLine(""I4.remove_P1""); } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); i1.P1 += null; i1.P1 -= null; } } "; ValidateEventReAbstraction_013(source1, source2, @" I4.add_P1 I4.remove_P1 "); } private void ValidateEventReAbstraction_013(string source1, string source2, string expected) { var compilation1 = CreateCompilation(source2 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics(); foreach (var reference in new[] { compilation2.ToMetadataReference(), compilation2.EmitToImageReference() }) { var compilation3 = CreateCompilation(source2, options: TestOptions.DebugExe, references: new[] { reference }, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation3.SourceModule); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation1, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expected : null, verify: VerifyOnMonoOrCoreClr, symbolValidator: validate); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i4 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I4", i4.Name); var i4p1 = i4.GetMembers().OfType<EventSymbol>().Single(); var i1p1 = i4.ContainingNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.Same(i4p1, i4.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i4p1, test1.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i4p1.AddMethod, i4.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Same(i4p1.AddMethod, test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Same(i4p1.RemoveMethod, i4.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Same(i4p1.RemoveMethod, test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } [Fact] public void EventReAbstraction_014() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { add { throw null; } remove { throw null; } } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (10,5): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // { Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(10, 5), // (22,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(22, 15) ); } private static void ValidateEventReAbstraction_014(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<EventSymbol>().Single(); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); ValidateReabstraction(i2p1); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); if (i1p1.AddMethod is object) { if (i2p1.AddMethod is object) { Assert.Same(i1p1.AddMethod, i2p1.AddMethod.ExplicitInterfaceImplementations.Single()); } Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); } else if (i2p1.AddMethod is object) { Assert.Empty(i2p1.AddMethod.ExplicitInterfaceImplementations); } if (i1p1.RemoveMethod is object) { if (i2p1.RemoveMethod is object) { Assert.Same(i1p1.RemoveMethod, i2p1.RemoveMethod.ExplicitInterfaceImplementations.Single()); } Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } else if (i2p1.RemoveMethod is object) { Assert.Empty(i2p1.RemoveMethod.ExplicitInterfaceImplementations); } } } [Fact] public void EventReAbstraction_015() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { add => throw null; remove => throw null; } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (10,5): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // { Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(10, 5), // (16,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(16, 15) ); } [Fact] public void EventReAbstraction_016() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { extern abstract event System.Action I1.P1; } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,44): error CS0106: The modifier 'extern' is not valid for this item // extern abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("extern").WithLocation(9, 44), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_017() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract public event System.Action I1.P1; } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,44): error CS0106: The modifier 'public' is not valid for this item // abstract public event System.Action I1.P1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("public").WithLocation(9, 44), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_018() { var source1 = @" public interface I1 { event System.Action P1; } public class C2 : I1 { abstract event System.Action I1.P1; } "; ValidateEventReAbstraction_018(source1, // (7,19): error CS0535: 'C2' does not implement interface member 'I1.P1.remove' // public class C2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1.remove").WithLocation(7, 19), // (7,19): error CS0535: 'C2' does not implement interface member 'I1.P1.add' // public class C2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1.add").WithLocation(7, 19), // (9,37): error CS0071: An explicit interface implementation of an event must use event accessor syntax // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "P1").WithLocation(9, 37), // (9,37): error CS0106: The modifier 'abstract' is not valid for this item // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 37) ); } private static void ValidateEventReAbstraction_018(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var c2 = m.GlobalNamespace.GetTypeMember("C2"); var c2p1 = c2.GetMembers().OfType<EventSymbol>().Single(); Assert.False(c2p1.IsAbstract); Assert.False(c2p1.IsSealed); var i1p1 = c2p1.ExplicitInterfaceImplementations.Single(); Assert.Same(c2p1, c2.FindImplementationForInterfaceMember(i1p1)); var c2p1Add = c2p1.AddMethod; if (c2p1Add is object) { Assert.False(c2p1Add.IsAbstract); Assert.False(c2p1Add.IsSealed); Assert.Same(i1p1.AddMethod, c2p1Add.ExplicitInterfaceImplementations.Single()); Assert.Same(c2p1Add, c2.FindImplementationForInterfaceMember(i1p1.AddMethod)); } else { Assert.Null(c2.FindImplementationForInterfaceMember(i1p1.AddMethod)); } var c2p1Remove = c2p1.RemoveMethod; if (c2p1Remove is object) { Assert.False(c2p1Remove.IsAbstract); Assert.False(c2p1Remove.IsSealed); Assert.Same(i1p1.RemoveMethod, c2p1Remove.ExplicitInterfaceImplementations.Single()); Assert.Same(c2p1Remove, c2.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } else { Assert.Null(c2.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } } [Fact] public void EventReAbstraction_019() { var source1 = @" public interface I1 { event System.Action P1; } public class C2 : I1 { abstract event System.Action I1.P1 { add => throw null; remove => throw null; } } "; ValidateEventReAbstraction_018(source1, // (9,37): error CS0106: The modifier 'abstract' is not valid for this item // abstract event System.Action I1.P1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 37) ); } [Fact] public void EventReAbstraction_020() { var source1 = @" public interface I1 { event System.Action P1; } public struct C2 : I1 { abstract event System.Action I1.P1; } "; ValidateEventReAbstraction_018(source1, // (7,20): error CS0535: 'C2' does not implement interface member 'I1.P1.remove' // public struct C2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1.remove").WithLocation(7, 20), // (7,20): error CS0535: 'C2' does not implement interface member 'I1.P1.add' // public struct C2 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1.add").WithLocation(7, 20), // (9,37): error CS0071: An explicit interface implementation of an event must use event accessor syntax // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "P1").WithLocation(9, 37), // (9,37): error CS0106: The modifier 'abstract' is not valid for this item // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 37) ); } [Fact] public void EventReAbstraction_021() { var source1 = @" public interface I1 { event System.Action P1; } public struct C2 : I1 { abstract event System.Action I1.P1 { add => throw null; remove => throw null; } } "; ValidateEventReAbstraction_018(source1, // (9,37): error CS0106: The modifier 'abstract' is not valid for this item // abstract event System.Action I1.P1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("abstract").WithLocation(9, 37) ); } [Fact] public void EventReAbstraction_022() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { add => throw null; } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,40): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action I1.P1 { add => throw null; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_023() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { add; } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,40): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action I1.P1 { add; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_024() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { remove => throw null; } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,40): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action I1.P1 { remove => throw null; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_025() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { remove; } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,40): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action I1.P1 { remove; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_026() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { add; remove; } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,40): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action I1.P1 { add; remove; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_027() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 {} } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,40): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action I1.P1 {} Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_028() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 { add => throw null; remove => throw null; } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,40): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // abstract event System.Action I1.P1 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_029() { var source1 = @" public interface I1 { event System.Action P1 {add => throw null;} } public interface I2 : I1 { abstract event System.Action I1.P1; } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (4,25): error CS0065: 'I1.P1': event property must have both add and remove accessors // event System.Action P1 {add => throw null;} Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P1").WithArguments("I1.P1").WithLocation(4, 25), // (9,37): error CS0550: 'I2.I1.P1.remove' adds an accessor not found in interface member 'I1.P1' // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "P1").WithArguments("I2.I1.P1.remove", "I1.P1").WithLocation(9, 37), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_030() { var source1 = @" public interface I1 { event System.Action P1 {add => throw null;} } public interface I2 : I1 { abstract event System.Action I1.P1 { add {} remove {} } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (4,25): error CS0065: 'I1.P1': event property must have both add and remove accessors // event System.Action P1 {add => throw null;} Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P1").WithArguments("I1.P1").WithLocation(4, 25), // (10,5): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // { Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(10, 5), // (12,9): error CS0550: 'I2.I1.P1.remove' adds an accessor not found in interface member 'I1.P1' // remove {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "remove").WithArguments("I2.I1.P1.remove", "I1.P1").WithLocation(12, 9), // (16,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(16, 15) ); } [Fact] public void EventReAbstraction_031() { var source1 = @" public interface I1 { event System.Action P1 {remove => throw null;} } public interface I2 : I1 { abstract event System.Action I1.P1; } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (4,25): error CS0065: 'I1.P1': event property must have both add and remove accessors // event System.Action P1 {remove => throw null;} Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P1").WithArguments("I1.P1").WithLocation(4, 25), // (9,37): error CS0550: 'I2.I1.P1.add' adds an accessor not found in interface member 'I1.P1' // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "P1").WithArguments("I2.I1.P1.add", "I1.P1").WithLocation(9, 37), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_032() { var source1 = @" public interface I1 { event System.Action P1 {remove => throw null;} } public interface I2 : I1 { abstract event System.Action I1.P1 { add {} remove {} } } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (4,25): error CS0065: 'I1.P1': event property must have both add and remove accessors // event System.Action P1 {remove => throw null;} Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "P1").WithArguments("I1.P1").WithLocation(4, 25), // (10,5): error CS8712: 'I2.I1.P1': abstract event cannot use event accessor syntax // { Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I2.I1.P1").WithLocation(10, 5), // (11,9): error CS0550: 'I2.I1.P1.add' adds an accessor not found in interface member 'I1.P1' // add {} Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "add").WithArguments("I2.I1.P1.add", "I1.P1").WithLocation(11, 9), // (16,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(16, 15) ); } [Fact] public void EventReAbstraction_033() { var source1 = @" public interface I1 { internal event System.Action P1 {add => throw null; remove => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract event System.Action I1.P1; } class Test1 : I2 { } "; ValidateEventReAbstraction_033(source1, source2, // (4,37): error CS0122: 'I1.P1' is inaccessible due to its protection level // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_BadAccess, "P1").WithArguments("I1.P1").WithLocation(4, 37), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(7, 15) ); } private static void ValidateEventReAbstraction_033(string source1, string source2, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, references: new[] { reference }, targetFramework: TargetFramework.NetCoreApp); validate(compilation2.SourceModule); compilation2.VerifyDiagnostics(expected); } static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<EventSymbol>().Single(); var i1p1 = i2p1.ExplicitInterfaceImplementations.Single(); ValidateReabstraction(i2p1); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1)); Assert.Same(i1p1.AddMethod, i2p1.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.AddMethod)); Assert.Same(i1p1.RemoveMethod, i2p1.RemoveMethod.ExplicitInterfaceImplementations.Single()); Assert.Null(i2.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1p1.RemoveMethod)); } } [Fact] public void EventReAbstraction_034() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract event System.Action I1.P1; } class Test1 : I2 { } "; ValidateEventReAbstraction_034(source1, // (8,37): error CS0539: 'I2.P1' in explicit interface declaration is not found among members of the interface that can be implemented // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("I2.P1").WithLocation(8, 37) ); } private static void ValidateEventReAbstraction_034(string source1, params DiagnosticDescription[] expected) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); validate(compilation1.SourceModule); compilation1.VerifyDiagnostics(expected); static void validate(ModuleSymbol m) { var test1 = m.GlobalNamespace.GetTypeMember("Test1"); var i2 = test1.InterfacesNoUseSiteDiagnostics().First(); Assert.Equal("I2", i2.Name); var i2p1 = i2.GetMembers().OfType<EventSymbol>().Single(); ValidateReabstraction(i2p1); Assert.Empty(i2p1.ExplicitInterfaceImplementations); Assert.Empty(i2p1.AddMethod.ExplicitInterfaceImplementations); Assert.Empty(i2p1.RemoveMethod.ExplicitInterfaceImplementations); } } [Fact] public void EventReAbstraction_035() { var source1 = @" public interface I2 : I1 { abstract event System.Action I1.P1; } class Test1 : I2 { } "; ValidateEventReAbstraction_034(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,34): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 34), // (4,34): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 34) ); } [Fact] public void EventReAbstraction_036() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1 } class Test1 : I2 { } "; ValidateEventReAbstraction_014(source1, // (9,36): error CS0071: An explicit interface implementation of an event must use event accessor syntax // abstract event System.Action I1.P1 Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, ".").WithLocation(9, 36), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.P1' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.P1").WithLocation(12, 15) ); } [Fact] public void EventReAbstraction_037() { var source1 = @" public interface I1 { event System.Action P1; } public interface I2 : I1 { abstract event System.Action I1.P1; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,37): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "P1").WithArguments("default interface implementation", "8.0").WithLocation(9, 37) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,37): error CS8701: Target runtime doesn't support default interface implementation. // abstract event System.Action I1.P1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "P1").WithLocation(9, 37) ); } [Fact] public void IndexerReAbstraction_001() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_002() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_003() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; i1[0] = 1; } int I1.this[int i] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set => System.Console.WriteLine(""Test1.set_P1""); } } "; ValidatePropertyReAbstraction_003(source1, source2, @" Test1.get_P1 Test1.set_P1 "); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_004() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; i1[0] = 1; } int I1.this[int i] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } set => System.Console.WriteLine(""Test1.set_P1""); } } "; ValidatePropertyReAbstraction_003(source1, source2, @" Test1.get_P1 Test1.set_P1 "); } [Fact] public void IndexerReAbstraction_005() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_006() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_007() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I2 { int I1.this[int i] { get { System.Console.WriteLine(""I3.get_P1""); return 0; } set => System.Console.WriteLine(""I3.set_P1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; i1[0] = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, @" I3.get_P1 I3.set_P1 "); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_008() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I2 { int I1.this[int i] { get { System.Console.WriteLine(""I3.get_P1""); return 0; } set => System.Console.WriteLine(""I3.set_P1""); } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; i1[0] = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, @" I3.get_P1 I3.set_P1 "); } [Fact] public void IndexerReAbstraction_009() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I1 { abstract int I1.this[int i] {get; set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_010() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { int I1.this[int i] { get => throw null; set => throw null; } } public interface I3 : I1 { abstract int I1.this[int i] {get; set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_011() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I1 { int I1.this[int i] { get => throw null; set => throw null; } } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_012() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I1 { abstract int I1.this[int i] {get; set;} } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; ValidatePropertyReAbstraction_012(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_013() { var source1 = @" public interface I1 { int this[int i] { get => throw null; set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } public interface I3 : I1 { abstract int I1.this[int i] {get; set;} } public interface I4 : I2, I3 { int I1.this[int i] { get { System.Console.WriteLine(""I4.get_P1""); return 0; } set => System.Console.WriteLine(""I4.set_P1""); } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; i1[0] = 1; } } "; ValidatePropertyReAbstraction_013(source1, source2, @" I4.get_P1 I4.set_P1 "); } [Fact] public void IndexerReAbstraction_014() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] { get { throw null; } set { throw null; } } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.this[int].get' cannot declare a body because it is marked abstract // get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.this[int].get").WithLocation(11, 9), // (15,9): error CS0500: 'I2.I1.this[int].set' cannot declare a body because it is marked abstract // set Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.this[int].set").WithLocation(15, 9), // (22,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(22, 15) ); } [Fact] public void IndexerReAbstraction_015() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] { get => throw null; set => throw null; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.this[int].get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.this[int].get").WithLocation(11, 9), // (12,9): error CS0500: 'I2.I1.this[int].set' cannot declare a body because it is marked abstract // set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.this[int].set").WithLocation(12, 9), // (16,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(16, 15) ); } [Fact] public void IndexerReAbstraction_016() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { extern abstract int I1.this[int i] {get; set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_016(source1, // (9,28): error CS0180: 'I2.I1.this[int]' cannot be both extern and abstract // extern abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "this").WithArguments("I2.I1.this[int]").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_017() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract public int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,28): error CS0106: The modifier 'public' is not valid for this item // abstract public int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("public").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_018() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public class C2 : I1 { abstract int I1.this[int i] { get; set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(9, 21), // (9,35): error CS0501: 'C2.I1.this[int].get' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("C2.I1.this[int].get").WithLocation(9, 35), // (9,40): error CS0501: 'C2.I1.this[int].set' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("C2.I1.this[int].set").WithLocation(9, 40) ); } [Fact] public void IndexerReAbstraction_019() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public struct C2 : I1 { abstract int I1.this[int i] { get; set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(9, 21), // (9,35): error CS0501: 'C2.I1.this[int].get' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("C2.I1.this[int].get").WithLocation(9, 35), // (9,40): error CS0501: 'C2.I1.this[int].set' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("C2.I1.this[int].set").WithLocation(9, 40) ); } [Fact] public void IndexerReAbstraction_020() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] { get; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.this[int]' is missing accessor 'I1.this[int].set' // abstract int I1.this[int i] { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("I2.I1.this[int]", "I1.this[int].set").WithLocation(9, 21), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_021() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] { set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.this[int]' is missing accessor 'I1.this[int].get' // abstract int I1.this[int i] { set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("I2.I1.this[int]", "I1.this[int].get").WithLocation(9, 21), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_022() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,40): error CS0550: 'I2.I1.this[int].set' adds an accessor not found in interface member 'I1.this[int]' // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.I1.this[int].set", "I1.this[int]").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_023() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,35): error CS0550: 'I2.I1.this[int].get' adds an accessor not found in interface member 'I1.this[int]' // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.I1.this[int].get", "I1.this[int]").WithLocation(9, 35), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_024() { var source1 = @" public interface I1 { int this[int i] {get => throw null; private set => throw null;} } public interface I2 : I1 { abstract int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,40): error CS0550: 'I2.I1.this[int].set' adds an accessor not found in interface member 'I1.this[int]' // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.I1.this[int].set", "I1.this[int]").WithLocation(9, 40), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_025() { var source1 = @" public interface I1 { int this[int i] {private get => throw null; set => throw null;} } public interface I2 : I1 { abstract int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,35): error CS0550: 'I2.I1.this[int].get' adds an accessor not found in interface member 'I1.this[int]' // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.I1.this[int].get", "I1.this[int]").WithLocation(9, 35), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_026() { var source1 = @" public interface I1 { internal int this[int i] {get => throw null; set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int]").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(7, 15) ); } [Fact] public void IndexerReAbstraction_027() { var source1 = @" public interface I1 { int this[int i] {internal get => throw null; set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.this[int].get' is inaccessible due to its protection level // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int].get").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(7, 15) ); } [Fact] public void IndexerReAbstraction_028() { var source1 = @" public interface I1 { int this[int i] {get => throw null; internal set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.this[int i] { get; set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.this[int].set' is inaccessible due to its protection level // abstract int I1.this[int i] { get; set; } Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int].set").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(7, 15) ); } [Fact] public void IndexerReAbstraction_037() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] {get;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_038() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_039() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] {get;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; } int I1.this[int i] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.get_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_040() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; } int I1.this[int i] { get { System.Console.WriteLine(""Test1.get_P1""); return 0; } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.get_P1"); } [Fact] public void IndexerReAbstraction_041() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_042() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_043() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I2 { int I1.this[int i] { get { System.Console.WriteLine(""I3.get_P1""); return 0; } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.get_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_044() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I2 { int I1.this[int i] { get { System.Console.WriteLine(""I3.get_P1""); return 0; } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.get_P1"); } [Fact] public void IndexerReAbstraction_045() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I1 { abstract int I1.this[int i] {get;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_046() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { int I1.this[int i] { get => throw null; } } public interface I3 : I1 { abstract int I1.this[int i] {get;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_047() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I1 { int I1.this[int i] { get => throw null; } } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_048() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I1 { abstract int I1.this[int i] {get;} } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; ValidatePropertyReAbstraction_012(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_049() { var source1 = @" public interface I1 { int this[int i] { get => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {get;} } public interface I3 : I1 { abstract int I1.this[int i] {get;} } public interface I4 : I2, I3 { int I1.this[int i] { get { System.Console.WriteLine(""I4.get_P1""); return 0; } } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); _ = i1[0]; } } "; ValidatePropertyReAbstraction_013(source1, source2, "I4.get_P1"); } [Fact] public void IndexerReAbstraction_050() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] { get { throw null; } } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.this[int].get' cannot declare a body because it is marked abstract // get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.this[int].get").WithLocation(11, 9), // (18,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(18, 15) ); } [Fact] public void IndexerReAbstraction_051() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] { get => throw null; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.this[int].get' cannot declare a body because it is marked abstract // get => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I2.I1.this[int].get").WithLocation(11, 9), // (15,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(15, 15) ); } [Fact] public void IndexerReAbstraction_052() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] => throw null; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,36): error CS0500: 'I2.I1.this[int].get' cannot declare a body because it is marked abstract // abstract int I1.this[int i] => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "throw null").WithArguments("I2.I1.this[int].get").WithLocation(9, 36), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_053() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { extern abstract int I1.this[int i] {get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_016(source1, // (9,28): error CS0180: 'I2.I1.this[int]' cannot be both extern and abstract // extern abstract int I1.this[int i] {get;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "this").WithArguments("I2.I1.this[int]").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_054() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract public int I1.this[int i] { get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,28): error CS0106: The modifier 'public' is not valid for this item // abstract public int I1.this[int i] { get;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("public").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_055() { var source1 = @" public interface I1 { int this[int i] {get;} } public class C2 : I1 { abstract int I1.this[int i] { get; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.this[int i] { get; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(9, 21), // (9,35): error CS0501: 'C2.I1.this[int].get' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { get; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("C2.I1.this[int].get").WithLocation(9, 35) ); } [Fact] public void IndexerReAbstraction_056() { var source1 = @" public interface I1 { int this[int i] {get;} } public struct C2 : I1 { abstract int I1.this[int i] { get; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.this[int i] { get; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(9, 21), // (9,35): error CS0501: 'C2.I1.this[int].get' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { get; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("C2.I1.this[int].get").WithLocation(9, 35) ); } [Fact] public void IndexerReAbstraction_057() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] { get; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.this[int]' is missing accessor 'I1.this[int].set' // abstract int I1.this[int i] { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("I2.I1.this[int]", "I1.this[int].set").WithLocation(9, 21), // (9,35): error CS0550: 'I2.I1.this[int].get' adds an accessor not found in interface member 'I1.this[int]' // abstract int I1.this[int i] { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("I2.I1.this[int].get", "I1.this[int]").WithLocation(9, 35), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_058() { var source1 = @" public interface I1 { internal int this[int i] {get => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.this[int i] { get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // abstract int I1.this[int i] { get;} Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int]").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(7, 15) ); } [Fact] public void IndexerReAbstraction_059() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] {set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_060() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } "; var source2 = @" class Test1 : I2 { } "; ValidatePropertyReAbstraction_001(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_061() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] {set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } int I1.this[int i] { set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.set_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_062() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } "; var source2 = @" class Test1 : I2 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } int I1.this[int i] { set { System.Console.WriteLine(""Test1.set_P1""); } } } "; ValidatePropertyReAbstraction_003(source1, source2, "Test1.set_P1"); } [Fact] public void IndexerReAbstraction_063() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_064() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I2 {} "; var source2 = @" class Test1 : I3 { } "; ValidatePropertyReAbstraction_005(source1, source2, // (2,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test1", "I1.this[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_065() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I2 { int I1.this[int i] { set { System.Console.WriteLine(""I3.set_P1""); } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.set_P1"); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_066() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I2 { int I1.this[int i] { set { System.Console.WriteLine(""I3.set_P1""); } } } "; var source2 = @" class Test1 : I3 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } } "; ValidatePropertyReAbstraction_007(source1, source2, "I3.set_P1"); } [Fact] public void IndexerReAbstraction_067() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I1 { abstract int I1.this[int i] {set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_068() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { int I1.this[int i] { set => throw null; } } public interface I3 : I1 { abstract int I1.this[int i] {set;} } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_069() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I1 { int I1.this[int i] { set => throw null; } } "; var source2 = @" class Test1 : I2, I3 { } "; ValidatePropertyReAbstraction_009(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I2, I3 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I2").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] public void IndexerReAbstraction_070() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I1 { abstract int I1.this[int i] {set;} } public interface I4 : I2, I3 {} "; var source2 = @" class Test1 : I4 { } "; ValidatePropertyReAbstraction_012(source1, source2, new[] { // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.this[int]', nor 'I3.I1.this[int]' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.this[int]", "I2.I1.this[int]", "I3.I1.this[int]").WithLocation(2, 15) }, // (2,15): error CS8705: Interface member 'I1.this[int]' does not have a most specific implementation. Neither 'I2.I1.Item[int]', nor 'I3.I1.Item[int]' are most specific. // class Test1 : I4 Diagnostic(ErrorCode.ERR_MostSpecificImplementationIsNotFound, "I4").WithArguments("I1.this[int]", "I2.I1.Item[int]", "I3.I1.Item[int]").WithLocation(2, 15) ); } [Fact] [WorkItem(35769, "https://github.com/dotnet/roslyn/issues/35769")] public void IndexerReAbstraction_071() { var source1 = @" public interface I1 { int this[int i] { set => throw null; } } public interface I2 : I1 { abstract int I1.this[int i] {set;} } public interface I3 : I1 { abstract int I1.this[int i] {set;} } public interface I4 : I2, I3 { int I1.this[int i] { set { System.Console.WriteLine(""I4.set_P1""); } } } "; var source2 = @" class Test1 : I4 { static void Main() { I1 i1 = new Test1(); i1[0] = 1; } } "; ValidatePropertyReAbstraction_013(source1, source2, "I4.set_P1"); } [Fact] public void IndexerReAbstraction_072() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] { set { throw null; } } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.this[int].set' cannot declare a body because it is marked abstract // set Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.this[int].set").WithLocation(11, 9), // (18,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(18, 15) ); } [Fact] public void IndexerReAbstraction_073() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] { set => throw null; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (11,9): error CS0500: 'I2.I1.this[int].set' cannot declare a body because it is marked abstract // set => throw null; Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("I2.I1.this[int].set").WithLocation(11, 9), // (15,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(15, 15) ); } [Fact] public void IndexerReAbstraction_074() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { extern abstract int I1.this[int i] {set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_016(source1, // (9,28): error CS0180: 'I2.I1.this[int]' cannot be both extern and abstract // extern abstract int I1.this[int i] {set;} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "this").WithArguments("I2.I1.this[int]").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_075() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract public int I1.this[int i] { set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,28): error CS0106: The modifier 'public' is not valid for this item // abstract public int I1.this[int i] { set;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("public").WithLocation(9, 28), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_076() { var source1 = @" public interface I1 { int this[int i] {set;} } public class C2 : I1 { abstract int I1.this[int i] { set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.this[int i] { set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(9, 21), // (9,35): error CS0501: 'C2.I1.this[int].set' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { set; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("C2.I1.this[int].set").WithLocation(9, 35) ); } [Fact] public void IndexerReAbstraction_077() { var source1 = @" public interface I1 { int this[int i] {set;} } public struct C2 : I1 { abstract int I1.this[int i] { set; } } "; ValidatePropertyReAbstraction_018(source1, // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract int I1.this[int i] { set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(9, 21), // (9,35): error CS0501: 'C2.I1.this[int].set' must declare a body because it is not marked abstract, extern, or partial // abstract int I1.this[int i] { set; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("C2.I1.this[int].set").WithLocation(9, 35) ); } [Fact] public void IndexerReAbstraction_078() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] { set; } } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,21): error CS0551: Explicit interface implementation 'I2.I1.this[int]' is missing accessor 'I1.this[int].get' // abstract int I1.this[int i] { set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("I2.I1.this[int]", "I1.this[int].get").WithLocation(9, 21), // (9,35): error CS0550: 'I2.I1.this[int].set' adds an accessor not found in interface member 'I1.this[int]' // abstract int I1.this[int i] { set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("I2.I1.this[int].set", "I1.this[int]").WithLocation(9, 35), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_079() { var source1 = @" public interface I1 { internal int this[int i] {set => throw null;} } "; var source2 = @" public interface I2 : I1 { abstract int I1.this[int i] { set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_026(source1, source2, // (4,21): error CS0122: 'I1.this[int]' is inaccessible due to its protection level // abstract int I1.this[int i] { set;} Diagnostic(ErrorCode.ERR_BadAccess, "this").WithArguments("I1.this[int]").WithLocation(4, 21), // (7,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(7, 15) ); } [Fact] public void IndexerReAbstraction_080() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] { get; set; } = 0; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,47): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // abstract int I1.this[int i] { get; set; } = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(9, 47), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_081() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] { get; } = 0; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,42): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // abstract int I1.this[int i] { get; } = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(9, 42), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_082() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] { set; } = 0; } class Test1 : I2 { } "; ValidatePropertyReAbstraction_014(source1, // (9,42): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // abstract int I1.this[int i] { set; } = 0; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(9, 42), // (12,15): error CS0535: 'Test1' does not implement interface member 'I1.this[int]' // class Test1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test1", "I1.this[int]").WithLocation(12, 15) ); } [Fact] public void IndexerReAbstraction_083() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (8,21): error CS0539: 'I2.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("I2.this[int]").WithLocation(8, 21) ); } [Fact] public void IndexerReAbstraction_084() { var source1 = @" public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,18): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 18), // (4,18): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 18) ); } [Fact] public void IndexerReAbstraction_085() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract int I1.this[int i] {get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (8,21): error CS0539: 'I2.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // abstract int I1.this[int i] {get;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("I2.this[int]").WithLocation(8, 21) ); } [Fact] public void IndexerReAbstraction_086() { var source1 = @" public interface I2 : I1 { abstract int I1.this[int i] {get;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,18): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract int I1.this[int i] {get;} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 18), // (4,18): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract int I1.this[int i] {get;} Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 18) ); } [Fact] public void IndexerReAbstraction_087() { var source1 = @" public interface I1 { } public interface I2 : I1 { abstract int I1.this[int i] {set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (8,21): error CS0539: 'I2.this[int]' in explicit interface declaration is not found among members of the interface that can be implemented // abstract int I1.this[int i] {set;} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("I2.this[int]").WithLocation(8, 21) ); } [Fact] public void IndexerReAbstraction_088() { var source1 = @" public interface I2 : I1 { abstract int I1.this[int i] {set;} } class Test1 : I2 { } "; ValidatePropertyReAbstraction_083(source1, // (2,23): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // public interface I2 : I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(2, 23), // (4,18): error CS0246: The type or namespace name 'I1' could not be found (are you missing a using directive or an assembly reference?) // abstract int I1.this[int i] {set;} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I1").WithArguments("I1").WithLocation(4, 18), // (4,18): error CS0538: 'I1' in explicit interface declaration is not an interface // abstract int I1.this[int i] {set;} Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "I1").WithArguments("I1").WithLocation(4, 18) ); } [Fact] public void IndexerReAbstraction_089() { var source1 = @" public interface I1 { int this[int i] {get; set;} } public interface I2 : I1 { abstract int I1.this[int i] {get; set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,34): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(9, 34), // (9,39): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(9, 39) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,34): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(9, 34), // (9,39): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.this[int i] {get; set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(9, 39) ); } [Fact] public void IndexerReAbstraction_090() { var source1 = @" public interface I1 { int this[int i] {get;} } public interface I2 : I1 { abstract int I1.this[int i] {get;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,34): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.this[int i] {get;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "get").WithArguments("default interface implementation", "8.0").WithLocation(9, 34) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,34): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.this[int i] {get;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "get").WithLocation(9, 34) ); } [Fact] public void IndexerReAbstraction_091() { var source1 = @" public interface I1 { int this[int i] {set;} } public interface I2 : I1 { abstract int I1.this[int i] {set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,34): error CS8652: The feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // abstract int I1.this[int i] {set;} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "set").WithArguments("default interface implementation", "8.0").WithLocation(9, 34) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.DesktopLatestExtended); compilation2.VerifyDiagnostics( // (9,34): error CS8701: Target runtime doesn't support default interface implementation. // abstract int I1.this[int i] {set;} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "set").WithLocation(9, 34) ); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void ImplicitImplementationOfNonPublicMethod_01() { var ilSource = @" .class interface public abstract auto ansi I1 { .method assembly hidebysig newslot strict virtual instance string M() cil managed { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""I1.M"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } // end of method I1::M .method public hidebysig instance string Test() cil managed { // Code size 12 (0xc) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: callvirt instance string I1::M() IL_0007: stloc.0 IL_0008: br.s IL_000a IL_000a: ldloc.0 IL_000b: ret } // end of method I1::Test } // end of class I1 .class public auto ansi beforefieldinit C0 extends System.Object implements I1 { .method public hidebysig newslot virtual instance string M() cil managed { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""C0.M"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } // end of method C0::M .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C0::.ctor } // end of class C0 "; var source1 = @" class Test { static void Main() { I1 x = new C0(); System.Console.WriteLine(x.Test()); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: "C0.M"); var c0 = compilation1.GetTypeByMetadataName("C0"); var i1M = compilation1.GetMember<MethodSymbol>("I1.M"); Assert.Equal("System.String C0.M()", c0.FindImplementationForInterfaceMember(i1M).ToTestDisplayString()); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] public void ImplicitImplementationOfNonPublicMethod_02() { var ilSource = @" .class interface public abstract auto ansi I1 { .method assembly hidebysig newslot strict virtual instance string M() cil managed { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""I1.M"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } // end of method I1::M .method public hidebysig instance string Test() cil managed { // Code size 12 (0xc) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: callvirt instance string I1::M() IL_0007: stloc.0 IL_0008: br.s IL_000a IL_000a: ldloc.0 IL_000b: ret } // end of method I1::Test } // end of class I1 .class public auto ansi beforefieldinit C0 extends System.Object implements I1 { .method public hidebysig newslot virtual instance string M() cil managed { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""C0.M"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } // end of method C0::M .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C0::.ctor } // end of class C0 "; var source1 = @" class Test : C0, I1 { static void Main() { I1 x = new Test(); System.Console.WriteLine(x.Test()); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: "C0.M"); var test = compilation1.GetTypeByMetadataName("Test"); var i1M = compilation1.GetMember<MethodSymbol>("I1.M"); Assert.Equal("System.String C0.M()", test.FindImplementationForInterfaceMember(i1M).ToTestDisplayString()); } [Fact] public void ImplicitImplementationOfNonPublicMethod_03() { var source1 = @" public interface I1 { internal string M() { return ""I1.M""; } public sealed string Test() { return M(); } } public class C0 : I1 { public virtual string M() { return ""C0.M""; } } class Test : C0, I1 { static void Main() { I1 x = new Test(); System.Console.WriteLine(x.Test()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); var i1M = compilation1.GetMember<MethodSymbol>("I1.M"); var c0 = compilation1.GetTypeByMetadataName("C0"); var test = compilation1.GetTypeByMetadataName("Test"); Assert.Equal("System.String C0.M()", c0.FindImplementationForInterfaceMember(i1M).ToTestDisplayString()); Assert.Equal("System.String C0.M()", test.FindImplementationForInterfaceMember(i1M).ToTestDisplayString()); compilation1.VerifyDiagnostics( // (15,19): error CS8704: 'C0' does not implement interface member 'I1.M()'. 'C0.M()' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class C0 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("C0", "I1.M()", "C0.M()", "9.0", "10.0").WithLocation(15, 19) ); compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); i1M = compilation1.GetMember<MethodSymbol>("I1.M"); c0 = compilation1.GetTypeByMetadataName("C0"); test = compilation1.GetTypeByMetadataName("Test"); Assert.Equal("System.String C0.M()", c0.FindImplementationForInterfaceMember(i1M).ToTestDisplayString()); Assert.Equal("System.String C0.M()", test.FindImplementationForInterfaceMember(i1M).ToTestDisplayString()); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "C0.M", verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] public void ImplicitImplementationOfNonPublicMethod_04() { var source1 = @" public interface I1 { internal int get_P(); } public class C0 : I1 { public virtual int P { get; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,19): error CS8704: 'C0' does not implement interface member 'I1.get_P()'. 'C0.P.get' cannot implicitly implement a non-public member in C# 9.0. Please use language version '10.0' or greater. // public class C0 : I1 Diagnostic(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, "I1").WithArguments("C0", "I1.get_P()", "C0.P.get", "9.0", "10.0").WithLocation(7, 19), // (9,28): error CS0686: Accessor 'C0.P.get' cannot implement interface member 'I1.get_P()' for type 'C0'. Use an explicit interface implementation. // public virtual int P { get; } Diagnostic(ErrorCode.ERR_AccessorImplementingMethod, "get").WithArguments("C0.P.get", "I1.get_P()", "C0").WithLocation(9, 28) ); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,28): error CS0686: Accessor 'C0.P.get' cannot implement interface member 'I1.get_P()' for type 'C0'. Use an explicit interface implementation. // public virtual int P { get; } Diagnostic(ErrorCode.ERR_AccessorImplementingMethod, "get").WithArguments("C0.P.get", "I1.get_P()", "C0").WithLocation(9, 28) ); } private static string BuildAssemblyExternClause(PortableExecutableReference reference) { AssemblyIdentity assemblyIdentity = ((AssemblyMetadata)reference.GetMetadata()).GetAssembly().Identity; Version version = assemblyIdentity.Version; var publicKeyToken = assemblyIdentity.PublicKeyToken; if (publicKeyToken.Length > 0) { return @" .assembly extern " + assemblyIdentity.Name + @" { .publickeytoken = (" + publicKeyToken[0].ToString("X2") + publicKeyToken[1].ToString("X2") + publicKeyToken[2].ToString("X2") + publicKeyToken[3].ToString("X2") + publicKeyToken[4].ToString("X2") + publicKeyToken[5].ToString("X2") + publicKeyToken[6].ToString("X2") + publicKeyToken[7].ToString("X2") + @" ) .ver " + $"{version.Major}:{version.Minor}:{version.Build}:{version.Revision}" + @" } "; } else { return @" .assembly extern " + assemblyIdentity.Name + @" { .ver " + $"{version.Major}:{version.Minor}:{version.Build}:{version.Revision}" + @" } "; } } [Fact] [WorkItem(36532, "https://github.com/dotnet/roslyn/issues/36532")] public void WindowsRuntimeEvent_01() { var windowsRuntimeRef = CompilationExtensions.CreateWindowsRuntimeMetadataReference(); var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + BuildAssemblyExternClause(windowsRuntimeRef) + @" .class public auto ansi sealed Event extends [System.Runtime]System.MulticastDelegate { .method private hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public hidebysig newslot specialname virtual instance void Invoke() runtime managed { } } // end of class Event .class interface public abstract auto ansi Interface`1<T> { .method public hidebysig newslot specialname abstract virtual instance void add_Normal(class Event 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance void remove_Normal(class Event 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance valuetype [System.Runtime.InteropServices.WindowsRuntime]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken add_WinRT([in] class Event 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance void remove_WinRT([in] valuetype [System.Runtime.InteropServices.WindowsRuntime]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken 'value') cil managed { } .event Event Normal { .addon instance void Interface`1::add_Normal(class Event) .removeon instance void Interface`1::remove_Normal(class Event) } // end of event I`1::Normal .event Event WinRT { .addon instance valuetype [System.Runtime.InteropServices.WindowsRuntime]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken Interface`1::add_WinRT(class Event) .removeon instance void Interface`1::remove_WinRT(valuetype [System.Runtime.InteropServices.WindowsRuntime]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) } } // end of class Interface "; var source = @" interface I1 : Interface<int> { event Event Interface<int>.Normal { add { throw null; } remove { throw null; } } event Event Interface<int>.WinRT { add { return new System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken(); } remove { System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken x = value; x.ToString(); } } } class C1 : I1, Interface<int> {} "; foreach (var options in new[] { TestOptions.DebugDll, TestOptions.DebugWinMD }) { var comp = CreateCompilationWithIL(source, ilSource, options: options, targetFramework: TargetFramework.NetCoreApp, references: new[] { windowsRuntimeRef }); void Validate(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var c1 = m.GlobalNamespace.GetTypeMember("C1"); var baseInterface = i1.Interfaces().Single(); Assert.True(baseInterface.IsInterface); Assert.True(i1.IsInterface); var i1Normal = i1.GetMember<EventSymbol>("Interface<System.Int32>.Normal"); var i1WinRT = i1.GetMember<EventSymbol>("Interface<System.Int32>.WinRT"); var baseInterfaceNormal = baseInterface.GetMember<EventSymbol>("Normal"); var baseInterfaceWinRT = baseInterface.GetMember<EventSymbol>("WinRT"); Assert.False(baseInterfaceNormal.IsWindowsRuntimeEvent); Assert.False(i1Normal.IsWindowsRuntimeEvent); Assert.True(baseInterfaceWinRT.IsWindowsRuntimeEvent); Assert.True(i1WinRT.IsWindowsRuntimeEvent); Assert.Same(i1Normal, i1.FindImplementationForInterfaceMember(baseInterfaceNormal)); Assert.Same(i1Normal.AddMethod, i1.FindImplementationForInterfaceMember(baseInterfaceNormal.AddMethod)); Assert.Same(i1Normal.RemoveMethod, i1.FindImplementationForInterfaceMember(baseInterfaceNormal.RemoveMethod)); Assert.Same(i1WinRT, i1.FindImplementationForInterfaceMember(baseInterfaceWinRT)); Assert.Same(i1WinRT.AddMethod, i1.FindImplementationForInterfaceMember(baseInterfaceWinRT.AddMethod)); Assert.Same(i1WinRT.RemoveMethod, i1.FindImplementationForInterfaceMember(baseInterfaceWinRT.RemoveMethod)); Assert.Same(i1Normal, c1.FindImplementationForInterfaceMember(baseInterfaceNormal)); Assert.Same(i1Normal.AddMethod, c1.FindImplementationForInterfaceMember(baseInterfaceNormal.AddMethod)); Assert.Same(i1Normal.RemoveMethod, c1.FindImplementationForInterfaceMember(baseInterfaceNormal.RemoveMethod)); Assert.Same(i1WinRT, c1.FindImplementationForInterfaceMember(baseInterfaceWinRT)); Assert.Same(i1WinRT.AddMethod, c1.FindImplementationForInterfaceMember(baseInterfaceWinRT.AddMethod)); Assert.Same(i1WinRT.RemoveMethod, c1.FindImplementationForInterfaceMember(baseInterfaceWinRT.RemoveMethod)); Assert.Equal("void I1.Interface<System.Int32>.Normal.add", i1Normal.AddMethod.ToTestDisplayString()); Assert.Equal("void I1.Interface<System.Int32>.Normal.remove", i1Normal.RemoveMethod.ToTestDisplayString()); Assert.Equal("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken I1.Interface<System.Int32>.WinRT.add", i1WinRT.AddMethod.ToTestDisplayString()); Assert.Equal("void I1.Interface<System.Int32>.WinRT.remove", i1WinRT.RemoveMethod.ToTestDisplayString()); } Validate(comp.SourceModule); CompileAndVerify(comp, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); } } [Fact] [WorkItem(36532, "https://github.com/dotnet/roslyn/issues/36532")] public void WindowsRuntimeEvent_02() { var source = @" interface I1 { event System.Action WinRT { add { return new System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken(); } remove { System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken x = value; x.ToString(); } } } class C1 : I1 { } "; var comp = CreateCompilation(source, options: TestOptions.DebugWinMD, targetFramework: TargetFramework.NetCoreApp, references: new[] { CompilationExtensions.CreateWindowsRuntimeMetadataReference() }); void Validate(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var c1 = m.GlobalNamespace.GetTypeMember("C1"); var i1WinRT = i1.GetMember<EventSymbol>("WinRT"); Assert.True(i1WinRT.IsWindowsRuntimeEvent); Assert.Same(i1WinRT, c1.FindImplementationForInterfaceMember(i1WinRT)); Assert.Same(i1WinRT.AddMethod, c1.FindImplementationForInterfaceMember(i1WinRT.AddMethod)); Assert.Same(i1WinRT.RemoveMethod, c1.FindImplementationForInterfaceMember(i1WinRT.RemoveMethod)); Assert.Equal("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken I1.WinRT.add", i1WinRT.AddMethod.ToTestDisplayString()); Assert.Equal("void I1.WinRT.remove", i1WinRT.RemoveMethod.ToTestDisplayString()); } Validate(comp.SourceModule); CompileAndVerify(comp, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); } [Fact] [WorkItem(36532, "https://github.com/dotnet/roslyn/issues/36532")] public void WindowsRuntimeEvent_03() { var source = @" interface Interface { event System.Action WinRT; } interface I1 : Interface { event System.Action Interface.WinRT { add { return new System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken(); } remove { System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken x = value; x.ToString(); } } } class C1 : I1, Interface {} "; var comp = CreateCompilation(source, options: TestOptions.DebugWinMD, targetFramework: TargetFramework.NetCoreApp, references: new[] { CompilationExtensions.CreateWindowsRuntimeMetadataReference() }); void Validate(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); var c1 = m.GlobalNamespace.GetTypeMember("C1"); var baseInterface = i1.Interfaces().Single(); Assert.True(baseInterface.IsInterface); Assert.True(i1.IsInterface); var i1WinRT = i1.GetMember<EventSymbol>("Interface.WinRT"); var baseInterfaceWinRT = baseInterface.GetMember<EventSymbol>("WinRT"); Assert.True(baseInterfaceWinRT.IsWindowsRuntimeEvent); Assert.True(i1WinRT.IsWindowsRuntimeEvent); Assert.Same(i1WinRT, i1.FindImplementationForInterfaceMember(baseInterfaceWinRT)); Assert.Same(i1WinRT.AddMethod, i1.FindImplementationForInterfaceMember(baseInterfaceWinRT.AddMethod)); Assert.Same(i1WinRT.RemoveMethod, i1.FindImplementationForInterfaceMember(baseInterfaceWinRT.RemoveMethod)); Assert.Same(i1WinRT, c1.FindImplementationForInterfaceMember(baseInterfaceWinRT)); Assert.Same(i1WinRT.AddMethod, c1.FindImplementationForInterfaceMember(baseInterfaceWinRT.AddMethod)); Assert.Same(i1WinRT.RemoveMethod, c1.FindImplementationForInterfaceMember(baseInterfaceWinRT.RemoveMethod)); Assert.Equal("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken I1.Interface.WinRT.add", i1WinRT.AddMethod.ToTestDisplayString()); Assert.Equal("void I1.Interface.WinRT.remove", i1WinRT.RemoveMethod.ToTestDisplayString()); } Validate(comp.SourceModule); CompileAndVerify(comp, verify: VerifyOnMonoOrCoreClr, symbolValidator: Validate); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_01() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P1() cil managed { } // end of method I1::get_P1 .method public hidebysig newslot specialname abstract virtual instance int32 get_P2() cil managed { } // end of method I1::get_P2 .method public hidebysig newslot specialname abstract virtual instance void set_P2(int32 'value') cil managed { } // end of method I1::set_P2 .method public hidebysig newslot specialname abstract virtual instance void set_P3(int32 'value') cil managed { } // end of method I1::set_P3 .method public hidebysig newslot specialname abstract virtual instance void add_E1(class [System.Runtime]System.Action 'value') cil managed { } // end of method I1::add_E1 .method public hidebysig newslot specialname abstract virtual instance void remove_E1(class [System.Runtime]System.Action 'value') cil managed { } // end of method I1::remove_E1 .event [System.Runtime]System.Action E1 { .addon instance void I1::add_E1(class [System.Runtime]System.Action) .removeon instance void I1::remove_E1(class [System.Runtime]System.Action) } // end of event I1::E1 .property instance int32 P1() { .get instance int32 I1::get_P1() } // end of property I1::P1 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 .property instance int32 P3() { .set instance void I1::set_P3(int32) } // end of property I1::P3 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object implements I1 { .method private hidebysig newslot specialname virtual final instance int32 I1.get_P1() cil managed { .override I1::get_P1 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.get_P1 .method private hidebysig newslot specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.get_P2 .method private hidebysig newslot specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.set_P2 .method private hidebysig newslot specialname virtual final instance void I1.set_P3(int32 'value') cil managed { .override I1::set_P3 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.set_P3 .method private hidebysig newslot specialname virtual final instance void I1.add_E1(class [System.Runtime]System.Action 'value') cil managed { .override I1::add_E1 // Code size 3 (0x3) .maxstack 8 IL_0000: nop IL_0001: ldnull IL_0002: throw } // end of method C1::I1.add_E1 .method private hidebysig newslot specialname virtual final instance void I1.remove_E1(class [System.Runtime]System.Action 'value') cil managed { .override I1::remove_E1 // Code size 3 (0x3) .maxstack 8 IL_0000: nop IL_0001: ldnull IL_0002: throw } // end of method C1::I1.remove_E1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor } // end of class C1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P1() cil managed { .override I1::get_P1 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P1 .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .method private hidebysig specialname virtual final instance void I1.set_P3(int32 'value') cil managed { .override I1::set_P3 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P3 .method private hidebysig specialname virtual final instance void I1.add_E1(class [System.Runtime]System.Action 'value') cil managed { .override I1::add_E1 // Code size 3 (0x3) .maxstack 8 IL_0000: nop IL_0001: ldnull IL_0002: throw } // end of method I2::I1.add_E1 .method private hidebysig specialname virtual final instance void I1.remove_E1(class [System.Runtime]System.Action 'value') cil managed { .override I1::remove_E1 // Code size 3 (0x3) .maxstack 8 IL_0000: nop IL_0001: ldnull IL_0002: throw } // end of method I2::I1.remove_E1 } // end of class I2 "; var source1 = @" class Test1 : C1, I1 { } class Test2 : I2, I1 { } class Test3 : I2 { public long P1 {get => throw null;} public long P2 {get => throw null; set => throw null;} public long P3 {set => throw null;} } class Test4 : C1, I1 { public long P1 {get => throw null;} public long P2 {get => throw null; set => throw null;} public long P3 {set => throw null;} } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,19): error CS0535: 'Test2' does not implement interface member 'I1.E1' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.E1").WithLocation(6, 19), // (6,19): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(6, 19), // (6,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(6, 19), // (6,19): error CS0535: 'Test2' does not implement interface member 'I1.P3' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P3").WithLocation(6, 19), // (10,15): error CS0535: 'Test3' does not implement interface member 'I1.E1' // class Test3 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test3", "I1.E1").WithLocation(10, 15), // (10,15): error CS0738: 'Test3' does not implement interface member 'I1.P1'. 'Test3.P1' cannot implement 'I1.P1' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P1", "Test3.P1", "int").WithLocation(10, 15), // (10,15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(10, 15), // (10,15): error CS0738: 'Test3' does not implement interface member 'I1.P3'. 'Test3.P3' cannot implement 'I1.P3' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P3", "Test3.P3", "int").WithLocation(10, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var c1 = compilation1.GetTypeByMetadataName("C1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var test4 = compilation1.GetTypeByMetadataName("Test4"); var i1P1 = i1.GetMember<PropertySymbol>("P1"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i1P3 = i1.GetMember<PropertySymbol>("P3"); var i1E1 = i1.GetMember<EventSymbol>("E1"); var i2i1P1get = i2.GetMember<MethodSymbol>("I1.get_P1"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); var i2i1P3set = i2.GetMember<MethodSymbol>("I1.set_P3"); var i2i1E1add = i2.GetMember<MethodSymbol>("I1.add_E1"); var i2i1E1remove = i2.GetMember<MethodSymbol>("I1.remove_E1"); var c1i1P1get = c1.GetMember<MethodSymbol>("I1.get_P1"); var c1i1P2get = c1.GetMember<MethodSymbol>("I1.get_P2"); var c1i1P2set = c1.GetMember<MethodSymbol>("I1.set_P2"); var c1i1P3set = c1.GetMember<MethodSymbol>("I1.set_P3"); var c1i1E1add = c1.GetMember<MethodSymbol>("I1.add_E1"); var c1i1E1remove = c1.GetMember<MethodSymbol>("I1.remove_E1"); Assert.Null(i2.FindImplementationForInterfaceMember(i1P1)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P3)); Assert.Null(i2.FindImplementationForInterfaceMember(i1E1)); Assert.Same(i2i1P1get, test2.FindImplementationForInterfaceMember(i1P1.GetMethod)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(i2i1P3set, test2.FindImplementationForInterfaceMember(i1P3.SetMethod)); Assert.Same(i2i1E1add, test2.FindImplementationForInterfaceMember(i1E1.AddMethod)); Assert.Same(i2i1E1remove, test2.FindImplementationForInterfaceMember(i1E1.RemoveMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P3)); Assert.Null(test2.FindImplementationForInterfaceMember(i1E1)); Assert.Same(c1i1P1get, test1.FindImplementationForInterfaceMember(i1P1.GetMethod)); Assert.Same(c1i1P2get, test1.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test1.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(c1i1P3set, test1.FindImplementationForInterfaceMember(i1P3.SetMethod)); Assert.Same(c1i1E1add, test1.FindImplementationForInterfaceMember(i1E1.AddMethod)); Assert.Same(c1i1E1remove, test1.FindImplementationForInterfaceMember(i1E1.RemoveMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1P1)); Assert.Null(test1.FindImplementationForInterfaceMember(i1P2)); Assert.Null(test1.FindImplementationForInterfaceMember(i1P3)); Assert.Null(test1.FindImplementationForInterfaceMember(i1E1)); Assert.Same(c1i1P1get, test4.FindImplementationForInterfaceMember(i1P1.GetMethod)); Assert.Same(c1i1P2get, test4.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test4.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(c1i1P3set, test4.FindImplementationForInterfaceMember(i1P3.SetMethod)); Assert.Same(c1i1E1add, test4.FindImplementationForInterfaceMember(i1E1.AddMethod)); Assert.Same(c1i1E1remove, test4.FindImplementationForInterfaceMember(i1E1.RemoveMethod)); Assert.Null(test4.FindImplementationForInterfaceMember(i1P1)); Assert.Null(test4.FindImplementationForInterfaceMember(i1P2)); Assert.Null(test4.FindImplementationForInterfaceMember(i1P3)); Assert.Null(test4.FindImplementationForInterfaceMember(i1E1)); Assert.Same(i2i1P1get, test3.FindImplementationForInterfaceMember(i1P1.GetMethod)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(i2i1P3set, test3.FindImplementationForInterfaceMember(i1P3.SetMethod)); Assert.Same(i2i1E1add, test3.FindImplementationForInterfaceMember(i1E1.AddMethod)); Assert.Same(i2i1E1remove, test3.FindImplementationForInterfaceMember(i1E1.RemoveMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P1)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P3)); Assert.Null(test3.FindImplementationForInterfaceMember(i1E1)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_02() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P2() cil managed { } // end of method I1::get_P2 .method public hidebysig newslot specialname abstract virtual instance void set_P2(int32 'value') cil managed { } // end of method I1::set_P2 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object implements I1 { .method private hidebysig newslot specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.get_P2 .method private hidebysig newslot specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.set_P2 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor .property instance int32 I1.P2() { .get instance int32 C1::I1.get_P2() } // end of property C1::I1.P2 } // end of class C1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .property instance int32 I1.P2() { .get instance int32 I2::I1.get_P2() } // end of property I2::I1.P2 } // end of class I2 "; var source1 = @" class Test1 : C1, I1 { } class Test2 : I2, I1 { } class Test3 : I2 { public long P2 {get => throw null; set => throw null;} } class Test4 : C1, I1 { public long P2 {get => throw null; set => throw null;} } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(6, 19), // (10, 15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(10, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var c1 = compilation1.GetTypeByMetadataName("C1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var test4 = compilation1.GetTypeByMetadataName("Test4"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i2i1P2 = i2.GetMember<PropertySymbol>("I1.P2"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); var c1i1P2 = c1.GetMember<PropertySymbol>("I1.P2"); var c1i1P2get = c1.GetMember<MethodSymbol>("I1.get_P2"); var c1i1P2set = c1.GetMember<MethodSymbol>("I1.set_P2"); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(c1i1P2get, test1.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test1.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(c1i1P2, test1.FindImplementationForInterfaceMember(i1P2)); Assert.Same(c1i1P2get, test4.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test4.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(c1i1P2, test4.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_03() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P2() cil managed { } // end of method I1::get_P2 .method public hidebysig newslot specialname abstract virtual instance void set_P2(int32 'value') cil managed { } // end of method I1::set_P2 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object implements I1 { .method private hidebysig newslot specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.get_P2 .method private hidebysig newslot specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.set_P2 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor .property instance int32 I1.P2() { .set instance void C1::I1.set_P2(int32) } // end of property C1::I1.P2 } // end of class C1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .property instance int32 I1.P2() { .set instance void I2::I1.set_P2(int32) } // end of property I2::I1.P2 } // end of class I2 "; var source1 = @" class Test1 : C1, I1 { } class Test2 : I2, I1 { } class Test3 : I2 { public long P2 {get => throw null; set => throw null;} } class Test4 : C1, I1 { public long P2 {get => throw null; set => throw null;} } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(6, 19), // (10,15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(10, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var c1 = compilation1.GetTypeByMetadataName("C1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var test4 = compilation1.GetTypeByMetadataName("Test4"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i2i1P2 = i2.GetMember<PropertySymbol>("I1.P2"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); var c1i1P2 = c1.GetMember<PropertySymbol>("I1.P2"); var c1i1P2get = c1.GetMember<MethodSymbol>("I1.get_P2"); var c1i1P2set = c1.GetMember<MethodSymbol>("I1.set_P2"); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(c1i1P2get, test1.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test1.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(c1i1P2, test1.FindImplementationForInterfaceMember(i1P2)); Assert.Same(c1i1P2get, test4.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test4.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(c1i1P2, test4.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_04() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P2() cil managed { } // end of method I1::get_P2 .method public hidebysig newslot specialname abstract virtual instance void set_P2(int32 'value') cil managed { } // end of method I1::set_P2 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object implements I1 { .method private hidebysig newslot specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.get_P2 .method private hidebysig newslot specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::I1.set_P2 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor .property instance int32 I1.P21() { .get instance int32 C1::I1.get_P2() } // end of property C1::I1.P2 .property instance int32 I1.P22() { .set instance void C1::I1.set_P2(int32) } // end of property C1::I1.P2 } // end of class C1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .property instance int32 I1.P21() { .get instance int32 I2::I1.get_P2() } // end of property I2::I1.P2 .property instance int32 I1.P22() { .set instance void I2::I1.set_P2(int32) } // end of property I2::I1.P2 } // end of class I2 "; var source1 = @" class Test1 : C1, I1 { } class Test2 : I2, I1 { } class Test3 : I2 { public long P2 {get => throw null; set => throw null;} } class Test4 : C1, I1 { public long P2 {get => throw null; set => throw null;} } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(6, 19), // (10,15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(10, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var c1 = compilation1.GetTypeByMetadataName("C1"); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var test4 = compilation1.GetTypeByMetadataName("Test4"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); var c1i1P2get = c1.GetMember<MethodSymbol>("I1.get_P2"); var c1i1P2set = c1.GetMember<MethodSymbol>("I1.set_P2"); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(c1i1P2get, test1.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test1.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test1.FindImplementationForInterfaceMember(i1P2)); Assert.Same(c1i1P2get, test4.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(c1i1P2set, test4.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test4.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); } [Fact] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_05() { var ilSource = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P2() cil managed { } // end of method I1::get_P2 .method public hidebysig newslot specialname abstract virtual instance void set_P2(int32 'value') cil managed { } // end of method I1::set_P2 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [mscorlib]System.Object { .method public hidebysig newslot specialname instance int32 get_P2() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method C1::get_P2 .method public hidebysig newslot specialname instance void set_P2(int32 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C1::set_P2 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor .property instance int32 P2() { .get instance int32 C1::get_P2() .set instance void C1::set_P2(int32) } // end of property C1::P2 } // end of class C1 .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method private hidebysig newslot specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.2 IL_0001: ret } // end of method C2::I1.get_P2 .method private hidebysig newslot specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method C2::I1.set_P2 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: nop IL_0007: ret } // end of method C2::.ctor .property instance int32 I1.P21() { .get instance int32 C2::I1.get_P2() } // end of property C2::I1.P2 .property instance int32 I1.P22() { .set instance void C2::I1.set_P2(int32) } // end of property C2::I1.P2 } // end of class C2 "; var source1 = @" class C3 : C2, I1 { static void Main() { I1 x = new C3(); System.Console.WriteLine(x.P2); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugExe); var i1 = compilation1.GetTypeByMetadataName("I1"); var c3 = compilation1.GetTypeByMetadataName("C3"); Assert.Null(c3.FindImplementationForInterfaceMember(i1.GetMember<PropertySymbol>("P2"))); CompileAndVerify(compilation1, expectedOutput: "2"); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_06() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname virtual instance int32 get_P1() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::get_P1 .method public hidebysig newslot specialname virtual instance int32 get_P2() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::get_P2 .method public hidebysig newslot specialname virtual instance void set_P2(int32 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::set_P2 .method public hidebysig newslot specialname virtual instance void set_P3(int32 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::set_P3 .method public hidebysig newslot specialname virtual instance void add_E1(class [System.Runtime]System.Action 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::add_E1 .method public hidebysig newslot specialname virtual instance void remove_E1(class [System.Runtime]System.Action 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::remove_E1 .event [System.Runtime]System.Action E1 { .addon instance void I1::add_E1(class [System.Runtime]System.Action) .removeon instance void I1::remove_E1(class [System.Runtime]System.Action) } // end of event I1::E1 .property instance int32 P1() { .get instance int32 I1::get_P1() } // end of property I1::P1 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 .property instance int32 P3() { .set instance void I1::set_P3(int32) } // end of property I1::P3 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P1() cil managed { .override I1::get_P1 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P1 .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .method private hidebysig specialname virtual final instance void I1.set_P3(int32 'value') cil managed { .override I1::set_P3 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P3 .method private hidebysig specialname virtual final instance void I1.add_E1(class [System.Runtime]System.Action 'value') cil managed { .override I1::add_E1 // Code size 3 (0x3) .maxstack 8 IL_0000: nop IL_0001: ldnull IL_0002: throw } // end of method I2::I1.add_E1 .method private hidebysig specialname virtual final instance void I1.remove_E1(class [System.Runtime]System.Action 'value') cil managed { .override I1::remove_E1 // Code size 3 (0x3) .maxstack 8 IL_0000: nop IL_0001: ldnull IL_0002: throw } // end of method I2::I1.remove_E1 } // end of class I2 "; var source1 = @" class Test2 : I2, I1 { } class Test3 : I2 { public long P1 {get => throw null;} public long P2 {get => throw null; set => throw null;} public long P3 {set => throw null;} } interface I3 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'Test2' does not implement interface member 'I1.E1' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.E1").WithLocation(2, 19), // (2,19): error CS0535: 'Test2' does not implement interface member 'I1.P1' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P1").WithLocation(2, 19), // (2,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(2, 19), // (2,19): error CS0535: 'Test2' does not implement interface member 'I1.P3' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P3").WithLocation(2, 19), // (6,15): error CS0535: 'Test3' does not implement interface member 'I1.E1' // class Test3 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Test3", "I1.E1").WithLocation(6, 15), // (6,15): error CS0738: 'Test3' does not implement interface member 'I1.P1'. 'Test3.P1' cannot implement 'I1.P1' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P1", "Test3.P1", "int").WithLocation(6, 15), // (6,15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(6, 15), // (6,15): error CS0738: 'Test3' does not implement interface member 'I1.P3'. 'Test3.P3' cannot implement 'I1.P3' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P3", "Test3.P3", "int").WithLocation(6, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var i3 = compilation1.GetTypeByMetadataName("I3"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var i1P1 = i1.GetMember<PropertySymbol>("P1"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i1P3 = i1.GetMember<PropertySymbol>("P3"); var i1E1 = i1.GetMember<EventSymbol>("E1"); var i2i1P1get = i2.GetMember<MethodSymbol>("I1.get_P1"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); var i2i1P3set = i2.GetMember<MethodSymbol>("I1.set_P3"); var i2i1E1add = i2.GetMember<MethodSymbol>("I1.add_E1"); var i2i1E1remove = i2.GetMember<MethodSymbol>("I1.remove_E1"); Assert.Null(i3.FindImplementationForInterfaceMember(i1P1)); Assert.Null(i3.FindImplementationForInterfaceMember(i1P2)); Assert.Null(i3.FindImplementationForInterfaceMember(i1P3)); Assert.Null(i3.FindImplementationForInterfaceMember(i1E1)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P1)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P3)); Assert.Null(i2.FindImplementationForInterfaceMember(i1E1)); Assert.Same(i2i1P1get, test2.FindImplementationForInterfaceMember(i1P1.GetMethod)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(i2i1P3set, test2.FindImplementationForInterfaceMember(i1P3.SetMethod)); Assert.Same(i2i1E1add, test2.FindImplementationForInterfaceMember(i1E1.AddMethod)); Assert.Same(i2i1E1remove, test2.FindImplementationForInterfaceMember(i1E1.RemoveMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P1)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P3)); Assert.Null(test2.FindImplementationForInterfaceMember(i1E1)); Assert.Same(i2i1P1get, test3.FindImplementationForInterfaceMember(i1P1.GetMethod)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Same(i2i1P3set, test3.FindImplementationForInterfaceMember(i1P3.SetMethod)); Assert.Same(i2i1E1add, test3.FindImplementationForInterfaceMember(i1E1.AddMethod)); Assert.Same(i2i1E1remove, test3.FindImplementationForInterfaceMember(i1E1.RemoveMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P1)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P3)); Assert.Null(test3.FindImplementationForInterfaceMember(i1E1)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_07() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname virtual instance int32 get_P2() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::get_P2 .method public hidebysig newslot specialname virtual instance void set_P2(int32 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::set_P2 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .property instance int32 I1.P2() { .get instance int32 I2::I1.get_P2() } // end of property I2::I1.P2 } // end of class I2 "; var source1 = @" class Test2 : I2, I1 { } class Test3 : I2 { public long P2 {get => throw null; set => throw null;} } interface I3 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(2, 19), // (6,15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(6, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var i3 = compilation1.GetTypeByMetadataName("I3"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i2i1P2 = i2.GetMember<PropertySymbol>("I1.P2"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); Assert.Null(i3.FindImplementationForInterfaceMember(i1P2)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_08() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname virtual instance int32 get_P2() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::get_P2 .method public hidebysig newslot specialname virtual instance void set_P2(int32 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::set_P2 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .property instance int32 I1.P2() { .set instance void I2::I1.set_P2(int32) } // end of property I2::I1.P2 } // end of class I2 "; var source1 = @" class Test2 : I2, I1 { } class Test3 : I2 { public long P2 {get => throw null; set => throw null;} } interface I3 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(2, 19), // (6,15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(6, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var i3 = compilation1.GetTypeByMetadataName("I3"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i2i1P2 = i2.GetMember<PropertySymbol>("I1.P2"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); Assert.Null(i3.FindImplementationForInterfaceMember(i1P2)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34452, "https://github.com/dotnet/roslyn/issues/34452")] public void ExplicitlyImplementedViaAccessors_09() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname virtual instance int32 get_P2() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::get_P2 .method public hidebysig newslot specialname virtual instance void set_P2(int32 'value') cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I1::set_P2 .property instance int32 P2() { .get instance int32 I1::get_P2() .set instance void I1::set_P2(int32) } // end of property I1::P2 } // end of class I1 .class interface public abstract auto ansi I2 implements I1 { .method private hidebysig specialname virtual final instance int32 I1.get_P2() cil managed { .override I1::get_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.get_P2 .method private hidebysig specialname virtual final instance void I1.set_P2(int32 'value') cil managed { .override I1::set_P2 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method I2::I1.set_P2 .property instance int32 I1.P21() { .get instance int32 I2::I1.get_P2() } // end of property I2::I1.P2 .property instance int32 I1.P22() { .set instance void I2::I1.set_P2(int32) } // end of property I2::I1.P2 } // end of class I2 "; var source1 = @" class Test2 : I2, I1 { } class Test3 : I2 { public long P2 {get => throw null; set => throw null;} } interface I3 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'Test2' does not implement interface member 'I1.P2' // class Test2 : I2, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Test2", "I1.P2").WithLocation(2, 19), // (6,15): error CS0738: 'Test3' does not implement interface member 'I1.P2'. 'Test3.P2' cannot implement 'I1.P2' because it does not have the matching return type of 'int'. // class Test3 : I2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I2").WithArguments("Test3", "I1.P2", "Test3.P2", "int").WithLocation(6, 15) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var i3 = compilation1.GetTypeByMetadataName("I3"); var test2 = compilation1.GetTypeByMetadataName("Test2"); var test3 = compilation1.GetTypeByMetadataName("Test3"); var i1P2 = i1.GetMember<PropertySymbol>("P2"); var i2i1P2get = i2.GetMember<MethodSymbol>("I1.get_P2"); var i2i1P2set = i2.GetMember<MethodSymbol>("I1.set_P2"); Assert.Null(i3.FindImplementationForInterfaceMember(i1P2)); Assert.Null(i2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test2.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test2.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test2.FindImplementationForInterfaceMember(i1P2)); Assert.Same(i2i1P2get, test3.FindImplementationForInterfaceMember(i1P2.GetMethod)); Assert.Same(i2i1P2set, test3.FindImplementationForInterfaceMember(i1P2.SetMethod)); Assert.Null(test3.FindImplementationForInterfaceMember(i1P2)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34453, "https://github.com/dotnet/roslyn/issues/34453")] public void CheckForImplementationOfCorrespondingPropertyOrEvent_01() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance string get_P1() cil managed { } // end of method I1::get_P1 .property instance string P1() { .get instance string I1::get_P1() } // end of property I1::P1 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object { .method public hidebysig specialname virtual instance string get_P1() cil managed { // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr ""C1"" IL_0005: ret } // end of method C1::get_P1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor .property instance string P2() { .get instance string C1::get_P1() } // end of property C1::P1 } // end of class C1 "; var source1 = @" class C2 : C1, I1 { static void Main() { I1 x = new C2(); System.Console.WriteLine(x.P1); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,16): error CS0535: 'C2' does not implement interface member 'I1.P1' // class C2 : C1, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1").WithLocation(2, 16) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var c2 = compilation1.GetTypeByMetadataName("C2"); var p1 = i1.GetMember<PropertySymbol>("P1"); Assert.Null(c2.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(c2.FindImplementationForInterfaceMember(p1)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34453, "https://github.com/dotnet/roslyn/issues/34453")] public void CheckForImplementationOfCorrespondingPropertyOrEvent_02() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname virtual instance string get_P1() cil managed { // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr ""I1"" IL_0005: ret } // end of method I1::get_P1 .property instance string P1() { .get instance string I1::get_P1() } // end of property I1::P1 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object { .method public hidebysig specialname virtual instance string get_P1() cil managed { // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr ""C1"" IL_0005: ret } // end of method C1::get_P1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor .property instance string P2() { .get instance string C1::get_P1() } // end of property C1::P1 } // end of class C1 "; var source1 = @" class C2 : C1, I1 { static void Main() { I1 x = new C2(); System.Console.WriteLine(x.P1); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,16): error CS0535: 'C2' does not implement interface member 'I1.P1' // class C2 : C1, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1").WithLocation(2, 16) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var c2 = compilation1.GetTypeByMetadataName("C2"); var p1 = i1.GetMember<PropertySymbol>("P1"); Assert.Null(c2.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(c2.FindImplementationForInterfaceMember(p1)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34453, "https://github.com/dotnet/roslyn/issues/34453")] public void CheckForImplementationOfCorrespondingPropertyOrEvent_03() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname abstract virtual instance string get_P1() cil managed { } // end of method I1::get_P1 .property instance string P1() { .get instance string I1::get_P1() } // end of property I1::P1 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object { .method public hidebysig specialname virtual instance string get_P1() cil managed { // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr ""C1"" IL_0005: ret } // end of method C1::get_P1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor } // end of class C1 "; var source1 = @" class C2 : C1, I1 { static void Main() { I1 x = new C2(); System.Console.WriteLine(x.P1); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,16): error CS0535: 'C2' does not implement interface member 'I1.P1' // class C2 : C1, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1").WithLocation(2, 16), // (2,16): error CS0470: Method 'C1.get_P1()' cannot implement interface accessor 'I1.P1.get' for type 'C2'. Use an explicit interface implementation. // class C2 : C1, I1 Diagnostic(ErrorCode.ERR_MethodImplementingAccessor, "I1").WithArguments("C1.get_P1()", "I1.P1.get", "C2").WithLocation(2, 16) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var c1 = compilation1.GetTypeByMetadataName("C1"); var c2 = compilation1.GetTypeByMetadataName("C2"); var p1 = i1.GetMember<PropertySymbol>("P1"); Assert.Same(c1.GetMember("get_P1"), c2.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(c2.FindImplementationForInterfaceMember(p1)); } [ConditionalFact(typeof(MonoOrCoreClrOnly))] [WorkItem(34453, "https://github.com/dotnet/roslyn/issues/34453")] public void CheckForImplementationOfCorrespondingPropertyOrEvent_04() { var ilSource = BuildAssemblyExternClause(NetCoreApp.SystemRuntime) + @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot specialname virtual instance string get_P1() cil managed { // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr ""I1"" IL_0005: ret } // end of method I1::get_P1 .property instance string P1() { .get instance string I1::get_P1() } // end of property I1::P1 } // end of class I1 .class public auto ansi beforefieldinit C1 extends [System.Runtime]System.Object { .method public hidebysig specialname virtual instance string get_P1() cil managed { // Code size 6 (0x6) .maxstack 8 IL_0000: ldstr ""C1"" IL_0005: ret } // end of method C1::get_P1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor } // end of class C1 "; var source1 = @" class C2 : C1, I1 { static void Main() { I1 x = new C2(); System.Console.WriteLine(x.P1); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,16): error CS0535: 'C2' does not implement interface member 'I1.P1' // class C2 : C1, I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C2", "I1.P1").WithLocation(2, 16), // (2,16): error CS0470: Method 'C1.get_P1()' cannot implement interface accessor 'I1.P1.get' for type 'C2'. Use an explicit interface implementation. // class C2 : C1, I1 Diagnostic(ErrorCode.ERR_MethodImplementingAccessor, "I1").WithArguments("C1.get_P1()", "I1.P1.get", "C2").WithLocation(2, 16) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var c1 = compilation1.GetTypeByMetadataName("C1"); var c2 = compilation1.GetTypeByMetadataName("C2"); var p1 = i1.GetMember<PropertySymbol>("P1"); Assert.Same(c1.GetMember("get_P1"), c2.FindImplementationForInterfaceMember(p1.GetMethod)); Assert.Null(c2.FindImplementationForInterfaceMember(p1)); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_11() { var source1 = @" interface A : A.B { public interface B { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'A.B' causes a cycle in the interface hierarchy of 'A' // interface A : A.B Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "A").WithArguments("A", "A.B").WithLocation(2, 11) ); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_12() { var source1 = @" interface A : A.B.I { public interface B : A { public interface I { } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'A.B.I' causes a cycle in the interface hierarchy of 'A' // interface A : A.B.I Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "A").WithArguments("A", "A.B.I").WithLocation(2, 11), // (4,22): error CS0529: Inherited interface 'A' causes a cycle in the interface hierarchy of 'A.B' // public interface B : A Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "B").WithArguments("A.B", "A").WithLocation(4, 22) ); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_13() { var source1 = @" interface IA : IB.IQ { } interface IB : IA { interface IQ { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'IB.IQ' causes a cycle in the interface hierarchy of 'IA' // interface IA : IB.IQ Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IA").WithArguments("IA", "IB.IQ").WithLocation(2, 11), // (6,11): error CS0529: Inherited interface 'IA' causes a cycle in the interface hierarchy of 'IB' // interface IB : IA Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IB").WithArguments("IB", "IA").WithLocation(6, 11) ); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_14() { var source1 = @" interface IB : IA { interface IQ { } } interface IA : IB.IQ { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'IA' causes a cycle in the interface hierarchy of 'IB' // interface IB : IA Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IB").WithArguments("IB", "IA").WithLocation(2, 11), // (7,11): error CS0529: Inherited interface 'IB.IQ' causes a cycle in the interface hierarchy of 'IA' // interface IA : IB.IQ Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IA").WithArguments("IA", "IB.IQ").WithLocation(7, 11) ); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_15() { var source1 = @" class B : IA { public interface IQ { } } interface IA : B.IQ { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_16() { var source1 = @" interface I1 { class C : I1 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_17() { var source1 = @" class C : C.I1 { interface I1 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_18() { var source1 = @" public class CB : CB.CCB.IB, CB.ICB.IB { public class CCB { public interface IB { } } public interface ICB { public interface IB { } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_19() { var source1 = @" public class CD : CD.ICD.CB { public interface ICD { public class CB { } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,14): error CS0146: Circular base type dependency involving 'CD.ICD.CB' and 'CD' // public class CD : CD.ICD.CB Diagnostic(ErrorCode.ERR_CircularBase, "CD").WithArguments("CD.ICD.CB", "CD").WithLocation(2, 14) ); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_20() { var source1 = @" public interface IE : IE.CIE.IB, IE.IIE.IB { public class CIE { public interface IB { } } public interface IIE { public interface IB { } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,18): error CS0529: Inherited interface 'IE.CIE.IB' causes a cycle in the interface hierarchy of 'IE' // public interface IE : IE.CIE.IB, IE.IIE.IB Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IE").WithArguments("IE", "IE.CIE.IB").WithLocation(2, 18), // (2,18): error CS0529: Inherited interface 'IE.IIE.IB' causes a cycle in the interface hierarchy of 'IE' // public interface IE : IE.CIE.IB, IE.IIE.IB Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IE").WithArguments("IE", "IE.IIE.IB").WithLocation(2, 18) ); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_21() { var source1 = @" class C1 : C1.C2.I3 { public class C2 { public interface I3 { } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_22() { var source1 = @" class CA : IB.CQ { public interface I1 { } } interface IB : CA.I1 { public class CQ { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,7): error CS0146: Circular base type dependency involving 'IB.CQ' and 'CA' // class CA : IB.CQ Diagnostic(ErrorCode.ERR_CircularBase, "CA").WithArguments("IB.CQ", "CA").WithLocation(2, 7), // (8,11): error CS0529: Inherited interface 'CA.I1' causes a cycle in the interface hierarchy of 'IB' // interface IB : CA.I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IB").WithArguments("IB", "CA.I1").WithLocation(8, 11) ); } [Fact] [WorkItem(34704, "https://github.com/dotnet/roslyn/issues/34704")] public void NestedTypes_23() { var source1 = @" interface IB : CA.I1 { public class CQ { } } class CA : IB.CQ { public interface I1 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'CA.I1' causes a cycle in the interface hierarchy of 'IB' // interface IB : CA.I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "IB").WithArguments("IB", "CA.I1").WithLocation(2, 11), // (8,7): error CS0146: Circular base type dependency involving 'IB.CQ' and 'CA' // class CA : IB.CQ Diagnostic(ErrorCode.ERR_CircularBase, "CA").WithArguments("IB.CQ", "CA").WithLocation(8, 7) ); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_24() { var source1 = @" interface I100 { public class C100 { public void Test1() { System.Console.WriteLine(""I100.C100.Test1""); } public static void Test2() { System.Console.WriteLine(""I100.C100.Test2""); } } } interface I101 : I100 { private static C100 Test1() => new C100(); static void Main() { Test1().Test1(); C100.Test2(); } }"; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I100.C100.Test1 I100.C100.Test2", verify: VerifyOnMonoOrCoreClr); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_25() { var source1 = @" interface I100 { public class C100 { public void Test1() { System.Console.WriteLine(""I100.C100.Test1""); } public static void Test2() { System.Console.WriteLine(""I100.C100.Test2""); } } } interface I101 : I100 { private static I100.C100 Test1() => new I100.C100(); static void Main() { Test1().Test1(); I100.C100.Test2(); } }"; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I100.C100.Test1 I100.C100.Test2", verify: VerifyOnMonoOrCoreClr); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_26() { var source1 = @" interface I100 { public class C100 { public void Test1() { System.Console.WriteLine(""I100.C100.Test1""); } public static void Test2() { System.Console.WriteLine(""I100.C100.Test2""); } } } interface I101 : I100 { private static I101.C100 Test1() => new I101.C100(); static void Main() { Test1().Test1(); I101.C100.Test2(); } }"; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"I100.C100.Test1 I100.C100.Test2", verify: VerifyOnMonoOrCoreClr); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_27() { var source1 = @" public interface I100 { public class C100 { public void Test1() { System.Console.WriteLine(""I100.C100.Test1""); } } } public class C100 { public void Test1() { System.Console.WriteLine(""C100.Test1""); } } public interface I101 : I100 { C100 Test1(); } class Test : I101 { public virtual C100 Test1() => new C100(); static void Main() { I101 x = new Test(); x.Test1().Test1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (26,14): error CS0738: 'Test' does not implement interface member 'I101.Test1()'. 'Test.Test1()' cannot implement 'I101.Test1()' because it does not have the matching return type of 'I100.C100'. // class Test : I101 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I101").WithArguments("Test", "I101.Test1()", "Test.Test1()", "I100.C100").WithLocation(26, 14) ); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_28() { var source1 = @" public interface I100 { public class C100 { public void Test1() { System.Console.WriteLine(""I100.C100.Test1""); } } } public class C100 { public void Test1() { System.Console.WriteLine(""C100.Test1""); } } public interface I101 : I100 { C100 Test1(); } class Test : I101 { public virtual I100.C100 Test1() => new I100.C100(); static void Main() { I101 x = new Test(); x.Test1().Test1(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1, expectedOutput: "I100.C100.Test1"); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_29() { var source1 = @" interface A : C.E { } interface B : A { public interface E {} } interface C : B { public interface E {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'C.E' causes a cycle in the interface hierarchy of 'A' // interface A : C.E Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "A").WithArguments("A", "C.E").WithLocation(2, 11), // (6,11): error CS0529: Inherited interface 'A' causes a cycle in the interface hierarchy of 'B' // interface B : A Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "B").WithArguments("B", "A").WithLocation(6, 11), // (12,11): error CS0529: Inherited interface 'B' causes a cycle in the interface hierarchy of 'C' // interface C : B Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "C").WithArguments("C", "B").WithLocation(12, 11) ); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_30() { var source1 = @" #nullable enable interface A : B, C<object> { } interface B : C<object?> { } interface C<T> { public interface E {} } interface D : A.E { A.E Test(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,11): warning CS8645: 'C<object>' is already listed in the interface list on type 'A' with different nullability of reference types. // interface A : B, C<object> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "A").WithArguments("C<object>", "A").WithLocation(4, 11) ); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_31() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { new interface I2 { void Test(I2 x); } } interface I4 : I1, I3 { class C1 : I2 { public void Test(I2 x) {} } } interface I5 : I3, I1 { class C2 : I2 { public void Test(I2 x) {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1); } [Fact] [WorkItem(38469, "https://github.com/dotnet/roslyn/issues/38469")] public void NestedTypes_32() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { new interface I2 { void Test(I2 x); } } interface I4 : I1, I3 { class C1 : I2 { void I2.Test(I2 x) {} } } interface I5 : I3, I1 { class C2 : I2 { void I2.Test(I2 x) {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics(); CompileAndVerify(compilation1); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_33() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { interface I2 { } } class C1 { public interface I4 { } } class C3 : C1 { public interface I4 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (10,15): warning CS0108: 'I3.I2' hides inherited member 'I1.I2'. Use the new keyword if hiding was intended. // interface I2 Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2", "I1.I2").WithLocation(10, 15), // (23,22): warning CS0108: 'C3.I4' hides inherited member 'C1.I4'. Use the new keyword if hiding was intended. // public interface I4 Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4", "C1.I4").WithLocation(23, 22) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_34() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { new interface I2 { } } class C1 { public interface I4 { } } class C3 : C1 { new public interface I4 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_35() { var source1 = @" interface I1 { void I2(); } interface I3 : I1 { interface I2 { } } class C1 { public void I4() { } } class C3 : C1 { public interface I4 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (9,15): warning CS0108: 'I3.I2' hides inherited member 'I1.I2()'. Use the new keyword if hiding was intended. // interface I2 Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2", "I1.I2()").WithLocation(9, 15), // (22,22): warning CS0108: 'C3.I4' hides inherited member 'C1.I4()'. Use the new keyword if hiding was intended. // public interface I4 Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4", "C1.I4()").WithLocation(22, 22) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_36() { var source1 = @" interface I1 { void I2(); } interface I3 : I1 { new interface I2 { } } class C1 { public void I4() { } } class C3 : C1 { new public interface I4 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_37() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { void I2(); } class C1 { public interface I4 { } } class C3 : C1 { public void I4() { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (11,10): warning CS0108: 'I3.I2()' hides inherited member 'I1.I2'. Use the new keyword if hiding was intended. // void I2(); Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2()", "I1.I2").WithLocation(11, 10), // (23,17): warning CS0108: 'C3.I4()' hides inherited member 'C1.I4'. Use the new keyword if hiding was intended. // public void I4() Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4()", "C1.I4").WithLocation(23, 17) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_38() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { new void I2(); } class C1 { public interface I4 { } } class C3 : C1 { new public void I4() { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_39() { var source1 = @" interface I1 { static int I2 = 0; } interface I3 : I1 { static int I2 = 1; } class C1 { public static int I4 = 2; } class C3 : C1 { public static int I4 = 3; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,16): warning CS0108: 'I3.I2' hides inherited member 'I1.I2'. Use the new keyword if hiding was intended. // static int I2 = 1; Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2", "I1.I2").WithLocation(9, 16), // (19,23): warning CS0108: 'C3.I4' hides inherited member 'C1.I4'. Use the new keyword if hiding was intended. // public static int I4 = 3; Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4", "C1.I4").WithLocation(19, 23) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_40() { var source1 = @" interface I1 { static int I2 = 0; } interface I3 : I1 { new static int I2 = 1; } class C1 { public static int I4 = 2; } class C3 : C1 { new public static int I4 = 3; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_41() { var source1 = @" interface I1 { void I2(); } interface I3 : I1 { static int I2 = 0; } class C1 { public void I4() { } } class C3 : C1 { public static int I4 = 1; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,16): warning CS0108: 'I3.I2' hides inherited member 'I1.I2()'. Use the new keyword if hiding was intended. // static int I2 = 0; Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2", "I1.I2()").WithLocation(9, 16), // (20,23): warning CS0108: 'C3.I4' hides inherited member 'C1.I4()'. Use the new keyword if hiding was intended. // public static int I4 = 1; Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4", "C1.I4()").WithLocation(20, 23) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_42() { var source1 = @" interface I1 { void I2(); } interface I3 : I1 { new static int I2 = 0; } class C1 { public void I4() { } } class C3 : C1 { new public static int I4 = 1; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_43() { var source1 = @" interface I1 { static int I2 = 0; } interface I3 : I1 { void I2(); } class C1 { public static int I4 = 1; } class C3 : C1 { public void I4() { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,10): warning CS0108: 'I3.I2()' hides inherited member 'I1.I2'. Use the new keyword if hiding was intended. // void I2(); Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2()", "I1.I2").WithLocation(9, 10), // (19,17): warning CS0108: 'C3.I4()' hides inherited member 'C1.I4'. Use the new keyword if hiding was intended. // public void I4() Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4()", "C1.I4").WithLocation(19, 17) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_44() { var source1 = @" interface I1 { static int I2 = 0; } interface I3 : I1 { new void I2(); } class C1 { public static int I4 = 1; } class C3 : C1 { new public void I4() { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_45() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { interface I2<T> { } } class C1 { public interface I4 { } } class C3 : C1 { public interface I4<T> { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); CompileAndVerify(compilation1).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_46() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { new interface I2<T> { } } class C1 { public interface I4 { } } class C3 : C1 { public new interface I4<T> { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (10,19): warning CS0109: The member 'I3.I2<T>' does not hide an accessible member. The new keyword is not required. // new interface I2<T> Diagnostic(ErrorCode.WRN_NewNotRequired, "I2").WithArguments("I3.I2<T>").WithLocation(10, 19), // (23,26): warning CS0109: The member 'C3.I4<T>' does not hide an accessible member. The new keyword is not required. // public new interface I4<T> Diagnostic(ErrorCode.WRN_NewNotRequired, "I4").WithArguments("C3.I4<T>").WithLocation(23, 26) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_47() { var source1 = @" interface I1<T> { interface I2 { } interface I2<U> { } } interface I3 : I1<int> { interface I2 { } } class C1<T> { public interface I4 { } public interface I4<U> { } } class C3 : C1<int> { public interface I4 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (13,15): warning CS0108: 'I3.I2' hides inherited member 'I1<int>.I2'. Use the new keyword if hiding was intended. // interface I2 Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2", "I1<int>.I2").WithLocation(13, 15), // (29,22): warning CS0108: 'C3.I4' hides inherited member 'C1<int>.I4'. Use the new keyword if hiding was intended. // public interface I4 Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4", "C1<int>.I4").WithLocation(29, 22) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_48() { var source1 = @" interface I1 { static int I2 = 1; } interface I3 : I1 { interface I2 { } } class C1 { public static int I4 = 2; } class C3 : C1 { public interface I4 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,15): warning CS0108: 'I3.I2' hides inherited member 'I1.I2'. Use the new keyword if hiding was intended. // interface I2 Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2", "I1.I2").WithLocation(9, 15), // (21,22): warning CS0108: 'C3.I4' hides inherited member 'C1.I4'. Use the new keyword if hiding was intended. // public interface I4 Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4", "C1.I4").WithLocation(21, 22) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_49() { var source1 = @" interface I1 { static int I2 = 1; } interface I3 : I1 { new interface I2 { } } class C1 { public static int I4 = 2; } class C3 : C1 { new public interface I4 { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_50() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { static int I2 = 0; } class C1 { public interface I4 { } } class C3 : C1 { public static int I4 = 2; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (10,16): warning CS0108: 'I3.I2' hides inherited member 'I1.I2'. Use the new keyword if hiding was intended. // static int I2 = 0; Diagnostic(ErrorCode.WRN_NewRequired, "I2").WithArguments("I3.I2", "I1.I2").WithLocation(10, 16), // (21,23): warning CS0108: 'C3.I4' hides inherited member 'C1.I4'. Use the new keyword if hiding was intended. // public static int I4 = 2; Diagnostic(ErrorCode.WRN_NewRequired, "I4").WithArguments("C3.I4", "C1.I4").WithLocation(21, 23) ); } [Fact] [WorkItem(38711, "https://github.com/dotnet/roslyn/issues/38711")] public void NestedTypes_51() { var source1 = @" interface I1 { interface I2 { } } interface I3 : I1 { new static int I2 = 0; } class C1 { public interface I4 { } } class C3 : C1 { new public static int I4 = 2; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr).VerifyDiagnostics(); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_01() { var source1 = @" interface I1<out T1, in T2, T3> { delegate void D11(T1 x); delegate T2 D12(); delegate T3 D13(T3 x); void M1(T1 x); T2 M2(); T3 M3(T3 x); interface I2 { void M21(T1 x); T2 M22(); T3 M23(T3 x); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,23): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I1<T1, T2, T3>.D11.Invoke(T1)'. 'T1' is covariant. // delegate void D11(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I1<T1, T2, T3>.D11.Invoke(T1)", "T1", "covariant", "contravariantly").WithLocation(4, 23), // (5,14): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I1<T1, T2, T3>.D12.Invoke()'. 'T2' is contravariant. // delegate T2 D12(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I1<T1, T2, T3>.D12.Invoke()", "T2", "contravariant", "covariantly").WithLocation(5, 14), // (8,13): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I1<T1, T2, T3>.M1(T1)'. 'T1' is covariant. // void M1(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I1<T1, T2, T3>.M1(T1)", "T1", "covariant", "contravariantly").WithLocation(8, 13), // (9,5): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I1<T1, T2, T3>.M2()'. 'T2' is contravariant. // T2 M2(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I1<T1, T2, T3>.M2()", "T2", "contravariant", "covariantly").WithLocation(9, 5), // (14,18): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I1<T1, T2, T3>.I2.M21(T1)'. 'T1' is covariant. // void M21(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I1<T1, T2, T3>.I2.M21(T1)", "T1", "covariant", "contravariantly").WithLocation(14, 18), // (15,9): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I1<T1, T2, T3>.I2.M22()'. 'T2' is contravariant. // T2 M22(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I1<T1, T2, T3>.I2.M22()", "T2", "contravariant", "covariantly").WithLocation(15, 9) ); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_02() { var source1 = @" interface I2<in T1, out T2> { delegate void D21(T1 x); delegate T2 D22(); void M1(T1 x); T2 M2(); interface I2 { void M21(T1 x); T2 M22(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_03() { var source1 = @" interface I1<out T1, in T2, T3> { interface I2 { delegate void D11(T1 x); delegate T2 D12(); delegate T3 D13(T3 x); interface I3 { void M31(T1 x); T2 M32(); T3 M33(T3 x); } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,27): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I1<T1, T2, T3>.I2.D11.Invoke(T1)'. 'T1' is covariant. // delegate void D11(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I1<T1, T2, T3>.I2.D11.Invoke(T1)", "T1", "covariant", "contravariantly").WithLocation(6, 27), // (7,18): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I1<T1, T2, T3>.I2.D12.Invoke()'. 'T2' is contravariant. // delegate T2 D12(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I1<T1, T2, T3>.I2.D12.Invoke()", "T2", "contravariant", "covariantly").WithLocation(7, 18), // (12,22): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I1<T1, T2, T3>.I2.I3.M31(T1)'. 'T1' is covariant. // void M31(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I1<T1, T2, T3>.I2.I3.M31(T1)", "T1", "covariant", "contravariantly").WithLocation(12, 22), // (13,13): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I1<T1, T2, T3>.I2.I3.M32()'. 'T2' is contravariant. // T2 M32(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I1<T1, T2, T3>.I2.I3.M32()", "T2", "contravariant", "covariantly").WithLocation(13, 13) ); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_04() { var source1 = @" interface I2<in T1, out T2> { interface I2 { delegate void D21(T1 x); delegate T2 D22(); interface I3 { void M31(T1 x); T2 M32(); } } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_05() { var source1 = @" interface I1<out T1> { class C1 { void MC1(T1 x) {} class C {} struct S {} enum E {} } struct S1 { void MS1(T1 x) {} class C {} struct S {} enum E {} } enum E1 {} } interface I2<in T2> { class C2 { T2 MC2() => default; class C {} struct S {} enum E {} } struct S2 { T2 MS2() => default; class C {} struct S {} enum E {} } enum E2 {} } interface I3<T3> { class C3 { T3 MC3(T3 x) => default; class C {} struct S {} enum E {} } struct S3 { T3 MS3(T3 x) => default; class C {} struct S {} enum E {} } enum E3 {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,11): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // class C1 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "C1").WithLocation(4, 11), // (11,12): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // struct S1 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "S1").WithLocation(11, 12), // (18,10): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // enum E1 {} Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "E1").WithLocation(18, 10), // (23,11): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // class C2 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "C2").WithLocation(23, 11), // (30,12): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // struct S2 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "S2").WithLocation(30, 12), // (37,10): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // enum E2 {} Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "E2").WithLocation(37, 10) ); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_06() { var source1 = @" interface I1<out T1> { interface I0 { class C1 { interface I { class C {} struct S {} enum E {} } } struct S1 { interface I { class C {} struct S {} enum E {} } } enum E1 {} } } interface I2<in T2> { interface I0 { class C2 { interface I { class C {} struct S {} enum E {} } } struct S2 { interface I { class C {} struct S {} enum E {} } } enum E2 {} } } interface I3<T3> { interface I0 { class C3 { interface I { class C {} struct S {} enum E {} } } struct S3 { interface I { class C {} struct S {} enum E {} } } enum E3 {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,15): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // class C1 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "C1").WithLocation(6, 15), // (15,16): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // struct S1 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "S1").WithLocation(15, 16), // (24,14): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // enum E1 {} Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "E1").WithLocation(24, 14), // (32,15): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // class C2 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "C2").WithLocation(32, 15), // (41,16): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // struct S2 Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "S2").WithLocation(41, 16), // (50,14): error CS8427: Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. // enum E2 {} Diagnostic(ErrorCode.ERR_VarianceInterfaceNesting, "E2").WithLocation(50, 14) ); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_07() { var source1 = @" public interface I1<out T1, in T2, T3> { void M1() { T1 x = local(default, default); T1 local(T1 x, I2 y) { System.Console.WriteLine(""M1""); return x; } } void M2() { T2 x = local(default, default); T2 local(T2 x, I2.I3 y) { System.Console.WriteLine(""M2""); return x; } } void M3() { T3 x = local(default); T3 local(T3 x) { System.Console.WriteLine(""M3""); return x; } } interface I2 { void M4() { System.Console.WriteLine(""M4""); } interface I3 { } } delegate T1 D1(T2 x); delegate T3 D3(T3 x); } "; var source2 = @" class C1 : I1<C1, C1, C1>, I1<C1, object, C1>.I2 { static void Main() { I1<C1, C1, C1> x = new C1(); x.M1(); x.M2(); x.M3(); var y = (I1<C1, object, C1>.I2)x; I1<object, C1, C1>.I2 z = y; z.M4(); I1<C1, object, C1>.D1 d1 = M5; I1<object, C1, C1>.D1 d2 = d1; _ = d2(new C1()); } static C1 M5(object x) { System.Console.WriteLine(""M5""); return (C1)x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2 M3 M4 M5"); } } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_08() { var source1 = @" public interface I1<out T1, in T2> { void M1() { System.Func<T1, T1> d = (T1 x) => { System.Console.WriteLine(""M1""); return x; }; d(default); } void M2() { System.Func<T2, T2> d = (T2 x) => { System.Console.WriteLine(""M2""); return x; }; d(default); } } class C1 : I1<C1, C1> { static void Main() { I1<C1, C1> x = new C1(); x.M1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2"); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_09() { var source1 = @" using System.Collections.Generic; class Program : I2<int> { static void Main() { ((I2<int>)new Program()).M2().GetEnumerator().MoveNext(); } } interface I2<out T> { IEnumerable<int> M2() { System.Console.WriteLine(""M2""); yield break; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M2"); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_10() { var source1 = @" class Program { static void Main() { I2<string, string>.F1 = ""a""; I2<string, string>.F2 = ""b""; System.Console.WriteLine(I2<string, string>.F1); System.Console.WriteLine(I2<string, string>.F2); } } interface I2<out T1, in T2> { static T1 F1 = default; static T2 F2 = default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"a b"); } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_11() { var source1 = @" public interface I1<out T1, in T2> { void M1() { T1 x = local(default); T1 local(T1 x) { System.Console.WriteLine(GetString(""M1"")); return x; } } string GetString(string s) => s; void M2() { T2 x = local(default); T2 local(T2 x) { System.Console.WriteLine(GetString(""M2"")); return x; } } } "; var source2 = @" class C1 : I1<C1, C1> { static void Main() { I1<C1, C1> x = new C1(); x.M1(); x.M2(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(source2, new[] { reference }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"M1 M2"); } } [Fact] [WorkItem(39731, "https://github.com/dotnet/roslyn/issues/39731")] public void VarianceSafety_12() { var source1 = @" interface I1<out T1, in T2> { private void M1(T1 x) {} private T2 M2() => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,21): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I1<T1, T2>.M1(T1)'. 'T1' is covariant. // private void M1(T1 x) {} Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I1<T1, T2>.M1(T1)", "T1", "covariant", "contravariantly").WithLocation(4, 21), // (5,13): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I1<T1, T2>.M2()'. 'T2' is contravariant. // private T2 M2() => default; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I1<T1, T2>.M2()", "T2", "contravariant", "covariantly").WithLocation(5, 13) ); } [Fact] public void VarianceSafety_13() { var source1 = @" class Program { static void Main() { I2<string, string>.P1 = ""a""; I2<string, string>.P2 = ""b""; System.Console.WriteLine(I2<string, string>.P1); System.Console.WriteLine(I2<string, string>.P2); } } interface I2<out T1, in T2> { static T1 P1 { get; set; } static T2 P2 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (15,12): error CS8904: Invalid variance: The type parameter 'T1' must be invariantly valid on 'I2<T1, T2>.P1' unless language version '9.0' or greater is used. 'T1' is covariant. // static T1 P1 { get; set; } Diagnostic(ErrorCode.ERR_UnexpectedVarianceStaticMember, "T1").WithArguments("I2<T1, T2>.P1", "T1", "covariant", "invariantly", "9.0").WithLocation(15, 12), // (16,12): error CS8904: Invalid variance: The type parameter 'T2' must be invariantly valid on 'I2<T1, T2>.P2' unless language version '9.0' or greater is used. 'T2' is contravariant. // static T2 P2 { get; set; } Diagnostic(ErrorCode.ERR_UnexpectedVarianceStaticMember, "T2").WithArguments("I2<T1, T2>.P2", "T2", "contravariant", "invariantly", "9.0").WithLocation(16, 12) ); compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"a b").VerifyDiagnostics(); } [Fact] public void VarianceSafety_14() { var source1 = @" class Program { static void Main() { System.Console.WriteLine(I2<string, string>.M1(""a"")); System.Console.WriteLine(I2<string, string>.M2(""b"")); } } interface I2<out T1, in T2> { static T1 M1(T1 x) => x; static T2 M2(T2 x) => x; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (13,18): error CS8904: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.M1(T1)' unless language version '9.0' or greater is used. 'T1' is covariant. // static T1 M1(T1 x) => x; Diagnostic(ErrorCode.ERR_UnexpectedVarianceStaticMember, "T1").WithArguments("I2<T1, T2>.M1(T1)", "T1", "covariant", "contravariantly", "9.0").WithLocation(13, 18), // (14,12): error CS8904: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.M2(T2)' unless language version '9.0' or greater is used. 'T2' is contravariant. // static T2 M2(T2 x) => x; Diagnostic(ErrorCode.ERR_UnexpectedVarianceStaticMember, "T2").WithArguments("I2<T1, T2>.M2(T2)", "T2", "contravariant", "covariantly", "9.0").WithLocation(14, 12) ); compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"a b").VerifyDiagnostics(); } [Fact] public void VarianceSafety_15() { var source1 = @" class Program { static void Main() { I2<string, string>.E1 += Print1; I2<string, string>.E2 += Print2; I2<string, string>.Raise(); } static void Print1(System.Func<string, string> x) { System.Console.WriteLine(x(""a"")); } static void Print2(System.Func<string, string> x) { System.Console.WriteLine(x(""b"")); } } interface I2<out T1, in T2> { static event System.Action<System.Func<T1, T1>> E1; static event System.Action<System.Func<T2, T2>> E2; static void Raise() { E1(Print); E2(Print); } static T3 Print<T3>(T3 x) { return x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (24,53): error CS8904: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.E1' unless language version '9.0' or greater is used. 'T1' is covariant. // static event System.Action<System.Func<T1, T1>> E1; Diagnostic(ErrorCode.ERR_UnexpectedVarianceStaticMember, "E1").WithArguments("I2<T1, T2>.E1", "T1", "covariant", "contravariantly", "9.0").WithLocation(24, 53), // (25,53): error CS8904: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.E2' unless language version '9.0' or greater is used. 'T2' is contravariant. // static event System.Action<System.Func<T2, T2>> E2; Diagnostic(ErrorCode.ERR_UnexpectedVarianceStaticMember, "E2").WithArguments("I2<T1, T2>.E2", "T2", "contravariant", "covariantly", "9.0").WithLocation(25, 53) ); compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, verify: VerifyOnMonoOrCoreClr, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"a b").VerifyDiagnostics(); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_01() { var source1 = @" interface I1 { int I1::M1() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,9): error CS0540: 'I1.M1()': containing type does not implement interface 'I1' // int I1::M1() => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("I1.M1()", "I1").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I1::M1() => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11) ); AssertNoMethodImplementation(compilation1); } private static void AssertNoMethodImplementation(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); Assert.Empty(i1.GetMembers().OfType<MethodSymbol>().Single().ExplicitInterfaceImplementations); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_02() { var source1 = @" interface I1 : I1 { int I1::M1() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I1").WithLocation(2, 11), // (4,9): error CS0540: 'I1.M1()': containing type does not implement interface 'I1' // int I1::M1() => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("I1.M1()", "I1").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I1::M1() => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11) ); AssertNoMethodImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_03() { var source1 = @" interface I1 { int I2::M1() => throw null; } interface I2 { int M1(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,9): error CS0540: 'I1.I2.M1()': containing type does not implement interface 'I2' // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.I2.M1()", "I2").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); Assert.Same(i2.GetMembers().OfType<MethodSymbol>().Single(), i1.GetMembers().OfType<MethodSymbol>().Single().ExplicitInterfaceImplementations.Single()); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_04() { var source1 = @" interface I1 : I2 { int I2::M1() => throw null; } interface I2 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(2, 11), // (4,9): error CS0540: 'I1.M1()': containing type does not implement interface 'I2' // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.M1()", "I2").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11), // (4,13): error CS0539: 'I1.M1()' in explicit interface declaration is not found among members of the interface that can be implemented // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M1").WithArguments("I1.M1()").WithLocation(4, 13), // (7,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(7, 11) ); AssertNoMethodImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_05() { var source1 = @" interface I2 : I1 { } interface I1 : I2 { int I2::M1() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(2, 11), // (6,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(6, 11), // (8,9): error CS0540: 'I1.M1()': containing type does not implement interface 'I2' // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.M1()", "I2").WithLocation(8, 9), // (8,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(8, 11), // (8,13): error CS0539: 'I1.M1()' in explicit interface declaration is not found among members of the interface that can be implemented // int I2::M1() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M1").WithArguments("I1.M1()").WithLocation(8, 13) ); AssertNoMethodImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_06() { var source1 = @" interface I1 { int I1::P1 => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,9): error CS0540: 'I1.P1': containing type does not implement interface 'I1' // int I1::P1 => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("I1.P1", "I1").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I1::P1 => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11) ); AssertNoPropertyImplementation(compilation1); } private static void AssertNoPropertyImplementation(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Empty(m.ExplicitInterfaceImplementations); Assert.Empty(m.GetMethod.ExplicitInterfaceImplementations); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_07() { var source1 = @" interface I1 : I1 { int I1::P1 => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I1").WithLocation(2, 11), // (4,9): error CS0540: 'I1.P1': containing type does not implement interface 'I1' // int I1::P1 => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("I1.P1", "I1").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I1::P1 => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11) ); AssertNoPropertyImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_08() { var source1 = @" interface I1 { int I2::P1 => throw null; } interface I2 { int P1 {get;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,9): error CS0540: 'I1.I2.P1': containing type does not implement interface 'I2' // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.I2.P1", "I2").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var m1 = i1.GetMembers().OfType<PropertySymbol>().Single(); var m2 = i2.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(m2, m1.ExplicitInterfaceImplementations.Single()); Assert.Same(m2.GetMethod, m1.GetMethod.ExplicitInterfaceImplementations.Single()); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_09() { var source1 = @" interface I1 : I2 { int I2::P1 => throw null; } interface I2 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(2, 11), // (4,9): error CS0540: 'I1.P1': containing type does not implement interface 'I2' // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.P1", "I2").WithLocation(4, 9), // (4,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 11), // (4,13): error CS0539: 'I1.P1' in explicit interface declaration is not found among members of the interface that can be implemented // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("I1.P1").WithLocation(4, 13), // (7,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(7, 11) ); AssertNoPropertyImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_10() { var source1 = @" interface I2 : I1 { } interface I1 : I2 { int I2::P1 => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(2, 11), // (6,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(6, 11), // (8,9): error CS0540: 'I1.P1': containing type does not implement interface 'I2' // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.P1", "I2").WithLocation(8, 9), // (8,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(8, 11), // (8,13): error CS0539: 'I1.P1' in explicit interface declaration is not found among members of the interface that can be implemented // int I2::P1 => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P1").WithArguments("I1.P1").WithLocation(8, 13) ); AssertNoPropertyImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_11() { var source1 = @" interface I1 { event System.Action I1::E1 { add => throw null; remove => throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,25): error CS0540: 'I1.E1': containing type does not implement interface 'I1' // event System.Action I1::E1 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("I1.E1", "I1").WithLocation(4, 25), // (4,27): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // event System.Action I1::E1 Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 27) ); AssertNoEventImplementation(compilation1); } private static void AssertNoEventImplementation(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Empty(m.ExplicitInterfaceImplementations); Assert.Empty(m.AddMethod.ExplicitInterfaceImplementations); Assert.Empty(m.RemoveMethod.ExplicitInterfaceImplementations); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_12() { var source1 = @" interface I1 : I1 { event System.Action I1::E1 { add => throw null; remove => throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I1").WithLocation(2, 11), // (4,25): error CS0540: 'I1.E1': containing type does not implement interface 'I1' // event System.Action I1::E1 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("I1.E1", "I1").WithLocation(4, 25), // (4,27): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // event System.Action I1::E1 Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 27) ); AssertNoEventImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_13() { var source1 = @" interface I1 { event System.Action I2::E1 { add => throw null; remove => throw null;} } interface I2 { event System.Action E1; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,25): error CS0540: 'I1.I2.E1': containing type does not implement interface 'I2' // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.I2.E1", "I2").WithLocation(4, 25), // (4,27): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 27) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var i2 = compilation1.GetTypeByMetadataName("I2"); var m1 = i1.GetMembers().OfType<EventSymbol>().Single(); var m2 = i2.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(m2, m1.ExplicitInterfaceImplementations.Single()); Assert.Same(m2.AddMethod, m1.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m2.RemoveMethod, m1.RemoveMethod.ExplicitInterfaceImplementations.Single()); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_14() { var source1 = @" interface I1 : I2 { event System.Action I2::E1 { add => throw null; remove => throw null;} } interface I2 : I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(2, 11), // (4,25): error CS0540: 'I1.E1': containing type does not implement interface 'I2' // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.E1", "I2").WithLocation(4, 25), // (4,27): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(4, 27), // (4,29): error CS0539: 'I1.E1' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "E1").WithArguments("I1.E1").WithLocation(4, 29), // (8,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(8, 11) ); AssertNoEventImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_15() { var source1 = @" interface I2 : I1 { } interface I1 : I2 { event System.Action I2::E1 { add => throw null; remove => throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,11): error CS0529: Inherited interface 'I1' causes a cycle in the interface hierarchy of 'I2' // interface I2 : I1 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I2").WithArguments("I2", "I1").WithLocation(2, 11), // (6,11): error CS0529: Inherited interface 'I2' causes a cycle in the interface hierarchy of 'I1' // interface I1 : I2 Diagnostic(ErrorCode.ERR_CycleInInterfaceInheritance, "I1").WithArguments("I1", "I2").WithLocation(6, 11), // (8,25): error CS0540: 'I1.E1': containing type does not implement interface 'I2' // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.E1", "I2").WithLocation(8, 25), // (8,27): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(8, 27), // (8,29): error CS0539: 'I1.E1' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I2::E1 Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "E1").WithArguments("I1.E1").WithLocation(8, 29) ); AssertNoEventImplementation(compilation1); } [Fact] [WorkItem(1029574, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1029574")] public void Errors_16() { var source1 = @" interface I1<T> { int I1<int>.P1 => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,9): error CS0540: 'I1<T>.P1': containing type does not implement interface 'I1<int>' // int I1<int>.P1 => throw null; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<int>").WithArguments("I1<T>.P1", "I1<int>").WithLocation(4, 9) ); } [Fact, WorkItem(41481, "https://github.com/dotnet/roslyn/issues/41481")] public void IncompletePropertyImplementationSyntax_01() { var source1 = @"interface A { object A.B{"; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); compilation1.VerifyDiagnostics( // (3,12): error CS0540: 'A.B': containing type does not implement interface 'A' // object A.B{ Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "A").WithArguments("A.B", "A").WithLocation(3, 12), // (3,14): error CS0548: 'A.B': property or indexer must have at least one accessor // object A.B{ Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "B").WithArguments("A.B").WithLocation(3, 14), // (3,16): error CS1513: } expected // object A.B{ Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(3, 16), // (3,16): error CS1513: } expected // object A.B{ Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(3, 16) ); } [Fact, WorkItem(49341, "https://github.com/dotnet/roslyn/issues/49341")] public void RefReturningAutoProperty_01() { var source1 = @" interface IA { static ref int PA { get;} } interface IB { static ref int PB { get; set;} } interface IC { static ref int PC { set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,20): error CS8145: Auto-implemented properties cannot return by reference // static ref int PA { get;} Diagnostic(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, "PA").WithArguments("IA.PA").WithLocation(4, 20), // (9,20): error CS8145: Auto-implemented properties cannot return by reference // static ref int PB { get; set;} Diagnostic(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, "PB").WithArguments("IB.PB").WithLocation(9, 20), // (9,30): error CS8147: Properties which return by reference cannot have set accessors // static ref int PB { get; set;} Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("IB.PB.set").WithLocation(9, 30), // (14,20): error CS8146: Properties which return by reference must have a get accessor // static ref int PC { set;} Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "PC").WithArguments("IC.PC").WithLocation(14, 20) ); } [Fact, WorkItem(49341, "https://github.com/dotnet/roslyn/issues/49341")] public void RefReturningAutoProperty_02() { var source1 = @" interface IA { ref int PA { get;} } interface IB { ref int PB { get; set;} } interface IC { ref int PC { set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,23): error CS8147: Properties which return by reference cannot have set accessors // ref int PB { get; set;} Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("IB.PB.set").WithLocation(9, 23), // (14,13): error CS8146: Properties which return by reference must have a get accessor // ref int PC { set;} Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "PC").WithArguments("IC.PC").WithLocation(14, 13) ); } [Fact, WorkItem(49341, "https://github.com/dotnet/roslyn/issues/49341")] public void RefReturningAutoProperty_03() { var source1 = @" interface IA { sealed ref int PA { get;} } interface IB { sealed ref int PB { get; set;} } interface IC { sealed ref int PC { set;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,25): error CS0501: 'IA.PA.get' must declare a body because it is not marked abstract, extern, or partial // sealed ref int PA { get;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("IA.PA.get").WithLocation(4, 25), // (9,25): error CS0501: 'IB.PB.get' must declare a body because it is not marked abstract, extern, or partial // sealed ref int PB { get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("IB.PB.get").WithLocation(9, 25), // (9,30): error CS8147: Properties which return by reference cannot have set accessors // sealed ref int PB { get; set;} Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("IB.PB.set").WithLocation(9, 30), // (9,30): error CS0501: 'IB.PB.set' must declare a body because it is not marked abstract, extern, or partial // sealed ref int PB { get; set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("IB.PB.set").WithLocation(9, 30), // (14,20): error CS8146: Properties which return by reference must have a get accessor // sealed ref int PC { set;} Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "PC").WithArguments("IC.PC").WithLocation(14, 20), // (14,25): error CS0501: 'IC.PC.set' must declare a body because it is not marked abstract, extern, or partial // sealed ref int PC { set;} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("IC.PC.set").WithLocation(14, 25) ); } [Fact, WorkItem(50491, "https://github.com/dotnet/roslyn/issues/50491")] public void RuntimeFeatureAsInterface_01() { var source1 = @" namespace System.Runtime.CompilerServices { public static partial interface RuntimeFeature { public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); } } "; var compilation1 = CreateEmptyCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (4,37): error CS0106: The modifier 'static' is not valid for this item // public static partial interface RuntimeFeature Diagnostic(ErrorCode.ERR_BadMemberFlag, "RuntimeFeature").WithArguments("static").WithLocation(4, 37), // (6,22): error CS0518: Predefined type 'System.String' is not defined or imported // public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "string").WithArguments("System.String").WithLocation(6, 22), // (6,29): error CS8701: Target runtime doesn't support default interface implementation. // public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "DefaultImplementationsOfInterfaces").WithLocation(6, 29) ); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); } [Fact, WorkItem(50491, "https://github.com/dotnet/roslyn/issues/50491")] public void RuntimeFeatureAsInterface_02() { var source1 = @" namespace System.Runtime.CompilerServices { public partial interface RuntimeFeature { public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); } } "; var compilation1 = CreateEmptyCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation1.VerifyDiagnostics( // (6,22): error CS0518: Predefined type 'System.String' is not defined or imported // public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "string").WithArguments("System.String").WithLocation(6, 22), // (6,29): error CS8701: Target runtime doesn't support default interface implementation. // public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, "DefaultImplementationsOfInterfaces").WithLocation(6, 29) ); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); } [Fact, WorkItem(50491, "https://github.com/dotnet/roslyn/issues/50491")] public void RuntimeFeatureAsInterface_03() { var source1 = @" namespace System.Runtime.CompilerServices { public partial interface RuntimeFeature { public const string DefaultImplementationsOfInterfaces = ""Test""; } } class Test { static void Main() { System.Console.WriteLine(System.Runtime.CompilerServices.RuntimeFeature.DefaultImplementationsOfInterfaces); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "Test", verify: VerifyOnMonoOrCoreClr); } [Fact, WorkItem(53565, "https://github.com/dotnet/roslyn/issues/53565")] public void PartialPropertyImplementation_01() { var source1 = @" interface I1 { int P1 {get; set;} int P2 {get => throw null; internal set{}} int P3 {get => throw null; set{}} } class C0 : I1 { int I1.P1 {get; set;} } class C1 : C0, I1 { public int P1 { get { System.Console.WriteLine(""C1.get_P1""); return 0; } } public int P2 { get { System.Console.WriteLine(""C1.get_P2""); return 0; } } public int P3 { get { System.Console.WriteLine(""C1.get_P3""); return 0; } } static void Main() { I1 x = new C1(); _ = x.P1; _ = x.P2; _ = x.P3; } } "; foreach (var parseOptions in new[] { TestOptions.Regular8, TestOptions.Regular9, TestOptions.Regular }) { var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"C1.get_P1 C1.get_P2 C1.get_P3 ", verify: VerifyOnMonoOrCoreClr); var c1 = compilation1.GetTypeByMetadataName("C1"); foreach (var p in c1.GetMembers().OfType<PropertySymbol>()) { Assert.True(p.GetMethod.IsMetadataVirtual()); Assert.True(p.GetMethod.IsMetadataFinal); } } } [Fact, WorkItem(53565, "https://github.com/dotnet/roslyn/issues/53565")] public void PartialPropertyImplementation_02() { var source1 = @" interface I1 { internal int P1 {get; set;} internal int P2 {get => throw null; set{}} } class C0 : I1 { int I1.P1 {get; set;} } class C1 : C0, I1 { public int P1 { get { System.Console.WriteLine(""C1.get_P1""); return 0; } } public int P2 { get { System.Console.WriteLine(""C1.get_P2""); return 0; } } static void Main() { I1 x = new C1(); _ = x.P1; _ = x.P2; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : @"C1.get_P1 C1.get_P2 ", verify: VerifyOnMonoOrCoreClr); var c1 = compilation1.GetTypeByMetadataName("C1"); foreach (var p in c1.GetMembers().OfType<PropertySymbol>()) { Assert.True(p.GetMethod.IsMetadataVirtual()); Assert.True(p.GetMethod.IsMetadataFinal); } } } }
1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/CSharp/Test/Symbol/Symbols/MissingSpecialMember.cs
// 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. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MissingSpecialMember : CSharpTestBase { [Fact] public void Missing_System_Collections_Generic_IEnumerable_T__GetEnumerator() { var source = @"using System.Collections.Generic; public class Program { public static void Main(string[] args) { } public IEnumerable<int> M() { yield return 0; yield return 1; } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(SpecialMember.System_Collections_Generic_IEnumerable_T__GetEnumerator); comp.VerifyEmitDiagnostics( // (10,5): error CS0656: Missing compiler required member 'System.Collections.Generic.IEnumerable`1.GetEnumerator' // { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"{ yield return 0; yield return 1; }").WithArguments("System.Collections.Generic.IEnumerable`1", "GetEnumerator").WithLocation(10, 5) ); } [Fact] public void Missing_System_IDisposable__Dispose() { var source = @"using System.Collections.Generic; public class Program { public static void Main(string[] args) { } public IEnumerable<int> M() { yield return 0; yield return 1; } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(SpecialMember.System_IDisposable__Dispose); comp.VerifyEmitDiagnostics( // (10,5): error CS0656: Missing compiler required member 'System.IDisposable.Dispose' // { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"{ yield return 0; yield return 1; }").WithArguments("System.IDisposable", "Dispose").WithLocation(10, 5) ); } [Fact] public void Missing_System_Diagnostics_DebuggerHiddenAttribute__ctor() { var source = @"using System.Collections.Generic; public class Program { public static void Main(string[] args) { } public IEnumerable<int> M() { yield return 0; yield return 1; } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor); comp.VerifyEmitDiagnostics( // the DebuggerHidden attribute is optional. ); } [Fact] public void Missing_System_Runtime_CompilerServices_ExtensionAttribute__ctor() { var source = @"using System.Collections.Generic; public static class Program { public static void Main(string[] args) { } public static void Extension(this string x) {} }"; var comp = CreateEmptyCompilation(source, new[] { Net40.mscorlib }, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor); comp.VerifyEmitDiagnostics( // (9,34): error CS1110: Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll? // public static void Extension(this string x) {} Diagnostic(ErrorCode.ERR_ExtensionAttrNotFound, "this").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(9, 34) ); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicSpecialType() { var source = @" namespace System { public class Object { public Object() { } } internal class String : Object { } public class ValueType { } public struct Void { } } "; Action<CSharpCompilation> validate = comp => { var specialType = comp.GetSpecialType(SpecialType.System_String); Assert.Equal(TypeKind.Error, specialType.TypeKind); Assert.Equal(SpecialType.System_String, specialType.SpecialType); Assert.Equal(Accessibility.NotApplicable, specialType.DeclaredAccessibility); var lookupType = comp.GetTypeByMetadataName("System.String"); Assert.Equal(TypeKind.Class, lookupType.TypeKind); Assert.Equal(SpecialType.None, lookupType.SpecialType); Assert.Equal(Accessibility.Internal, lookupType.DeclaredAccessibility); }; ValidateSourceAndMetadata(source, validate); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicSpecialTypeMember() { var sourceTemplate = @" namespace System {{ public class Object {{ public Object() {{ }} {0} virtual String ToString() {{ return null; }} }} {0} class String : Object {{ public static String Concat(String s1, String s2) {{ return null; }} }} public class ValueType {{ }} public struct Void {{ }} }} "; Action<CSharpCompilation> validatePresent = comp => { Assert.NotNull(comp.GetSpecialTypeMember(SpecialMember.System_Object__ToString)); Assert.NotNull(comp.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString)); comp.GetDiagnostics(); }; Action<CSharpCompilation> validateMissing = comp => { Assert.Null(comp.GetSpecialTypeMember(SpecialMember.System_Object__ToString)); Assert.Null(comp.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString)); comp.GetDiagnostics(); }; ValidateSourceAndMetadata(string.Format(sourceTemplate, "public"), validatePresent); ValidateSourceAndMetadata(string.Format(sourceTemplate, "internal"), validateMissing); } // Document the fact that we don't reject type parameters with constraints (yet?). [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void GenericConstraintsOnSpecialType() { var source = @" namespace System { public class Object { public Object() { } } public struct Nullable<T> where T : new() { } public class ValueType { } public struct Void { } } "; Action<CSharpCompilation> validate = comp => { var specialType = comp.GetSpecialType(SpecialType.System_Nullable_T); Assert.Equal(TypeKind.Struct, specialType.TypeKind); Assert.Equal(SpecialType.System_Nullable_T, specialType.SpecialType); var lookupType = comp.GetTypeByMetadataName("System.Nullable`1"); Assert.Equal(TypeKind.Struct, lookupType.TypeKind); Assert.Equal(SpecialType.System_Nullable_T, lookupType.SpecialType); }; ValidateSourceAndMetadata(source, validate); } // No special type members have type parameters that could (incorrectly) be constrained. [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicWellKnownType() { var source = @" namespace System { public class Object { public Object() { } } internal class Type : Object { } public class ValueType { } public struct Void { } } "; var comp = CreateEmptyCompilation(source); var wellKnownType = comp.GetWellKnownType(WellKnownType.System_Type); Assert.Equal(TypeKind.Class, wellKnownType.TypeKind); Assert.Equal(Accessibility.Internal, wellKnownType.DeclaredAccessibility); var lookupType = comp.GetTypeByMetadataName("System.Type"); Assert.Equal(TypeKind.Class, lookupType.TypeKind); Assert.Equal(Accessibility.Internal, lookupType.DeclaredAccessibility); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicWellKnownType_Nested() { var sourceTemplate = @" namespace System.Diagnostics {{ {0} class DebuggableAttribute {{ {1} enum DebuggingModes {{ }} }} }} namespace System {{ public class Object {{ }} public class ValueType {{ }} public class Enum : ValueType {{ }} public struct Void {{ }} public struct Int32 {{ }} }} "; Action<CSharpCompilation> validate = comp => { var wellKnownType = comp.GetWellKnownType(WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes); Assert.Equal(TypeKind.Error, wellKnownType.TypeKind); Assert.Equal(Accessibility.NotApplicable, wellKnownType.DeclaredAccessibility); var lookupType = comp.GetTypeByMetadataName("System.Diagnostics.DebuggableAttribute+DebuggingModes"); Assert.Equal(TypeKind.Enum, lookupType.TypeKind); Assert.NotEqual(Accessibility.NotApplicable, lookupType.DeclaredAccessibility); }; ValidateSourceAndMetadata(string.Format(sourceTemplate, "public", "protected"), validate); ValidateSourceAndMetadata(string.Format(sourceTemplate, "public", "private"), validate); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicWellKnownTypeMember() { var sourceTemplate = @" namespace System {{ public class Object {{ public Object() {{ }} }} {0} class Type : Object {{ public static readonly Object Missing = new Object(); }} public static class Math : Object {{ {0} static Double Round(Double d) {{ return d; }} }} public class ValueType {{ }} public struct Void {{ }} public struct Double {{ }} }} "; Action<CSharpCompilation> validatePresent = comp => { Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Type__Missing)); Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Math__RoundDouble)); comp.GetDiagnostics(); }; validatePresent(CreateEmptyCompilation(string.Format(sourceTemplate, "public"))); validatePresent(CreateEmptyCompilation(string.Format(sourceTemplate, "internal"))); } // Document the fact that we don't reject type parameters with constraints (yet?). [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void GenericConstraintsOnWellKnownType() { var source = @" namespace System { public class Object { public Object() { } } namespace Threading.Tasks { public class Task<T> where T : new() { } } public class ValueType { } public struct Void { } } "; Action<CSharpCompilation> validate = comp => { var wellKnownType = comp.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T); Assert.Equal(TypeKind.Class, wellKnownType.TypeKind); var lookupType = comp.GetTypeByMetadataName("System.Threading.Tasks.Task`1"); Assert.Equal(TypeKind.Class, lookupType.TypeKind); }; ValidateSourceAndMetadata(source, validate); } // Document the fact that we don't reject type parameters with constraints (yet?). [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void GenericConstraintsOnWellKnownTypeMember() { var sourceTemplate = @" namespace System {{ public class Object {{ public Object() {{ }} }} namespace Threading {{ public static class Interlocked {{ public static T CompareExchange<T>(ref T t1, T t2, T t3){0} {{ return t1; }} }} }} public class ValueType {{ }} public struct Void {{ }} }} "; Action<CSharpCompilation> validate = comp => { Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T)); comp.GetDiagnostics(); }; ValidateSourceAndMetadata(string.Format(sourceTemplate, ""), validate); ValidateSourceAndMetadata(string.Format(sourceTemplate, " where T : new()"), validate); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void PublicVersusInternalWellKnownType() { var corlibSource = @" namespace System { public class Object { public Object() { } } public class String { } public class Attribute { } public class ValueType { } public struct Void { } } namespace System.Runtime.CompilerServices { public class InternalsVisibleToAttribute : Attribute { public InternalsVisibleToAttribute(String s) { } } } "; var libSourceTemplate = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Test"")] namespace System {{ {0} class Type {{ }} }} "; var corlibRef = CreateEmptyCompilation(corlibSource).EmitToImageReference(expectedWarnings: new[] { // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) }); var publicLibRef = CreateEmptyCompilation(string.Format(libSourceTemplate, "public"), new[] { corlibRef }).EmitToImageReference(); var internalLibRef = CreateEmptyCompilation(string.Format(libSourceTemplate, "internal"), new[] { corlibRef }).EmitToImageReference(); var comp = CreateEmptyCompilation("", new[] { corlibRef, publicLibRef, internalLibRef }, assemblyName: "Test"); var wellKnown = comp.GetWellKnownType(WellKnownType.System_Type); Assert.NotNull(wellKnown); Assert.Equal(TypeKind.Class, wellKnown.TypeKind); Assert.Equal(Accessibility.Public, wellKnown.DeclaredAccessibility); var lookup = comp.GetTypeByMetadataName("System.Type"); Assert.Null(lookup); // Ambiguous } private static void ValidateSourceAndMetadata(string source, Action<CSharpCompilation> validate) { var comp1 = CreateEmptyCompilation(source); validate(comp1); var reference = comp1.EmitToImageReference(expectedWarnings: new[] { // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) }); var comp2 = CreateEmptyCompilation("", new[] { reference }); validate(comp2); } [Fact] [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] public void AllSpecialTypes() { var comp = CreateEmptyCompilation("", new[] { MscorlibRef_v4_0_30316_17626 }); for (var special = SpecialType.None + 1; special <= SpecialType.Count; special++) { var symbol = comp.GetSpecialType(special); Assert.NotNull(symbol); if (special == SpecialType.System_Runtime_CompilerServices_RuntimeFeature || special == SpecialType.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute) { Assert.Equal(SymbolKind.ErrorType, symbol.Kind); // Not available } else { Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind); } } } [Fact] [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] public void AllSpecialTypeMembers() { var comp = CreateEmptyCompilation("", new[] { MscorlibRef_v4_0_30316_17626 }); foreach (SpecialMember special in Enum.GetValues(typeof(SpecialMember))) { if (special == SpecialMember.Count) continue; // Not a real value; var symbol = comp.GetSpecialTypeMember(special); if (special == SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces || special == SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses || special == SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention || special == SpecialMember.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor) { Assert.Null(symbol); // Not available } else { Assert.NotNull(symbol); } } } [Fact] [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] public void AllWellKnownTypes() { var refs = new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929, CSharpRef, SystemXmlRef, SystemXmlLinqRef, SystemWindowsFormsRef, ValueTupleRef }.Concat(WinRtRefs).ToArray(); var comp = CreateEmptyCompilation("", refs); for (var wkt = WellKnownType.First; wkt < WellKnownType.NextAvailable; wkt++) { switch (wkt) { case WellKnownType.Microsoft_VisualBasic_Embedded: case WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators: // Not applicable in C#. continue; case WellKnownType.System_FormattableString: case WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory: case WellKnownType.System_Runtime_CompilerServices_NullableAttribute: case WellKnownType.System_Runtime_CompilerServices_NullableContextAttribute: case WellKnownType.System_Runtime_CompilerServices_NullablePublicOnlyAttribute: case WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute: case WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute: case WellKnownType.System_Span_T: case WellKnownType.System_ReadOnlySpan_T: case WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute: case WellKnownType.System_Index: case WellKnownType.System_Range: case WellKnownType.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute: case WellKnownType.System_IAsyncDisposable: case WellKnownType.System_Collections_Generic_IAsyncEnumerable_T: case WellKnownType.System_Collections_Generic_IAsyncEnumerator_T: case WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T: case WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus: case WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags: case WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T: case WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource: case WellKnownType.System_Threading_Tasks_ValueTask_T: case WellKnownType.System_Threading_Tasks_ValueTask: case WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder: case WellKnownType.System_Threading_CancellationToken: case WellKnownType.System_Runtime_CompilerServices_SwitchExpressionException: case WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute: case WellKnownType.System_Runtime_CompilerServices_IsExternalInit: case WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler: // Not yet in the platform. continue; case WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation: case WellKnownType.System_Runtime_CompilerServices_ITuple: case WellKnownType.System_Runtime_CompilerServices_NonNullTypesAttribute: case WellKnownType.Microsoft_CodeAnalysis_EmbeddedAttribute: // Not always available. continue; case WellKnownType.ExtSentinel: // Not a real type continue; } switch (wkt) { case WellKnownType.System_ValueTuple: case WellKnownType.System_ValueTuple_T1: case WellKnownType.System_ValueTuple_T2: case WellKnownType.System_ValueTuple_T3: case WellKnownType.System_ValueTuple_T4: case WellKnownType.System_ValueTuple_T5: case WellKnownType.System_ValueTuple_T6: case WellKnownType.System_ValueTuple_T7: case WellKnownType.System_ValueTuple_TRest: Assert.True(wkt.IsValueTupleType()); break; default: Assert.False(wkt.IsValueTupleType()); break; } var symbol = comp.GetWellKnownType(wkt); Assert.NotNull(symbol); Assert.True(symbol.Kind != SymbolKind.ErrorType, $"{wkt} should not be an error type"); } } [Fact] public void AllWellKnownTypesBeforeCSharp7() { foreach (var type in new[] { WellKnownType.System_Math, WellKnownType.System_Array, WellKnownType.System_Attribute, WellKnownType.System_CLSCompliantAttribute, WellKnownType.System_Convert, WellKnownType.System_Exception, WellKnownType.System_FlagsAttribute, WellKnownType.System_FormattableString, WellKnownType.System_Guid, WellKnownType.System_IFormattable, WellKnownType.System_RuntimeTypeHandle, WellKnownType.System_RuntimeFieldHandle, WellKnownType.System_RuntimeMethodHandle, WellKnownType.System_MarshalByRefObject, WellKnownType.System_Type, WellKnownType.System_Reflection_AssemblyKeyFileAttribute, WellKnownType.System_Reflection_AssemblyKeyNameAttribute, WellKnownType.System_Reflection_MethodInfo, WellKnownType.System_Reflection_ConstructorInfo, WellKnownType.System_Reflection_MethodBase, WellKnownType.System_Reflection_FieldInfo, WellKnownType.System_Reflection_MemberInfo, WellKnownType.System_Reflection_Missing, WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory, WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, WellKnownType.System_Runtime_InteropServices_StructLayoutAttribute, WellKnownType.System_Runtime_InteropServices_UnknownWrapper, WellKnownType.System_Runtime_InteropServices_DispatchWrapper, WellKnownType.System_Runtime_InteropServices_CallingConvention, WellKnownType.System_Runtime_InteropServices_ClassInterfaceAttribute, WellKnownType.System_Runtime_InteropServices_ClassInterfaceType, WellKnownType.System_Runtime_InteropServices_CoClassAttribute, WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, WellKnownType.System_Runtime_InteropServices_ComEventInterfaceAttribute, WellKnownType.System_Runtime_InteropServices_ComInterfaceType, WellKnownType.System_Runtime_InteropServices_ComSourceInterfacesAttribute, WellKnownType.System_Runtime_InteropServices_ComVisibleAttribute, WellKnownType.System_Runtime_InteropServices_DispIdAttribute, WellKnownType.System_Runtime_InteropServices_GuidAttribute, WellKnownType.System_Runtime_InteropServices_InterfaceTypeAttribute, WellKnownType.System_Runtime_InteropServices_Marshal, WellKnownType.System_Runtime_InteropServices_TypeIdentifierAttribute, WellKnownType.System_Runtime_InteropServices_BestFitMappingAttribute, WellKnownType.System_Runtime_InteropServices_DefaultParameterValueAttribute, WellKnownType.System_Runtime_InteropServices_LCIDConversionAttribute, WellKnownType.System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute, WellKnownType.System_Activator, WellKnownType.System_Threading_Tasks_Task, WellKnownType.System_Threading_Tasks_Task_T, WellKnownType.System_Threading_Interlocked, WellKnownType.System_Threading_Monitor, WellKnownType.System_Threading_Thread, WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfoFlags, WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, WellKnownType.Microsoft_VisualBasic_CallType, WellKnownType.Microsoft_VisualBasic_Embedded, WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators, WellKnownType.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute, WellKnownType.Microsoft_VisualBasic_CompilerServices_Utils, WellKnownType.Microsoft_VisualBasic_CompilerServices_LikeOperator, WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl, WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl, WellKnownType.Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag, WellKnownType.Microsoft_VisualBasic_CompilerServices_StringType, WellKnownType.Microsoft_VisualBasic_CompilerServices_IncompleteInitialization, WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, WellKnownType.Microsoft_VisualBasic_CompareMethod, WellKnownType.Microsoft_VisualBasic_Strings, WellKnownType.Microsoft_VisualBasic_ErrObject, WellKnownType.Microsoft_VisualBasic_FileSystem, WellKnownType.Microsoft_VisualBasic_ApplicationServices_ApplicationBase, WellKnownType.Microsoft_VisualBasic_ApplicationServices_WindowsFormsApplicationBase, WellKnownType.Microsoft_VisualBasic_Information, WellKnownType.Microsoft_VisualBasic_Interaction, WellKnownType.System_Func_T, WellKnownType.System_Func_T2, WellKnownType.System_Func_T3, WellKnownType.System_Func_T4, WellKnownType.System_Func_T5, WellKnownType.System_Func_T6, WellKnownType.System_Func_T7, WellKnownType.System_Func_T8, WellKnownType.System_Func_T9, WellKnownType.System_Func_T10, WellKnownType.System_Func_T11, WellKnownType.System_Func_T12, WellKnownType.System_Func_T13, WellKnownType.System_Func_T14, WellKnownType.System_Func_T15, WellKnownType.System_Func_T16, WellKnownType.System_Func_T17, WellKnownType.System_Action, WellKnownType.System_Action_T, WellKnownType.System_Action_T2, WellKnownType.System_Action_T3, WellKnownType.System_Action_T4, WellKnownType.System_Action_T5, WellKnownType.System_Action_T6, WellKnownType.System_Action_T7, WellKnownType.System_Action_T8, WellKnownType.System_Action_T9, WellKnownType.System_Action_T10, WellKnownType.System_Action_T11, WellKnownType.System_Action_T12, WellKnownType.System_Action_T13, WellKnownType.System_Action_T14, WellKnownType.System_Action_T15, WellKnownType.System_Action_T16, WellKnownType.System_AttributeUsageAttribute, WellKnownType.System_ParamArrayAttribute, WellKnownType.System_NonSerializedAttribute, WellKnownType.System_STAThreadAttribute, WellKnownType.System_Reflection_DefaultMemberAttribute, WellKnownType.System_Runtime_CompilerServices_DateTimeConstantAttribute, WellKnownType.System_Runtime_CompilerServices_DecimalConstantAttribute, WellKnownType.System_Runtime_CompilerServices_IUnknownConstantAttribute, WellKnownType.System_Runtime_CompilerServices_IDispatchConstantAttribute, WellKnownType.System_Runtime_CompilerServices_ExtensionAttribute, WellKnownType.System_Runtime_CompilerServices_INotifyCompletion, WellKnownType.System_Runtime_CompilerServices_InternalsVisibleToAttribute, WellKnownType.System_Runtime_CompilerServices_CompilerGeneratedAttribute, WellKnownType.System_Runtime_CompilerServices_AccessedThroughPropertyAttribute, WellKnownType.System_Runtime_CompilerServices_CompilationRelaxationsAttribute, WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute, WellKnownType.System_Runtime_CompilerServices_UnsafeValueTypeAttribute, WellKnownType.System_Runtime_CompilerServices_FixedBufferAttribute, WellKnownType.System_Runtime_CompilerServices_DynamicAttribute, WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, WellKnownType.System_Runtime_CompilerServices_CallSite, WellKnownType.System_Runtime_CompilerServices_CallSite_T, WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, WellKnownType.Windows_Foundation_IAsyncAction, WellKnownType.Windows_Foundation_IAsyncActionWithProgress_T, WellKnownType.Windows_Foundation_IAsyncOperation_T, WellKnownType.Windows_Foundation_IAsyncOperationWithProgress_T2, WellKnownType.System_Diagnostics_Debugger, WellKnownType.System_Diagnostics_DebuggerDisplayAttribute, WellKnownType.System_Diagnostics_DebuggerNonUserCodeAttribute, WellKnownType.System_Diagnostics_DebuggerHiddenAttribute, WellKnownType.System_Diagnostics_DebuggerBrowsableAttribute, WellKnownType.System_Diagnostics_DebuggerStepThroughAttribute, WellKnownType.System_Diagnostics_DebuggerBrowsableState, WellKnownType.System_Diagnostics_DebuggableAttribute, WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, WellKnownType.System_ComponentModel_DesignerSerializationVisibilityAttribute, WellKnownType.System_IEquatable_T, WellKnownType.System_Collections_IList, WellKnownType.System_Collections_ICollection, WellKnownType.System_Collections_Generic_EqualityComparer_T, WellKnownType.System_Collections_Generic_List_T, WellKnownType.System_Collections_Generic_IDictionary_KV, WellKnownType.System_Collections_Generic_IReadOnlyDictionary_KV, WellKnownType.System_Collections_ObjectModel_Collection_T, WellKnownType.System_Collections_ObjectModel_ReadOnlyCollection_T, WellKnownType.System_Collections_Specialized_INotifyCollectionChanged, WellKnownType.System_ComponentModel_INotifyPropertyChanged, WellKnownType.System_ComponentModel_EditorBrowsableAttribute, WellKnownType.System_ComponentModel_EditorBrowsableState, WellKnownType.System_Linq_Enumerable, WellKnownType.System_Linq_Expressions_Expression, WellKnownType.System_Linq_Expressions_Expression_T, WellKnownType.System_Linq_Expressions_ParameterExpression, WellKnownType.System_Linq_Expressions_ElementInit, WellKnownType.System_Linq_Expressions_MemberBinding, WellKnownType.System_Linq_Expressions_ExpressionType, WellKnownType.System_Linq_IQueryable, WellKnownType.System_Linq_IQueryable_T, WellKnownType.System_Xml_Linq_Extensions, WellKnownType.System_Xml_Linq_XAttribute, WellKnownType.System_Xml_Linq_XCData, WellKnownType.System_Xml_Linq_XComment, WellKnownType.System_Xml_Linq_XContainer, WellKnownType.System_Xml_Linq_XDeclaration, WellKnownType.System_Xml_Linq_XDocument, WellKnownType.System_Xml_Linq_XElement, WellKnownType.System_Xml_Linq_XName, WellKnownType.System_Xml_Linq_XNamespace, WellKnownType.System_Xml_Linq_XObject, WellKnownType.System_Xml_Linq_XProcessingInstruction, WellKnownType.System_Security_UnverifiableCodeAttribute, WellKnownType.System_Security_Permissions_SecurityAction, WellKnownType.System_Security_Permissions_SecurityAttribute, WellKnownType.System_Security_Permissions_SecurityPermissionAttribute, WellKnownType.System_NotSupportedException, WellKnownType.System_Runtime_CompilerServices_ICriticalNotifyCompletion, WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, WellKnownType.System_Runtime_CompilerServices_AsyncStateMachineAttribute, WellKnownType.System_Runtime_CompilerServices_IteratorStateMachineAttribute, WellKnownType.System_Windows_Forms_Form, WellKnownType.System_Windows_Forms_Application, WellKnownType.System_Environment, WellKnownType.System_Runtime_GCLatencyMode, WellKnownType.System_IFormatProvider } ) { Assert.True(type <= WellKnownType.CSharp7Sentinel); } // There were 204 well-known types prior to CSharp7 Assert.Equal(204, (int)(WellKnownType.CSharp7Sentinel - WellKnownType.First)); } [Fact] [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] public void AllWellKnownTypeMembers() { var refs = new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929, CSharpDesktopRef, SystemXmlRef, SystemXmlLinqRef, SystemWindowsFormsRef, ValueTupleRef }.Concat(WinRtRefs).ToArray(); var comp = CreateEmptyCompilation("", refs); foreach (WellKnownMember wkm in Enum.GetValues(typeof(WellKnownMember))) { switch (wkm) { case WellKnownMember.Count: // Not a real value; continue; case WellKnownMember.Microsoft_VisualBasic_Embedded__ctor: case WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean: // C# can't embed VB core. continue; case WellKnownMember.System_Array__Empty: case WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte: case WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags: case WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor: case WellKnownMember.System_Span_T__ctor: case WellKnownMember.System_Span_T__get_Item: case WellKnownMember.System_Span_T__get_Length: case WellKnownMember.System_ReadOnlySpan_T__ctor: case WellKnownMember.System_ReadOnlySpan_T__get_Item: case WellKnownMember.System_ReadOnlySpan_T__get_Length: case WellKnownMember.System_Index__ctor: case WellKnownMember.System_Index__GetOffset: case WellKnownMember.System_Range__ctor: case WellKnownMember.System_Range__StartAt: case WellKnownMember.System_Range__EndAt: case WellKnownMember.System_Range__get_All: case WellKnownMember.System_Range__get_Start: case WellKnownMember.System_Range__get_End: case WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor: case WellKnownMember.System_IAsyncDisposable__DisposeAsync: case WellKnownMember.System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator: case WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync: case WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__get_Current: case WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version: case WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult: case WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus: case WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted: case WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset: case WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult: case WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException: case WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult: case WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus: case WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted: case WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__GetResult: case WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__GetStatus: case WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted: case WellKnownMember.System_Threading_Tasks_ValueTask_T__ctorSourceAndToken: case WellKnownMember.System_Threading_Tasks_ValueTask_T__ctorValue: case WellKnownMember.System_Threading_Tasks_ValueTask__ctor: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T: case WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctor: case WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctorObject: case WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags: case WellKnownMember.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear: // Not yet in the platform. continue; case WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile: case WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles: case WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Item: case WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Length: // Not always available. continue; } if (wkm == WellKnownMember.Count) continue; // Not a real value. var symbol = comp.GetWellKnownTypeMember(wkm); Assert.True((object)symbol != null, $"Unexpected null for {wkm}"); } } [Fact, WorkItem(377890, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=377890")] public void System_IntPtr__op_Explicit_FromInt32() { string source = @" using System; public class MyClass { static void Main() { ((IntPtr)0).GetHashCode(); } } "; var comp = CreateCompilation(source); comp.MakeMemberMissing(SpecialMember.System_IntPtr__op_Explicit_FromInt32); comp.VerifyEmitDiagnostics( // (8,10): error CS0656: Missing compiler required member 'System.IntPtr.op_Explicit' // ((IntPtr)0).GetHashCode(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr)0").WithArguments("System.IntPtr", "op_Explicit").WithLocation(8, 10) ); } [Fact] public void System_Delegate__Combine() { var source = @" using System; using System.Threading.Tasks; namespace RoslynAsyncDelegate { class Program { static EventHandler MyEvent; static void Main(string[] args) { MyEvent += async delegate { await Task.Delay(0); }; } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); compilation.MakeMemberMissing(SpecialMember.System_Delegate__Combine); compilation.VerifyEmitDiagnostics( // (13,12): error CS0656: Missing compiler required member 'System.Delegate.Combine' // MyEvent += async delegate { await Task.Delay(0); }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "MyEvent += async delegate { await Task.Delay(0); }").WithArguments("System.Delegate", "Combine").WithLocation(13, 12) ); } [Fact] public void System_Nullable_T__ctor_01() { string source = @" using System; public struct S { public static implicit operator int(S n) // 1 native compiler { Console.WriteLine(1); return 0; } public static implicit operator int?(S n) // 2 Roslyn compiler { Console.WriteLine(2); return null; } public static void Main() { int? qa = 5; S b = default(S); var sum = qa + b; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (20,19): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // int? qa = 5; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "5").WithArguments("System.Nullable`1", ".ctor").WithLocation(20, 19), // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", ".ctor").WithLocation(22, 19) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_01() { string source = @" using System; public struct S { public static implicit operator int(S n) // 1 native compiler { Console.WriteLine(1); return 0; } public static implicit operator int?(S n) // 2 Roslyn compiler { Console.WriteLine(2); return null; } public static void Main() { int? qa = 5; S b = default(S); var sum = qa + b; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(22, 19), // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(22, 19) ); } [Fact] public void System_Nullable_T_get_HasValue_01() { string source = @" using System; public struct S { public static implicit operator int(S n) // 1 native compiler { Console.WriteLine(1); return 0; } public static implicit operator int?(S n) // 2 Roslyn compiler { Console.WriteLine(2); return null; } public static void Main() { int? qa = 5; S b = default(S); var sum = qa + b; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_get_HasValue); compilation.VerifyEmitDiagnostics( // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(22, 19), // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(22, 19) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_02() { string source = @" using System; namespace Test { static class Program { static void Main() { int? i = 123; C c = (C)i; } } public class C { public readonly int v; public C(int v) { this.v = v; } public static implicit operator C(int v) { Console.Write(v); return new C(v); } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (10,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // C c = (C)i; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(C)i").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(10, 19) ); } [Fact] public void System_Nullable_T_get_Value() { var source = @" using System; class C { static void Test() { byte? b = 0; IntPtr p = (IntPtr)b; Console.WriteLine(p); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_get_Value); compilation.VerifyEmitDiagnostics( // (9,28): error CS0656: Missing compiler required member 'System.Nullable`1.get_Value' // IntPtr p = (IntPtr)b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "b").WithArguments("System.Nullable`1", "get_Value").WithLocation(9, 28) ); } [Fact] public void System_Nullable_T__ctor_02() { var source = @" using System; class C { static void Main() { Console.WriteLine((IntPtr?)M_int()); Console.WriteLine((IntPtr?)M_int(42)); Console.WriteLine((IntPtr?)M_long()); Console.WriteLine((IntPtr?)M_long(300)); } static int? M_int(int? p = null) { return p; } static long? M_long(long? p = null) { return p; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (8,27): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_int()); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr?)M_int()").WithArguments("System.Nullable`1", ".ctor").WithLocation(8, 27), // (9,42): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_int(42)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "42").WithArguments("System.Nullable`1", ".ctor").WithLocation(9, 42), // (9,27): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_int(42)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr?)M_int(42)").WithArguments("System.Nullable`1", ".ctor").WithLocation(9, 27), // (10,27): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_long()); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr?)M_long()").WithArguments("System.Nullable`1", ".ctor").WithLocation(10, 27), // (11,43): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_long(300)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "300").WithArguments("System.Nullable`1", ".ctor").WithLocation(11, 43), // (11,27): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_long(300)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr?)M_long(300)").WithArguments("System.Nullable`1", ".ctor").WithLocation(11, 27) ); } [Fact] public void System_Nullable_T__ctor_03() { var source = @" using System; class Class1 { static void Main() { MyClass b = (int?)1; } } class MyClass { public static implicit operator MyClass(decimal Value) { return new MyClass(); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (9,21): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // MyClass b = (int?)1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(int?)1").WithArguments("System.Nullable`1", ".ctor").WithLocation(9, 21) ); } [Fact] public void System_Nullable_T__ctor_04() { var source1 = @" using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public static class Test { public static void Generic<T>([Optional][DecimalConstant(0, 0, 0, 0, 50)] T x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void Decimal([Optional][DecimalConstant(0, 0, 0, 0, 50)] Decimal x) { Console.WriteLine(x.ToString()); } public static void NullableDecimal([Optional][DecimalConstant(0, 0, 0, 0, 50)] Decimal? x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void Object([Optional][DecimalConstant(0, 0, 0, 0, 50)] object x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void String([Optional][DecimalConstant(0, 0, 0, 0, 50)] string x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void Int32([Optional][DecimalConstant(0, 0, 0, 0, 50)] int x) { Console.WriteLine(x.ToString()); } public static void IComparable([Optional][DecimalConstant(0, 0, 0, 0, 50)] IComparable x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void ValueType([Optional][DecimalConstant(0, 0, 0, 0, 50)] ValueType x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } } "; var source2 = @" class Program { public static void Main() { // Respects default value Test.Generic<decimal>(); Test.Generic<decimal?>(); Test.Generic<object>(); Test.Decimal(); Test.NullableDecimal(); Test.Object(); Test.IComparable(); Test.ValueType(); Test.Int32(); // Null, since not convertible Test.Generic<string>(); Test.String(); } } "; var compilation = CreateCompilationWithMscorlib45(source1 + source2); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (55,9): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Test.Generic<decimal?>(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "Test.Generic<decimal?>()").WithArguments("System.Nullable`1", ".ctor").WithLocation(55, 9), // (58,9): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Test.NullableDecimal(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "Test.NullableDecimal()").WithArguments("System.Nullable`1", ".ctor").WithLocation(58, 9) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_04() { var source = @" using System; class Class1 { static void Main() { int? a = 1; a.ToString(); MyClass b = a; b.ToString(); } } class MyClass { public static implicit operator MyClass(decimal Value) { return new MyClass(); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (11,21): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // MyClass b = a; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "a").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(11, 21), // (11,21): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // MyClass b = a; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "a").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(11, 21) ); } [Fact] public void System_Nullable_T_get_HasValue_02() { var source = @" using System; class Class1 { static void Main() { int? a = 1; a.ToString(); MyClass b = a; b.ToString(); } } class MyClass { public static implicit operator MyClass(decimal Value) { Console.WriteLine(""Value is: "" + Value); return new MyClass(); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_get_HasValue); compilation.VerifyEmitDiagnostics( // (11,21): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // MyClass b = a; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "a").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(11, 21) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_03() { string source = @"using System; namespace Test { static class Program { static void Main() { S.v = 0; S? S2 = 123; // not lifted, int=>int?, int?=>S, S=>S? Console.WriteLine(S.v == 123); } } public struct S { public static int v; // s == null, return v = -1 public static implicit operator S(int? s) { Console.Write(""Imp S::int? -> S ""); S ss = new S(); S.v = s ?? -1; return ss; } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (23,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // S.v = s ?? -1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "s").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(23, 19) ); } [Fact] public void System_String__ConcatObjectObject() { var source = @" using System; using System.Linq.Expressions; class Class1 { static void Main() { Expression<Func<object, string>> e = x => ""X = "" + x; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatObjectObject); compilation.VerifyEmitDiagnostics( // (9,51): error CS0656: Missing compiler required member 'System.String.Concat' // Expression<Func<object, string>> e = x => "X = " + x; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"""X = "" + x").WithArguments("System.String", "Concat").WithLocation(9, 51) ); } [Fact] public void System_String__ConcatStringStringString() { string source = @" using System; struct S { private string str; public S(char chr) { this.str = chr.ToString(); } public S(string str) { this.str = str; } public static S operator + (S x, S y) { return new S(x.str + '+' + y.str); } } class C { static void Main() { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatStringStringString); compilation.VerifyEmitDiagnostics( // (8,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator + (S x, S y) { return new S(x.str + '+' + y.str); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x.str + '+' + y.str").WithArguments("System.String", "Concat").WithLocation(8, 58) ); } [Fact] public void System_String__ConcatStringStringStringString() { string source = @" using System; struct S { private string str; public S(char chr) { this.str = chr.ToString(); } public S(string str) { this.str = str; } public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); } } class C { static void Main() { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatStringStringStringString); compilation.VerifyEmitDiagnostics( // (8,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '+' + y.str").WithArguments("System.String", "Concat").WithLocation(8, 58) ); } [Fact] public void System_String__ConcatStringArray() { string source = @" using System; struct S { private string str; public S(char chr) { this.str = chr.ToString(); } public S(string str) { this.str = str; } public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); } public static S operator - (S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); } public static S operator % (S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); } public static S operator / (S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); } public static S operator * (S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); } public static S operator & (S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); } public static S operator | (S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); } public static S operator ^ (S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); } public static S operator << (S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); } public static S operator >> (S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); } public static S operator >= (S x, S y) { return new S('(' + x.str + '>' + '=' + y.str + ')'); } public static S operator <= (S x, S y) { return new S('(' + x.str + '<' + '=' + y.str + ')'); } public static S operator > (S x, S y) { return new S('(' + x.str + '>' + y.str + ')'); } public static S operator < (S x, S y) { return new S('(' + x.str + '<' + y.str + ')'); } public override string ToString() { return this.str; } } class C { static void Main() { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatStringArray); compilation.VerifyEmitDiagnostics( // (8,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '+' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(8, 58), // (9,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator - (S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '-' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(9, 58), // (10,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator % (S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '%' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(10, 58), // (11,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator / (S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '/' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(11, 58), // (12,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator * (S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '*' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(12, 58), // (13,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator & (S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '&' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(13, 58), // (14,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator | (S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '|' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(14, 58), // (15,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator ^ (S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '^' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(15, 58), // (16,61): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator << (S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '<' + '<' + y.ToString() + ')'").WithArguments("System.String", "Concat").WithLocation(16, 61), // (17,61): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator >> (S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '>' + '>' + y.ToString() + ')'").WithArguments("System.String", "Concat").WithLocation(17, 61), // (18,59): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator >= (S x, S y) { return new S('(' + x.str + '>' + '=' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '>' + '=' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(18, 59), // (19,59): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator <= (S x, S y) { return new S('(' + x.str + '<' + '=' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '<' + '=' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(19, 59), // (20,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator > (S x, S y) { return new S('(' + x.str + '>' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '>' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(20, 58), // (21,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator < (S x, S y) { return new S('(' + x.str + '<' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '<' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(21, 58) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_05() { string source = @" struct S { public static int operator +(S s) { return 1; } public static void Main() { S s = new S(); S? sq = s; var j = +sq; System.Console.WriteLine(j); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (9,17): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // var j = +sq; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "+sq").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(9, 17) ); } [Fact] public void System_Nullable_T__ctor_05() { string source = @" struct S { public static int operator +(S s) { return 1; } public static void Main() { S s = new S(); S? sq = s; var j = +sq; System.Console.WriteLine(j); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (8,17): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // S? sq = s; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "s").WithArguments("System.Nullable`1", ".ctor").WithLocation(8, 17), // (9,17): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // var j = +sq; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "+sq").WithArguments("System.Nullable`1", ".ctor").WithLocation(9, 17) ); } [Fact] public void System_Nullable_T__ctor_06() { string source = @" class C { public readonly int? i; public C(int? i) { this.i = i; } public static implicit operator int?(C c) { return c.i; } public static implicit operator C(int? s) { return new C(s); } static void Main() { C c = new C(null); c++; System.Console.WriteLine(object.ReferenceEquals(c, null) ? 1 : 0); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (11,5): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // c++; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "c++").WithArguments("System.Nullable`1", ".ctor").WithLocation(11, 5) ); } [Fact] public void System_Decimal__op_Multiply() { string source = @" using System; class Program { static void Main() { Func<decimal?, decimal?> lambda = a => { return checked(a * a); }; } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Decimal__op_Multiply); compilation.VerifyEmitDiagnostics( // (7,65): error CS0656: Missing compiler required member 'System.Decimal.op_Multiply' // Func<decimal?, decimal?> lambda = a => { return checked(a * a); }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "a * a").WithArguments("System.Decimal", "op_Multiply").WithLocation(7, 65) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_06() { string source = @" using System; struct S : IDisposable { public void Dispose() { Console.WriteLine(123); } static void Main() { using (S? r = new S()) { Console.Write(r); } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (13,9): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // using (S? r = new S()) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"using (S? r = new S()) { Console.Write(r); }").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(13, 9) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_07() { string source = @" using System; class C { static void Main() { decimal q = 10; decimal? x = 10; T(2, (x++).Value == (q++)); } static void T(int line, bool b) { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (10,11): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // T(2, (x++).Value == (q++)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x++").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(10, 11) ); } [Fact] public void System_Nullable_T__ctor_07() { string source = @" using System; class C { static void Main() { decimal q = 10; decimal? x = 10; T(2, (x++).Value == (q++)); } static void T(int line, bool b) { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (8,18): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // decimal? x = 10; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "10").WithArguments("System.Nullable`1", ".ctor").WithLocation(8, 18), // (10,11): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // T(2, (x++).Value == (q++)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x++").WithArguments("System.Nullable`1", ".ctor").WithLocation(10, 11), // (10,11): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // T(2, (x++).Value == (q++)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x++").WithArguments("System.Nullable`1", ".ctor").WithLocation(10, 11) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_08() { string source = @" using System; struct S { public int x; public S(int x) { this.x = x; } public static S operator ++(S s) { return new S(s.x + 1); } public static S operator --(S s) { return new S(s.x - 1); } } class C { static void Main() { S? n = new S(1); S s = new S(1); T(2, (n++).Value.x == (s++).x); } static void T(int line, bool b) { } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (18,11): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // T(2, (n++).Value.x == (s++).x); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "n++").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(18, 11) ); } [Fact] public void System_Nullable_T__ctor_08() { string source = @" using System; struct S { public int x; public S(int x) { this.x = x; } public static S operator ++(S s) { return new S(s.x + 1); } public static S operator --(S s) { return new S(s.x - 1); } } class C { static void Main() { S? n = new S(1); S s = new S(1); T(2, (n++).Value.x == (s++).x); } static void T(int line, bool b) { } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (15,12): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // S? n = new S(1); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "new S(1)").WithArguments("System.Nullable`1", ".ctor").WithLocation(15, 12), // (18,11): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // T(2, (n++).Value.x == (s++).x); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "n++").WithArguments("System.Nullable`1", ".ctor").WithLocation(18, 11) ); } [Fact] public void System_Nullable_T__ctor_09() { string source = @" using System; class C { static void T(int x, bool? b) {} static void Main() { bool bt = true; bool? bnt = bt; T(1, true & bnt); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (11,21): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // bool? bnt = bt; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "bt").WithArguments("System.Nullable`1", ".ctor").WithLocation(11, 21), // (13,14): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // T(1, true & bnt); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "true").WithArguments("System.Nullable`1", ".ctor").WithLocation(13, 14) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_09() { string source = @" using System; class C { static void T(int x, bool? b) {} static void Main() { bool bt = true; bool? bnt = bt; T(13, bnt & bnt); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (13,15): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // T(13, bnt & bnt); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "bnt & bnt").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(13, 15), // (13,15): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // T(13, bnt & bnt); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "bnt & bnt").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(13, 15) ); } [Fact] public void System_String__op_Equality_01() { string source = @" using System; struct SZ { public string str; public SZ(string str) { this.str = str; } public SZ(char c) { this.str = c.ToString(); } public static bool operator ==(SZ sz1, SZ sz2) { return sz1.str == sz2.str; } public static bool operator !=(SZ sz1, SZ sz2) { return sz1.str != sz2.str; } public override bool Equals(object x) { return true; } public override int GetHashCode() { return 0; } } class C { static void Main() { } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__op_Equality); compilation.VerifyEmitDiagnostics( // (8,61): error CS0656: Missing compiler required member 'System.String.op_Equality' // public static bool operator ==(SZ sz1, SZ sz2) { return sz1.str == sz2.str; } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "sz1.str == sz2.str").WithArguments("System.String", "op_Equality").WithLocation(8, 61) ); } [Fact] public void System_Nullable_T_get_HasValue_03() { var source = @" using System; static class LiveList { struct WhereInfo<TSource> { public int Key { get; set; } } static void Where<TSource>() { Action subscribe = () => { WhereInfo<TSource>? previous = null; var previousKey = previous?.Key; }; } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_get_HasValue); compilation.VerifyEmitDiagnostics( // (17,31): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // var previousKey = previous?.Key; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "previous?.Key").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(17, 31) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_10() { var source = @"using System; public class X { public static void Main() { var s = nameof(Main); if (s is string t) Console.WriteLine(""1. {0}"", t); s = null; Console.WriteLine(""2. {0}"", s is string w ? w : nameof(X)); int? x = 12; {if (x is var y) Console.WriteLine(""3. {0}"", y);} {if (x is int y) Console.WriteLine(""4. {0}"", y);} x = null; {if (x is var y) Console.WriteLine(""5. {0}"", y);} {if (x is int y) Console.WriteLine(""6. {0}"", y);} Console.WriteLine(""7. {0}"", (x is bool is bool)); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (16,38): warning CS0184: The given expression is never of the provided ('bool') type // Console.WriteLine("7. {0}", (x is bool is bool)); Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "x is bool").WithArguments("bool").WithLocation(16, 38), // (16,38): warning CS0183: The given expression is always of the provided ('bool') type // Console.WriteLine("7. {0}", (x is bool is bool)); Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "x is bool is bool").WithArguments("bool").WithLocation(16, 38), // (12,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // {if (x is int y) Console.WriteLine("4. {0}", y);} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int y").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(12, 19), // (15,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // {if (x is int y) Console.WriteLine("6. {0}", y);} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int y").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(15, 19) ); } [Fact] public void System_String__op_Equality_02() { var source = @" using System; public class X { public static void Main() { } public static void M(object o) { switch (o) { case ""hmm"": Console.WriteLine(""hmm""); break; case null: Console.WriteLine(""null""); break; case 1: Console.WriteLine(""int 1""); break; case ((byte)1): Console.WriteLine(""byte 1""); break; case ((short)1): Console.WriteLine(""short 1""); break; case ""bar"": Console.WriteLine(""bar""); break; case object t when t != o: Console.WriteLine(""impossible""); break; case 2: Console.WriteLine(""int 2""); break; case ((byte)2): Console.WriteLine(""byte 2""); break; case ((short)2): Console.WriteLine(""short 2""); break; case ""baz"": Console.WriteLine(""baz""); break; default: Console.WriteLine(""other "" + o); break; } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__op_Equality); compilation.VerifyEmitDiagnostics( // (13,18): error CS0656: Missing compiler required member 'System.String.op_Equality' // case "hmm": Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"""hmm""").WithArguments("System.String", "op_Equality").WithLocation(13, 18), // (33,18): error CS0656: Missing compiler required member 'System.String.op_Equality' // case "baz": Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"""baz""").WithArguments("System.String", "op_Equality").WithLocation(33, 18) ); } [Fact] public void System_String__Chars() { var source = @"using System; class Program { public static void Main(string[] args) { bool hasB = false; foreach (var c in ""ab"") { switch (c) { case char b when IsB(b): hasB = true; break; default: hasB = false; break; } } Console.WriteLine(hasB); } public static bool IsB(char value) { return value == 'b'; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__Chars); compilation.VerifyEmitDiagnostics( // (8,9): error CS0656: Missing compiler required member 'System.String.get_Chars' // foreach (var c in "ab") Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"foreach (var c in ""ab"") { switch (c) { case char b when IsB(b): hasB = true; break; default: hasB = false; break; } }").WithArguments("System.String", "get_Chars").WithLocation(8, 9) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_11() { var source = @"using System; class Program { static void Main(string[] args) { } static void M(X? x) { switch (x) { case null: Console.WriteLine(""null""); break; case 1: Console.WriteLine(1); break; } } } struct X { public static implicit operator int? (X x) { return 1; } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (9,13): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // switch (x) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(9, 13), // (14,12): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // case 1: Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "1").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(14, 12) ); } [Fact] public void System_String__ConcatObject() { // It isn't possible to trigger this diagnostic, as we don't use String.Concat(object) var source = @" using System; public class Test { private static string S = ""F""; private static object O = ""O""; static void Main() { Console.WriteLine(O + null); Console.WriteLine(S + null); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatObject); compilation.VerifyEmitDiagnostics(); // We don't expect any CompileAndVerify(compilation, expectedOutput: @"O F"); } [Fact] public void System_Object__ToString() { var source = @" using System; public class Test { static void Main() { char c = 'c'; Console.WriteLine(c + ""3""); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Object__ToString); compilation.VerifyEmitDiagnostics( // (9,27): error CS0656: Missing compiler required member 'System.Object.ToString' // Console.WriteLine(c + "3"); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"c + ""3""").WithArguments("System.Object", "ToString").WithLocation(9, 27) ); } [Fact] public void System_String__ConcatStringString() { var source = @" using System; using System.Linq; using System.Linq.Expressions; class Test { public static void Main() { Expression<Func<string, string, string>> testExpr = (x, y) => x + y; var result = testExpr.Compile()(""Hello "", ""World!""); Console.WriteLine(result); } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatStringString); compilation.VerifyEmitDiagnostics( // (10,71): error CS0656: Missing compiler required member 'System.String.Concat' // Expression<Func<string, string, string>> testExpr = (x, y) => x + y; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x + y").WithArguments("System.String", "Concat").WithLocation(10, 71) ); } [Fact] public void System_Array__GetLowerBound() { var source = @" class C { static void Main() { double[,] values = { { 1.2, 2.3, 3.4, 4.5 }, { 5.6, 6.7, 7.8, 8.9 }, }; foreach (var x in values) { System.Console.WriteLine(x); } } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Array__GetLowerBound); compilation.VerifyEmitDiagnostics( // (11,9): error CS0656: Missing compiler required member 'System.Array.GetLowerBound' // foreach (var x in values) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"foreach (var x in values) { System.Console.WriteLine(x); }").WithArguments("System.Array", "GetLowerBound").WithLocation(11, 9) ); } [Fact] public void System_Array__GetUpperBound() { var source = @" class C { static void Main() { double[,] values = { { 1.2, 2.3, 3.4, 4.5 }, { 5.6, 6.7, 7.8, 8.9 }, }; foreach (var x in values) { System.Console.WriteLine(x); } } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Array__GetUpperBound); compilation.VerifyEmitDiagnostics( // (11,9): error CS0656: Missing compiler required member 'System.Array.GetUpperBound' // foreach (var x in values) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"foreach (var x in values) { System.Console.WriteLine(x); }").WithArguments("System.Array", "GetUpperBound").WithLocation(11, 9) ); } [Fact] public void System_Decimal__op_Implicit_FromInt32() { var source = @"using System; using System.Linq.Expressions; public struct SampStruct { public static implicit operator int(SampStruct ss1) { return 1; } } public class Test { static void Main() { Expression<Func<SampStruct?, decimal, decimal>> testExpr = (x, y) => x ?? y; } }"; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }); compilation.MakeMemberMissing(SpecialMember.System_Decimal__op_Implicit_FromInt32); compilation.VerifyEmitDiagnostics( // (16,78): error CS0656: Missing compiler required member 'System.Decimal.op_Implicit' // Expression<Func<SampStruct?, decimal, decimal>> testExpr = (x, y) => x ?? y; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x ?? y").WithArguments("System.Decimal", "op_Implicit").WithLocation(16, 78) ); } [Fact] public void System_Nullable_T__ctor_10() { string source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System; class Test { static void LogCallerLineNumber5([CallerLineNumber] int? lineNumber = 5) { Console.WriteLine(""line: "" + lineNumber); } public static void Main() { LogCallerLineNumber5(); } }"; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemRef }); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (10,9): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // LogCallerLineNumber5(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "LogCallerLineNumber5()").WithArguments("System.Nullable`1", ".ctor").WithLocation(10, 9) ); } } }
// 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. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MissingSpecialMember : CSharpTestBase { [Fact] public void Missing_System_Collections_Generic_IEnumerable_T__GetEnumerator() { var source = @"using System.Collections.Generic; public class Program { public static void Main(string[] args) { } public IEnumerable<int> M() { yield return 0; yield return 1; } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(SpecialMember.System_Collections_Generic_IEnumerable_T__GetEnumerator); comp.VerifyEmitDiagnostics( // (10,5): error CS0656: Missing compiler required member 'System.Collections.Generic.IEnumerable`1.GetEnumerator' // { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"{ yield return 0; yield return 1; }").WithArguments("System.Collections.Generic.IEnumerable`1", "GetEnumerator").WithLocation(10, 5) ); } [Fact] public void Missing_System_IDisposable__Dispose() { var source = @"using System.Collections.Generic; public class Program { public static void Main(string[] args) { } public IEnumerable<int> M() { yield return 0; yield return 1; } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(SpecialMember.System_IDisposable__Dispose); comp.VerifyEmitDiagnostics( // (10,5): error CS0656: Missing compiler required member 'System.IDisposable.Dispose' // { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"{ yield return 0; yield return 1; }").WithArguments("System.IDisposable", "Dispose").WithLocation(10, 5) ); } [Fact] public void Missing_System_Diagnostics_DebuggerHiddenAttribute__ctor() { var source = @"using System.Collections.Generic; public class Program { public static void Main(string[] args) { } public IEnumerable<int> M() { yield return 0; yield return 1; } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor); comp.VerifyEmitDiagnostics( // the DebuggerHidden attribute is optional. ); } [Fact] public void Missing_System_Runtime_CompilerServices_ExtensionAttribute__ctor() { var source = @"using System.Collections.Generic; public static class Program { public static void Main(string[] args) { } public static void Extension(this string x) {} }"; var comp = CreateEmptyCompilation(source, new[] { Net40.mscorlib }, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor); comp.VerifyEmitDiagnostics( // (9,34): error CS1110: Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll? // public static void Extension(this string x) {} Diagnostic(ErrorCode.ERR_ExtensionAttrNotFound, "this").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(9, 34) ); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicSpecialType() { var source = @" namespace System { public class Object { public Object() { } } internal class String : Object { } public class ValueType { } public struct Void { } } "; Action<CSharpCompilation> validate = comp => { var specialType = comp.GetSpecialType(SpecialType.System_String); Assert.Equal(TypeKind.Error, specialType.TypeKind); Assert.Equal(SpecialType.System_String, specialType.SpecialType); Assert.Equal(Accessibility.NotApplicable, specialType.DeclaredAccessibility); var lookupType = comp.GetTypeByMetadataName("System.String"); Assert.Equal(TypeKind.Class, lookupType.TypeKind); Assert.Equal(SpecialType.None, lookupType.SpecialType); Assert.Equal(Accessibility.Internal, lookupType.DeclaredAccessibility); }; ValidateSourceAndMetadata(source, validate); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicSpecialTypeMember() { var sourceTemplate = @" namespace System {{ public class Object {{ public Object() {{ }} {0} virtual String ToString() {{ return null; }} }} {0} class String : Object {{ public static String Concat(String s1, String s2) {{ return null; }} }} public class ValueType {{ }} public struct Void {{ }} }} "; Action<CSharpCompilation> validatePresent = comp => { Assert.NotNull(comp.GetSpecialTypeMember(SpecialMember.System_Object__ToString)); Assert.NotNull(comp.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString)); comp.GetDiagnostics(); }; Action<CSharpCompilation> validateMissing = comp => { Assert.Null(comp.GetSpecialTypeMember(SpecialMember.System_Object__ToString)); Assert.Null(comp.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString)); comp.GetDiagnostics(); }; ValidateSourceAndMetadata(string.Format(sourceTemplate, "public"), validatePresent); ValidateSourceAndMetadata(string.Format(sourceTemplate, "internal"), validateMissing); } // Document the fact that we don't reject type parameters with constraints (yet?). [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void GenericConstraintsOnSpecialType() { var source = @" namespace System { public class Object { public Object() { } } public struct Nullable<T> where T : new() { } public class ValueType { } public struct Void { } } "; Action<CSharpCompilation> validate = comp => { var specialType = comp.GetSpecialType(SpecialType.System_Nullable_T); Assert.Equal(TypeKind.Struct, specialType.TypeKind); Assert.Equal(SpecialType.System_Nullable_T, specialType.SpecialType); var lookupType = comp.GetTypeByMetadataName("System.Nullable`1"); Assert.Equal(TypeKind.Struct, lookupType.TypeKind); Assert.Equal(SpecialType.System_Nullable_T, lookupType.SpecialType); }; ValidateSourceAndMetadata(source, validate); } // No special type members have type parameters that could (incorrectly) be constrained. [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicWellKnownType() { var source = @" namespace System { public class Object { public Object() { } } internal class Type : Object { } public class ValueType { } public struct Void { } } "; var comp = CreateEmptyCompilation(source); var wellKnownType = comp.GetWellKnownType(WellKnownType.System_Type); Assert.Equal(TypeKind.Class, wellKnownType.TypeKind); Assert.Equal(Accessibility.Internal, wellKnownType.DeclaredAccessibility); var lookupType = comp.GetTypeByMetadataName("System.Type"); Assert.Equal(TypeKind.Class, lookupType.TypeKind); Assert.Equal(Accessibility.Internal, lookupType.DeclaredAccessibility); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicWellKnownType_Nested() { var sourceTemplate = @" namespace System.Diagnostics {{ {0} class DebuggableAttribute {{ {1} enum DebuggingModes {{ }} }} }} namespace System {{ public class Object {{ }} public class ValueType {{ }} public class Enum : ValueType {{ }} public struct Void {{ }} public struct Int32 {{ }} }} "; Action<CSharpCompilation> validate = comp => { var wellKnownType = comp.GetWellKnownType(WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes); Assert.Equal(TypeKind.Error, wellKnownType.TypeKind); Assert.Equal(Accessibility.NotApplicable, wellKnownType.DeclaredAccessibility); var lookupType = comp.GetTypeByMetadataName("System.Diagnostics.DebuggableAttribute+DebuggingModes"); Assert.Equal(TypeKind.Enum, lookupType.TypeKind); Assert.NotEqual(Accessibility.NotApplicable, lookupType.DeclaredAccessibility); }; ValidateSourceAndMetadata(string.Format(sourceTemplate, "public", "protected"), validate); ValidateSourceAndMetadata(string.Format(sourceTemplate, "public", "private"), validate); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicWellKnownTypeMember() { var sourceTemplate = @" namespace System {{ public class Object {{ public Object() {{ }} }} {0} class Type : Object {{ public static readonly Object Missing = new Object(); }} public static class Math : Object {{ {0} static Double Round(Double d) {{ return d; }} }} public class ValueType {{ }} public struct Void {{ }} public struct Double {{ }} }} "; Action<CSharpCompilation> validatePresent = comp => { Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Type__Missing)); Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Math__RoundDouble)); comp.GetDiagnostics(); }; validatePresent(CreateEmptyCompilation(string.Format(sourceTemplate, "public"))); validatePresent(CreateEmptyCompilation(string.Format(sourceTemplate, "internal"))); } // Document the fact that we don't reject type parameters with constraints (yet?). [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void GenericConstraintsOnWellKnownType() { var source = @" namespace System { public class Object { public Object() { } } namespace Threading.Tasks { public class Task<T> where T : new() { } } public class ValueType { } public struct Void { } } "; Action<CSharpCompilation> validate = comp => { var wellKnownType = comp.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T); Assert.Equal(TypeKind.Class, wellKnownType.TypeKind); var lookupType = comp.GetTypeByMetadataName("System.Threading.Tasks.Task`1"); Assert.Equal(TypeKind.Class, lookupType.TypeKind); }; ValidateSourceAndMetadata(source, validate); } // Document the fact that we don't reject type parameters with constraints (yet?). [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void GenericConstraintsOnWellKnownTypeMember() { var sourceTemplate = @" namespace System {{ public class Object {{ public Object() {{ }} }} namespace Threading {{ public static class Interlocked {{ public static T CompareExchange<T>(ref T t1, T t2, T t3){0} {{ return t1; }} }} }} public class ValueType {{ }} public struct Void {{ }} }} "; Action<CSharpCompilation> validate = comp => { Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T)); comp.GetDiagnostics(); }; ValidateSourceAndMetadata(string.Format(sourceTemplate, ""), validate); ValidateSourceAndMetadata(string.Format(sourceTemplate, " where T : new()"), validate); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void PublicVersusInternalWellKnownType() { var corlibSource = @" namespace System { public class Object { public Object() { } } public class String { } public class Attribute { } public class ValueType { } public struct Void { } } namespace System.Runtime.CompilerServices { public class InternalsVisibleToAttribute : Attribute { public InternalsVisibleToAttribute(String s) { } } } "; var libSourceTemplate = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Test"")] namespace System {{ {0} class Type {{ }} }} "; var corlibRef = CreateEmptyCompilation(corlibSource).EmitToImageReference(expectedWarnings: new[] { // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) }); var publicLibRef = CreateEmptyCompilation(string.Format(libSourceTemplate, "public"), new[] { corlibRef }).EmitToImageReference(); var internalLibRef = CreateEmptyCompilation(string.Format(libSourceTemplate, "internal"), new[] { corlibRef }).EmitToImageReference(); var comp = CreateEmptyCompilation("", new[] { corlibRef, publicLibRef, internalLibRef }, assemblyName: "Test"); var wellKnown = comp.GetWellKnownType(WellKnownType.System_Type); Assert.NotNull(wellKnown); Assert.Equal(TypeKind.Class, wellKnown.TypeKind); Assert.Equal(Accessibility.Public, wellKnown.DeclaredAccessibility); var lookup = comp.GetTypeByMetadataName("System.Type"); Assert.Null(lookup); // Ambiguous } private static void ValidateSourceAndMetadata(string source, Action<CSharpCompilation> validate) { var comp1 = CreateEmptyCompilation(source); validate(comp1); var reference = comp1.EmitToImageReference(expectedWarnings: new[] { // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) }); var comp2 = CreateEmptyCompilation("", new[] { reference }); validate(comp2); } [Fact] [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] public void AllSpecialTypes() { var comp = CreateEmptyCompilation("", new[] { MscorlibRef_v4_0_30316_17626 }); for (var special = SpecialType.None + 1; special <= SpecialType.Count; special++) { var symbol = comp.GetSpecialType(special); Assert.NotNull(symbol); if (special == SpecialType.System_Runtime_CompilerServices_RuntimeFeature || special == SpecialType.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute) { Assert.Equal(SymbolKind.ErrorType, symbol.Kind); // Not available } else { Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind); } } } [Fact] [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] public void AllSpecialTypeMembers() { var comp = CreateEmptyCompilation("", new[] { MscorlibRef_v4_0_30316_17626 }); foreach (SpecialMember special in Enum.GetValues(typeof(SpecialMember))) { if (special == SpecialMember.Count) continue; // Not a real value; var symbol = comp.GetSpecialTypeMember(special); if (special == SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces || special == SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses || special == SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__VirtualStaticsInInterfaces || special == SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention || special == SpecialMember.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor) { Assert.Null(symbol); // Not available } else { Assert.NotNull(symbol); } } } [Fact] [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] public void AllWellKnownTypes() { var refs = new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929, CSharpRef, SystemXmlRef, SystemXmlLinqRef, SystemWindowsFormsRef, ValueTupleRef }.Concat(WinRtRefs).ToArray(); var comp = CreateEmptyCompilation("", refs); for (var wkt = WellKnownType.First; wkt < WellKnownType.NextAvailable; wkt++) { switch (wkt) { case WellKnownType.Microsoft_VisualBasic_Embedded: case WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators: // Not applicable in C#. continue; case WellKnownType.System_FormattableString: case WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory: case WellKnownType.System_Runtime_CompilerServices_NullableAttribute: case WellKnownType.System_Runtime_CompilerServices_NullableContextAttribute: case WellKnownType.System_Runtime_CompilerServices_NullablePublicOnlyAttribute: case WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute: case WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute: case WellKnownType.System_Span_T: case WellKnownType.System_ReadOnlySpan_T: case WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute: case WellKnownType.System_Index: case WellKnownType.System_Range: case WellKnownType.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute: case WellKnownType.System_IAsyncDisposable: case WellKnownType.System_Collections_Generic_IAsyncEnumerable_T: case WellKnownType.System_Collections_Generic_IAsyncEnumerator_T: case WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T: case WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus: case WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags: case WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T: case WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource: case WellKnownType.System_Threading_Tasks_ValueTask_T: case WellKnownType.System_Threading_Tasks_ValueTask: case WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder: case WellKnownType.System_Threading_CancellationToken: case WellKnownType.System_Runtime_CompilerServices_SwitchExpressionException: case WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute: case WellKnownType.System_Runtime_CompilerServices_IsExternalInit: case WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler: // Not yet in the platform. continue; case WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation: case WellKnownType.System_Runtime_CompilerServices_ITuple: case WellKnownType.System_Runtime_CompilerServices_NonNullTypesAttribute: case WellKnownType.Microsoft_CodeAnalysis_EmbeddedAttribute: // Not always available. continue; case WellKnownType.ExtSentinel: // Not a real type continue; } switch (wkt) { case WellKnownType.System_ValueTuple: case WellKnownType.System_ValueTuple_T1: case WellKnownType.System_ValueTuple_T2: case WellKnownType.System_ValueTuple_T3: case WellKnownType.System_ValueTuple_T4: case WellKnownType.System_ValueTuple_T5: case WellKnownType.System_ValueTuple_T6: case WellKnownType.System_ValueTuple_T7: case WellKnownType.System_ValueTuple_TRest: Assert.True(wkt.IsValueTupleType()); break; default: Assert.False(wkt.IsValueTupleType()); break; } var symbol = comp.GetWellKnownType(wkt); Assert.NotNull(symbol); Assert.True(symbol.Kind != SymbolKind.ErrorType, $"{wkt} should not be an error type"); } } [Fact] public void AllWellKnownTypesBeforeCSharp7() { foreach (var type in new[] { WellKnownType.System_Math, WellKnownType.System_Array, WellKnownType.System_Attribute, WellKnownType.System_CLSCompliantAttribute, WellKnownType.System_Convert, WellKnownType.System_Exception, WellKnownType.System_FlagsAttribute, WellKnownType.System_FormattableString, WellKnownType.System_Guid, WellKnownType.System_IFormattable, WellKnownType.System_RuntimeTypeHandle, WellKnownType.System_RuntimeFieldHandle, WellKnownType.System_RuntimeMethodHandle, WellKnownType.System_MarshalByRefObject, WellKnownType.System_Type, WellKnownType.System_Reflection_AssemblyKeyFileAttribute, WellKnownType.System_Reflection_AssemblyKeyNameAttribute, WellKnownType.System_Reflection_MethodInfo, WellKnownType.System_Reflection_ConstructorInfo, WellKnownType.System_Reflection_MethodBase, WellKnownType.System_Reflection_FieldInfo, WellKnownType.System_Reflection_MemberInfo, WellKnownType.System_Reflection_Missing, WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory, WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, WellKnownType.System_Runtime_InteropServices_StructLayoutAttribute, WellKnownType.System_Runtime_InteropServices_UnknownWrapper, WellKnownType.System_Runtime_InteropServices_DispatchWrapper, WellKnownType.System_Runtime_InteropServices_CallingConvention, WellKnownType.System_Runtime_InteropServices_ClassInterfaceAttribute, WellKnownType.System_Runtime_InteropServices_ClassInterfaceType, WellKnownType.System_Runtime_InteropServices_CoClassAttribute, WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, WellKnownType.System_Runtime_InteropServices_ComEventInterfaceAttribute, WellKnownType.System_Runtime_InteropServices_ComInterfaceType, WellKnownType.System_Runtime_InteropServices_ComSourceInterfacesAttribute, WellKnownType.System_Runtime_InteropServices_ComVisibleAttribute, WellKnownType.System_Runtime_InteropServices_DispIdAttribute, WellKnownType.System_Runtime_InteropServices_GuidAttribute, WellKnownType.System_Runtime_InteropServices_InterfaceTypeAttribute, WellKnownType.System_Runtime_InteropServices_Marshal, WellKnownType.System_Runtime_InteropServices_TypeIdentifierAttribute, WellKnownType.System_Runtime_InteropServices_BestFitMappingAttribute, WellKnownType.System_Runtime_InteropServices_DefaultParameterValueAttribute, WellKnownType.System_Runtime_InteropServices_LCIDConversionAttribute, WellKnownType.System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute, WellKnownType.System_Activator, WellKnownType.System_Threading_Tasks_Task, WellKnownType.System_Threading_Tasks_Task_T, WellKnownType.System_Threading_Interlocked, WellKnownType.System_Threading_Monitor, WellKnownType.System_Threading_Thread, WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfoFlags, WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, WellKnownType.Microsoft_VisualBasic_CallType, WellKnownType.Microsoft_VisualBasic_Embedded, WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators, WellKnownType.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute, WellKnownType.Microsoft_VisualBasic_CompilerServices_Utils, WellKnownType.Microsoft_VisualBasic_CompilerServices_LikeOperator, WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl, WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl, WellKnownType.Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag, WellKnownType.Microsoft_VisualBasic_CompilerServices_StringType, WellKnownType.Microsoft_VisualBasic_CompilerServices_IncompleteInitialization, WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, WellKnownType.Microsoft_VisualBasic_CompareMethod, WellKnownType.Microsoft_VisualBasic_Strings, WellKnownType.Microsoft_VisualBasic_ErrObject, WellKnownType.Microsoft_VisualBasic_FileSystem, WellKnownType.Microsoft_VisualBasic_ApplicationServices_ApplicationBase, WellKnownType.Microsoft_VisualBasic_ApplicationServices_WindowsFormsApplicationBase, WellKnownType.Microsoft_VisualBasic_Information, WellKnownType.Microsoft_VisualBasic_Interaction, WellKnownType.System_Func_T, WellKnownType.System_Func_T2, WellKnownType.System_Func_T3, WellKnownType.System_Func_T4, WellKnownType.System_Func_T5, WellKnownType.System_Func_T6, WellKnownType.System_Func_T7, WellKnownType.System_Func_T8, WellKnownType.System_Func_T9, WellKnownType.System_Func_T10, WellKnownType.System_Func_T11, WellKnownType.System_Func_T12, WellKnownType.System_Func_T13, WellKnownType.System_Func_T14, WellKnownType.System_Func_T15, WellKnownType.System_Func_T16, WellKnownType.System_Func_T17, WellKnownType.System_Action, WellKnownType.System_Action_T, WellKnownType.System_Action_T2, WellKnownType.System_Action_T3, WellKnownType.System_Action_T4, WellKnownType.System_Action_T5, WellKnownType.System_Action_T6, WellKnownType.System_Action_T7, WellKnownType.System_Action_T8, WellKnownType.System_Action_T9, WellKnownType.System_Action_T10, WellKnownType.System_Action_T11, WellKnownType.System_Action_T12, WellKnownType.System_Action_T13, WellKnownType.System_Action_T14, WellKnownType.System_Action_T15, WellKnownType.System_Action_T16, WellKnownType.System_AttributeUsageAttribute, WellKnownType.System_ParamArrayAttribute, WellKnownType.System_NonSerializedAttribute, WellKnownType.System_STAThreadAttribute, WellKnownType.System_Reflection_DefaultMemberAttribute, WellKnownType.System_Runtime_CompilerServices_DateTimeConstantAttribute, WellKnownType.System_Runtime_CompilerServices_DecimalConstantAttribute, WellKnownType.System_Runtime_CompilerServices_IUnknownConstantAttribute, WellKnownType.System_Runtime_CompilerServices_IDispatchConstantAttribute, WellKnownType.System_Runtime_CompilerServices_ExtensionAttribute, WellKnownType.System_Runtime_CompilerServices_INotifyCompletion, WellKnownType.System_Runtime_CompilerServices_InternalsVisibleToAttribute, WellKnownType.System_Runtime_CompilerServices_CompilerGeneratedAttribute, WellKnownType.System_Runtime_CompilerServices_AccessedThroughPropertyAttribute, WellKnownType.System_Runtime_CompilerServices_CompilationRelaxationsAttribute, WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute, WellKnownType.System_Runtime_CompilerServices_UnsafeValueTypeAttribute, WellKnownType.System_Runtime_CompilerServices_FixedBufferAttribute, WellKnownType.System_Runtime_CompilerServices_DynamicAttribute, WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, WellKnownType.System_Runtime_CompilerServices_CallSite, WellKnownType.System_Runtime_CompilerServices_CallSite_T, WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, WellKnownType.Windows_Foundation_IAsyncAction, WellKnownType.Windows_Foundation_IAsyncActionWithProgress_T, WellKnownType.Windows_Foundation_IAsyncOperation_T, WellKnownType.Windows_Foundation_IAsyncOperationWithProgress_T2, WellKnownType.System_Diagnostics_Debugger, WellKnownType.System_Diagnostics_DebuggerDisplayAttribute, WellKnownType.System_Diagnostics_DebuggerNonUserCodeAttribute, WellKnownType.System_Diagnostics_DebuggerHiddenAttribute, WellKnownType.System_Diagnostics_DebuggerBrowsableAttribute, WellKnownType.System_Diagnostics_DebuggerStepThroughAttribute, WellKnownType.System_Diagnostics_DebuggerBrowsableState, WellKnownType.System_Diagnostics_DebuggableAttribute, WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, WellKnownType.System_ComponentModel_DesignerSerializationVisibilityAttribute, WellKnownType.System_IEquatable_T, WellKnownType.System_Collections_IList, WellKnownType.System_Collections_ICollection, WellKnownType.System_Collections_Generic_EqualityComparer_T, WellKnownType.System_Collections_Generic_List_T, WellKnownType.System_Collections_Generic_IDictionary_KV, WellKnownType.System_Collections_Generic_IReadOnlyDictionary_KV, WellKnownType.System_Collections_ObjectModel_Collection_T, WellKnownType.System_Collections_ObjectModel_ReadOnlyCollection_T, WellKnownType.System_Collections_Specialized_INotifyCollectionChanged, WellKnownType.System_ComponentModel_INotifyPropertyChanged, WellKnownType.System_ComponentModel_EditorBrowsableAttribute, WellKnownType.System_ComponentModel_EditorBrowsableState, WellKnownType.System_Linq_Enumerable, WellKnownType.System_Linq_Expressions_Expression, WellKnownType.System_Linq_Expressions_Expression_T, WellKnownType.System_Linq_Expressions_ParameterExpression, WellKnownType.System_Linq_Expressions_ElementInit, WellKnownType.System_Linq_Expressions_MemberBinding, WellKnownType.System_Linq_Expressions_ExpressionType, WellKnownType.System_Linq_IQueryable, WellKnownType.System_Linq_IQueryable_T, WellKnownType.System_Xml_Linq_Extensions, WellKnownType.System_Xml_Linq_XAttribute, WellKnownType.System_Xml_Linq_XCData, WellKnownType.System_Xml_Linq_XComment, WellKnownType.System_Xml_Linq_XContainer, WellKnownType.System_Xml_Linq_XDeclaration, WellKnownType.System_Xml_Linq_XDocument, WellKnownType.System_Xml_Linq_XElement, WellKnownType.System_Xml_Linq_XName, WellKnownType.System_Xml_Linq_XNamespace, WellKnownType.System_Xml_Linq_XObject, WellKnownType.System_Xml_Linq_XProcessingInstruction, WellKnownType.System_Security_UnverifiableCodeAttribute, WellKnownType.System_Security_Permissions_SecurityAction, WellKnownType.System_Security_Permissions_SecurityAttribute, WellKnownType.System_Security_Permissions_SecurityPermissionAttribute, WellKnownType.System_NotSupportedException, WellKnownType.System_Runtime_CompilerServices_ICriticalNotifyCompletion, WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, WellKnownType.System_Runtime_CompilerServices_AsyncStateMachineAttribute, WellKnownType.System_Runtime_CompilerServices_IteratorStateMachineAttribute, WellKnownType.System_Windows_Forms_Form, WellKnownType.System_Windows_Forms_Application, WellKnownType.System_Environment, WellKnownType.System_Runtime_GCLatencyMode, WellKnownType.System_IFormatProvider } ) { Assert.True(type <= WellKnownType.CSharp7Sentinel); } // There were 204 well-known types prior to CSharp7 Assert.Equal(204, (int)(WellKnownType.CSharp7Sentinel - WellKnownType.First)); } [Fact] [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] public void AllWellKnownTypeMembers() { var refs = new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929, CSharpDesktopRef, SystemXmlRef, SystemXmlLinqRef, SystemWindowsFormsRef, ValueTupleRef }.Concat(WinRtRefs).ToArray(); var comp = CreateEmptyCompilation("", refs); foreach (WellKnownMember wkm in Enum.GetValues(typeof(WellKnownMember))) { switch (wkm) { case WellKnownMember.Count: // Not a real value; continue; case WellKnownMember.Microsoft_VisualBasic_Embedded__ctor: case WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean: // C# can't embed VB core. continue; case WellKnownMember.System_Array__Empty: case WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte: case WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags: case WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor: case WellKnownMember.System_Span_T__ctor: case WellKnownMember.System_Span_T__get_Item: case WellKnownMember.System_Span_T__get_Length: case WellKnownMember.System_ReadOnlySpan_T__ctor: case WellKnownMember.System_ReadOnlySpan_T__get_Item: case WellKnownMember.System_ReadOnlySpan_T__get_Length: case WellKnownMember.System_Index__ctor: case WellKnownMember.System_Index__GetOffset: case WellKnownMember.System_Range__ctor: case WellKnownMember.System_Range__StartAt: case WellKnownMember.System_Range__EndAt: case WellKnownMember.System_Range__get_All: case WellKnownMember.System_Range__get_Start: case WellKnownMember.System_Range__get_End: case WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor: case WellKnownMember.System_IAsyncDisposable__DisposeAsync: case WellKnownMember.System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator: case WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync: case WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__get_Current: case WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version: case WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult: case WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus: case WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted: case WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset: case WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult: case WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException: case WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult: case WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus: case WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted: case WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__GetResult: case WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__GetStatus: case WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted: case WellKnownMember.System_Threading_Tasks_ValueTask_T__ctorSourceAndToken: case WellKnownMember.System_Threading_Tasks_ValueTask_T__ctorValue: case WellKnownMember.System_Threading_Tasks_ValueTask__ctor: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T: case WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctor: case WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctorObject: case WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags: case WellKnownMember.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear: // Not yet in the platform. continue; case WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile: case WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles: case WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Item: case WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Length: // Not always available. continue; } if (wkm == WellKnownMember.Count) continue; // Not a real value. var symbol = comp.GetWellKnownTypeMember(wkm); Assert.True((object)symbol != null, $"Unexpected null for {wkm}"); } } [Fact, WorkItem(377890, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=377890")] public void System_IntPtr__op_Explicit_FromInt32() { string source = @" using System; public class MyClass { static void Main() { ((IntPtr)0).GetHashCode(); } } "; var comp = CreateCompilation(source); comp.MakeMemberMissing(SpecialMember.System_IntPtr__op_Explicit_FromInt32); comp.VerifyEmitDiagnostics( // (8,10): error CS0656: Missing compiler required member 'System.IntPtr.op_Explicit' // ((IntPtr)0).GetHashCode(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr)0").WithArguments("System.IntPtr", "op_Explicit").WithLocation(8, 10) ); } [Fact] public void System_Delegate__Combine() { var source = @" using System; using System.Threading.Tasks; namespace RoslynAsyncDelegate { class Program { static EventHandler MyEvent; static void Main(string[] args) { MyEvent += async delegate { await Task.Delay(0); }; } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); compilation.MakeMemberMissing(SpecialMember.System_Delegate__Combine); compilation.VerifyEmitDiagnostics( // (13,12): error CS0656: Missing compiler required member 'System.Delegate.Combine' // MyEvent += async delegate { await Task.Delay(0); }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "MyEvent += async delegate { await Task.Delay(0); }").WithArguments("System.Delegate", "Combine").WithLocation(13, 12) ); } [Fact] public void System_Nullable_T__ctor_01() { string source = @" using System; public struct S { public static implicit operator int(S n) // 1 native compiler { Console.WriteLine(1); return 0; } public static implicit operator int?(S n) // 2 Roslyn compiler { Console.WriteLine(2); return null; } public static void Main() { int? qa = 5; S b = default(S); var sum = qa + b; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (20,19): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // int? qa = 5; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "5").WithArguments("System.Nullable`1", ".ctor").WithLocation(20, 19), // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", ".ctor").WithLocation(22, 19) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_01() { string source = @" using System; public struct S { public static implicit operator int(S n) // 1 native compiler { Console.WriteLine(1); return 0; } public static implicit operator int?(S n) // 2 Roslyn compiler { Console.WriteLine(2); return null; } public static void Main() { int? qa = 5; S b = default(S); var sum = qa + b; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(22, 19), // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(22, 19) ); } [Fact] public void System_Nullable_T_get_HasValue_01() { string source = @" using System; public struct S { public static implicit operator int(S n) // 1 native compiler { Console.WriteLine(1); return 0; } public static implicit operator int?(S n) // 2 Roslyn compiler { Console.WriteLine(2); return null; } public static void Main() { int? qa = 5; S b = default(S); var sum = qa + b; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_get_HasValue); compilation.VerifyEmitDiagnostics( // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(22, 19), // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(22, 19) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_02() { string source = @" using System; namespace Test { static class Program { static void Main() { int? i = 123; C c = (C)i; } } public class C { public readonly int v; public C(int v) { this.v = v; } public static implicit operator C(int v) { Console.Write(v); return new C(v); } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (10,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // C c = (C)i; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(C)i").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(10, 19) ); } [Fact] public void System_Nullable_T_get_Value() { var source = @" using System; class C { static void Test() { byte? b = 0; IntPtr p = (IntPtr)b; Console.WriteLine(p); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_get_Value); compilation.VerifyEmitDiagnostics( // (9,28): error CS0656: Missing compiler required member 'System.Nullable`1.get_Value' // IntPtr p = (IntPtr)b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "b").WithArguments("System.Nullable`1", "get_Value").WithLocation(9, 28) ); } [Fact] public void System_Nullable_T__ctor_02() { var source = @" using System; class C { static void Main() { Console.WriteLine((IntPtr?)M_int()); Console.WriteLine((IntPtr?)M_int(42)); Console.WriteLine((IntPtr?)M_long()); Console.WriteLine((IntPtr?)M_long(300)); } static int? M_int(int? p = null) { return p; } static long? M_long(long? p = null) { return p; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (8,27): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_int()); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr?)M_int()").WithArguments("System.Nullable`1", ".ctor").WithLocation(8, 27), // (9,42): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_int(42)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "42").WithArguments("System.Nullable`1", ".ctor").WithLocation(9, 42), // (9,27): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_int(42)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr?)M_int(42)").WithArguments("System.Nullable`1", ".ctor").WithLocation(9, 27), // (10,27): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_long()); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr?)M_long()").WithArguments("System.Nullable`1", ".ctor").WithLocation(10, 27), // (11,43): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_long(300)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "300").WithArguments("System.Nullable`1", ".ctor").WithLocation(11, 43), // (11,27): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_long(300)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr?)M_long(300)").WithArguments("System.Nullable`1", ".ctor").WithLocation(11, 27) ); } [Fact] public void System_Nullable_T__ctor_03() { var source = @" using System; class Class1 { static void Main() { MyClass b = (int?)1; } } class MyClass { public static implicit operator MyClass(decimal Value) { return new MyClass(); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (9,21): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // MyClass b = (int?)1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(int?)1").WithArguments("System.Nullable`1", ".ctor").WithLocation(9, 21) ); } [Fact] public void System_Nullable_T__ctor_04() { var source1 = @" using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public static class Test { public static void Generic<T>([Optional][DecimalConstant(0, 0, 0, 0, 50)] T x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void Decimal([Optional][DecimalConstant(0, 0, 0, 0, 50)] Decimal x) { Console.WriteLine(x.ToString()); } public static void NullableDecimal([Optional][DecimalConstant(0, 0, 0, 0, 50)] Decimal? x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void Object([Optional][DecimalConstant(0, 0, 0, 0, 50)] object x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void String([Optional][DecimalConstant(0, 0, 0, 0, 50)] string x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void Int32([Optional][DecimalConstant(0, 0, 0, 0, 50)] int x) { Console.WriteLine(x.ToString()); } public static void IComparable([Optional][DecimalConstant(0, 0, 0, 0, 50)] IComparable x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void ValueType([Optional][DecimalConstant(0, 0, 0, 0, 50)] ValueType x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } } "; var source2 = @" class Program { public static void Main() { // Respects default value Test.Generic<decimal>(); Test.Generic<decimal?>(); Test.Generic<object>(); Test.Decimal(); Test.NullableDecimal(); Test.Object(); Test.IComparable(); Test.ValueType(); Test.Int32(); // Null, since not convertible Test.Generic<string>(); Test.String(); } } "; var compilation = CreateCompilationWithMscorlib45(source1 + source2); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (55,9): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Test.Generic<decimal?>(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "Test.Generic<decimal?>()").WithArguments("System.Nullable`1", ".ctor").WithLocation(55, 9), // (58,9): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Test.NullableDecimal(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "Test.NullableDecimal()").WithArguments("System.Nullable`1", ".ctor").WithLocation(58, 9) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_04() { var source = @" using System; class Class1 { static void Main() { int? a = 1; a.ToString(); MyClass b = a; b.ToString(); } } class MyClass { public static implicit operator MyClass(decimal Value) { return new MyClass(); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (11,21): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // MyClass b = a; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "a").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(11, 21), // (11,21): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // MyClass b = a; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "a").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(11, 21) ); } [Fact] public void System_Nullable_T_get_HasValue_02() { var source = @" using System; class Class1 { static void Main() { int? a = 1; a.ToString(); MyClass b = a; b.ToString(); } } class MyClass { public static implicit operator MyClass(decimal Value) { Console.WriteLine(""Value is: "" + Value); return new MyClass(); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_get_HasValue); compilation.VerifyEmitDiagnostics( // (11,21): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // MyClass b = a; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "a").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(11, 21) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_03() { string source = @"using System; namespace Test { static class Program { static void Main() { S.v = 0; S? S2 = 123; // not lifted, int=>int?, int?=>S, S=>S? Console.WriteLine(S.v == 123); } } public struct S { public static int v; // s == null, return v = -1 public static implicit operator S(int? s) { Console.Write(""Imp S::int? -> S ""); S ss = new S(); S.v = s ?? -1; return ss; } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (23,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // S.v = s ?? -1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "s").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(23, 19) ); } [Fact] public void System_String__ConcatObjectObject() { var source = @" using System; using System.Linq.Expressions; class Class1 { static void Main() { Expression<Func<object, string>> e = x => ""X = "" + x; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatObjectObject); compilation.VerifyEmitDiagnostics( // (9,51): error CS0656: Missing compiler required member 'System.String.Concat' // Expression<Func<object, string>> e = x => "X = " + x; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"""X = "" + x").WithArguments("System.String", "Concat").WithLocation(9, 51) ); } [Fact] public void System_String__ConcatStringStringString() { string source = @" using System; struct S { private string str; public S(char chr) { this.str = chr.ToString(); } public S(string str) { this.str = str; } public static S operator + (S x, S y) { return new S(x.str + '+' + y.str); } } class C { static void Main() { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatStringStringString); compilation.VerifyEmitDiagnostics( // (8,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator + (S x, S y) { return new S(x.str + '+' + y.str); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x.str + '+' + y.str").WithArguments("System.String", "Concat").WithLocation(8, 58) ); } [Fact] public void System_String__ConcatStringStringStringString() { string source = @" using System; struct S { private string str; public S(char chr) { this.str = chr.ToString(); } public S(string str) { this.str = str; } public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); } } class C { static void Main() { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatStringStringStringString); compilation.VerifyEmitDiagnostics( // (8,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '+' + y.str").WithArguments("System.String", "Concat").WithLocation(8, 58) ); } [Fact] public void System_String__ConcatStringArray() { string source = @" using System; struct S { private string str; public S(char chr) { this.str = chr.ToString(); } public S(string str) { this.str = str; } public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); } public static S operator - (S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); } public static S operator % (S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); } public static S operator / (S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); } public static S operator * (S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); } public static S operator & (S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); } public static S operator | (S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); } public static S operator ^ (S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); } public static S operator << (S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); } public static S operator >> (S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); } public static S operator >= (S x, S y) { return new S('(' + x.str + '>' + '=' + y.str + ')'); } public static S operator <= (S x, S y) { return new S('(' + x.str + '<' + '=' + y.str + ')'); } public static S operator > (S x, S y) { return new S('(' + x.str + '>' + y.str + ')'); } public static S operator < (S x, S y) { return new S('(' + x.str + '<' + y.str + ')'); } public override string ToString() { return this.str; } } class C { static void Main() { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatStringArray); compilation.VerifyEmitDiagnostics( // (8,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '+' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(8, 58), // (9,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator - (S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '-' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(9, 58), // (10,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator % (S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '%' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(10, 58), // (11,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator / (S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '/' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(11, 58), // (12,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator * (S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '*' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(12, 58), // (13,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator & (S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '&' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(13, 58), // (14,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator | (S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '|' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(14, 58), // (15,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator ^ (S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '^' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(15, 58), // (16,61): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator << (S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '<' + '<' + y.ToString() + ')'").WithArguments("System.String", "Concat").WithLocation(16, 61), // (17,61): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator >> (S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '>' + '>' + y.ToString() + ')'").WithArguments("System.String", "Concat").WithLocation(17, 61), // (18,59): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator >= (S x, S y) { return new S('(' + x.str + '>' + '=' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '>' + '=' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(18, 59), // (19,59): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator <= (S x, S y) { return new S('(' + x.str + '<' + '=' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '<' + '=' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(19, 59), // (20,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator > (S x, S y) { return new S('(' + x.str + '>' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '>' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(20, 58), // (21,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator < (S x, S y) { return new S('(' + x.str + '<' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '<' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(21, 58) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_05() { string source = @" struct S { public static int operator +(S s) { return 1; } public static void Main() { S s = new S(); S? sq = s; var j = +sq; System.Console.WriteLine(j); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (9,17): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // var j = +sq; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "+sq").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(9, 17) ); } [Fact] public void System_Nullable_T__ctor_05() { string source = @" struct S { public static int operator +(S s) { return 1; } public static void Main() { S s = new S(); S? sq = s; var j = +sq; System.Console.WriteLine(j); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (8,17): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // S? sq = s; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "s").WithArguments("System.Nullable`1", ".ctor").WithLocation(8, 17), // (9,17): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // var j = +sq; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "+sq").WithArguments("System.Nullable`1", ".ctor").WithLocation(9, 17) ); } [Fact] public void System_Nullable_T__ctor_06() { string source = @" class C { public readonly int? i; public C(int? i) { this.i = i; } public static implicit operator int?(C c) { return c.i; } public static implicit operator C(int? s) { return new C(s); } static void Main() { C c = new C(null); c++; System.Console.WriteLine(object.ReferenceEquals(c, null) ? 1 : 0); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (11,5): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // c++; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "c++").WithArguments("System.Nullable`1", ".ctor").WithLocation(11, 5) ); } [Fact] public void System_Decimal__op_Multiply() { string source = @" using System; class Program { static void Main() { Func<decimal?, decimal?> lambda = a => { return checked(a * a); }; } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Decimal__op_Multiply); compilation.VerifyEmitDiagnostics( // (7,65): error CS0656: Missing compiler required member 'System.Decimal.op_Multiply' // Func<decimal?, decimal?> lambda = a => { return checked(a * a); }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "a * a").WithArguments("System.Decimal", "op_Multiply").WithLocation(7, 65) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_06() { string source = @" using System; struct S : IDisposable { public void Dispose() { Console.WriteLine(123); } static void Main() { using (S? r = new S()) { Console.Write(r); } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (13,9): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // using (S? r = new S()) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"using (S? r = new S()) { Console.Write(r); }").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(13, 9) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_07() { string source = @" using System; class C { static void Main() { decimal q = 10; decimal? x = 10; T(2, (x++).Value == (q++)); } static void T(int line, bool b) { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (10,11): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // T(2, (x++).Value == (q++)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x++").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(10, 11) ); } [Fact] public void System_Nullable_T__ctor_07() { string source = @" using System; class C { static void Main() { decimal q = 10; decimal? x = 10; T(2, (x++).Value == (q++)); } static void T(int line, bool b) { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (8,18): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // decimal? x = 10; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "10").WithArguments("System.Nullable`1", ".ctor").WithLocation(8, 18), // (10,11): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // T(2, (x++).Value == (q++)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x++").WithArguments("System.Nullable`1", ".ctor").WithLocation(10, 11), // (10,11): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // T(2, (x++).Value == (q++)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x++").WithArguments("System.Nullable`1", ".ctor").WithLocation(10, 11) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_08() { string source = @" using System; struct S { public int x; public S(int x) { this.x = x; } public static S operator ++(S s) { return new S(s.x + 1); } public static S operator --(S s) { return new S(s.x - 1); } } class C { static void Main() { S? n = new S(1); S s = new S(1); T(2, (n++).Value.x == (s++).x); } static void T(int line, bool b) { } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (18,11): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // T(2, (n++).Value.x == (s++).x); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "n++").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(18, 11) ); } [Fact] public void System_Nullable_T__ctor_08() { string source = @" using System; struct S { public int x; public S(int x) { this.x = x; } public static S operator ++(S s) { return new S(s.x + 1); } public static S operator --(S s) { return new S(s.x - 1); } } class C { static void Main() { S? n = new S(1); S s = new S(1); T(2, (n++).Value.x == (s++).x); } static void T(int line, bool b) { } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (15,12): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // S? n = new S(1); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "new S(1)").WithArguments("System.Nullable`1", ".ctor").WithLocation(15, 12), // (18,11): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // T(2, (n++).Value.x == (s++).x); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "n++").WithArguments("System.Nullable`1", ".ctor").WithLocation(18, 11) ); } [Fact] public void System_Nullable_T__ctor_09() { string source = @" using System; class C { static void T(int x, bool? b) {} static void Main() { bool bt = true; bool? bnt = bt; T(1, true & bnt); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (11,21): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // bool? bnt = bt; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "bt").WithArguments("System.Nullable`1", ".ctor").WithLocation(11, 21), // (13,14): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // T(1, true & bnt); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "true").WithArguments("System.Nullable`1", ".ctor").WithLocation(13, 14) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_09() { string source = @" using System; class C { static void T(int x, bool? b) {} static void Main() { bool bt = true; bool? bnt = bt; T(13, bnt & bnt); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (13,15): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // T(13, bnt & bnt); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "bnt & bnt").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(13, 15), // (13,15): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // T(13, bnt & bnt); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "bnt & bnt").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(13, 15) ); } [Fact] public void System_String__op_Equality_01() { string source = @" using System; struct SZ { public string str; public SZ(string str) { this.str = str; } public SZ(char c) { this.str = c.ToString(); } public static bool operator ==(SZ sz1, SZ sz2) { return sz1.str == sz2.str; } public static bool operator !=(SZ sz1, SZ sz2) { return sz1.str != sz2.str; } public override bool Equals(object x) { return true; } public override int GetHashCode() { return 0; } } class C { static void Main() { } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__op_Equality); compilation.VerifyEmitDiagnostics( // (8,61): error CS0656: Missing compiler required member 'System.String.op_Equality' // public static bool operator ==(SZ sz1, SZ sz2) { return sz1.str == sz2.str; } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "sz1.str == sz2.str").WithArguments("System.String", "op_Equality").WithLocation(8, 61) ); } [Fact] public void System_Nullable_T_get_HasValue_03() { var source = @" using System; static class LiveList { struct WhereInfo<TSource> { public int Key { get; set; } } static void Where<TSource>() { Action subscribe = () => { WhereInfo<TSource>? previous = null; var previousKey = previous?.Key; }; } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_get_HasValue); compilation.VerifyEmitDiagnostics( // (17,31): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // var previousKey = previous?.Key; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "previous?.Key").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(17, 31) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_10() { var source = @"using System; public class X { public static void Main() { var s = nameof(Main); if (s is string t) Console.WriteLine(""1. {0}"", t); s = null; Console.WriteLine(""2. {0}"", s is string w ? w : nameof(X)); int? x = 12; {if (x is var y) Console.WriteLine(""3. {0}"", y);} {if (x is int y) Console.WriteLine(""4. {0}"", y);} x = null; {if (x is var y) Console.WriteLine(""5. {0}"", y);} {if (x is int y) Console.WriteLine(""6. {0}"", y);} Console.WriteLine(""7. {0}"", (x is bool is bool)); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (16,38): warning CS0184: The given expression is never of the provided ('bool') type // Console.WriteLine("7. {0}", (x is bool is bool)); Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "x is bool").WithArguments("bool").WithLocation(16, 38), // (16,38): warning CS0183: The given expression is always of the provided ('bool') type // Console.WriteLine("7. {0}", (x is bool is bool)); Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "x is bool is bool").WithArguments("bool").WithLocation(16, 38), // (12,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // {if (x is int y) Console.WriteLine("4. {0}", y);} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int y").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(12, 19), // (15,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // {if (x is int y) Console.WriteLine("6. {0}", y);} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int y").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(15, 19) ); } [Fact] public void System_String__op_Equality_02() { var source = @" using System; public class X { public static void Main() { } public static void M(object o) { switch (o) { case ""hmm"": Console.WriteLine(""hmm""); break; case null: Console.WriteLine(""null""); break; case 1: Console.WriteLine(""int 1""); break; case ((byte)1): Console.WriteLine(""byte 1""); break; case ((short)1): Console.WriteLine(""short 1""); break; case ""bar"": Console.WriteLine(""bar""); break; case object t when t != o: Console.WriteLine(""impossible""); break; case 2: Console.WriteLine(""int 2""); break; case ((byte)2): Console.WriteLine(""byte 2""); break; case ((short)2): Console.WriteLine(""short 2""); break; case ""baz"": Console.WriteLine(""baz""); break; default: Console.WriteLine(""other "" + o); break; } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__op_Equality); compilation.VerifyEmitDiagnostics( // (13,18): error CS0656: Missing compiler required member 'System.String.op_Equality' // case "hmm": Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"""hmm""").WithArguments("System.String", "op_Equality").WithLocation(13, 18), // (33,18): error CS0656: Missing compiler required member 'System.String.op_Equality' // case "baz": Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"""baz""").WithArguments("System.String", "op_Equality").WithLocation(33, 18) ); } [Fact] public void System_String__Chars() { var source = @"using System; class Program { public static void Main(string[] args) { bool hasB = false; foreach (var c in ""ab"") { switch (c) { case char b when IsB(b): hasB = true; break; default: hasB = false; break; } } Console.WriteLine(hasB); } public static bool IsB(char value) { return value == 'b'; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__Chars); compilation.VerifyEmitDiagnostics( // (8,9): error CS0656: Missing compiler required member 'System.String.get_Chars' // foreach (var c in "ab") Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"foreach (var c in ""ab"") { switch (c) { case char b when IsB(b): hasB = true; break; default: hasB = false; break; } }").WithArguments("System.String", "get_Chars").WithLocation(8, 9) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_11() { var source = @"using System; class Program { static void Main(string[] args) { } static void M(X? x) { switch (x) { case null: Console.WriteLine(""null""); break; case 1: Console.WriteLine(1); break; } } } struct X { public static implicit operator int? (X x) { return 1; } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (9,13): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // switch (x) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(9, 13), // (14,12): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // case 1: Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "1").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(14, 12) ); } [Fact] public void System_String__ConcatObject() { // It isn't possible to trigger this diagnostic, as we don't use String.Concat(object) var source = @" using System; public class Test { private static string S = ""F""; private static object O = ""O""; static void Main() { Console.WriteLine(O + null); Console.WriteLine(S + null); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatObject); compilation.VerifyEmitDiagnostics(); // We don't expect any CompileAndVerify(compilation, expectedOutput: @"O F"); } [Fact] public void System_Object__ToString() { var source = @" using System; public class Test { static void Main() { char c = 'c'; Console.WriteLine(c + ""3""); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Object__ToString); compilation.VerifyEmitDiagnostics( // (9,27): error CS0656: Missing compiler required member 'System.Object.ToString' // Console.WriteLine(c + "3"); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"c + ""3""").WithArguments("System.Object", "ToString").WithLocation(9, 27) ); } [Fact] public void System_String__ConcatStringString() { var source = @" using System; using System.Linq; using System.Linq.Expressions; class Test { public static void Main() { Expression<Func<string, string, string>> testExpr = (x, y) => x + y; var result = testExpr.Compile()(""Hello "", ""World!""); Console.WriteLine(result); } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatStringString); compilation.VerifyEmitDiagnostics( // (10,71): error CS0656: Missing compiler required member 'System.String.Concat' // Expression<Func<string, string, string>> testExpr = (x, y) => x + y; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x + y").WithArguments("System.String", "Concat").WithLocation(10, 71) ); } [Fact] public void System_Array__GetLowerBound() { var source = @" class C { static void Main() { double[,] values = { { 1.2, 2.3, 3.4, 4.5 }, { 5.6, 6.7, 7.8, 8.9 }, }; foreach (var x in values) { System.Console.WriteLine(x); } } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Array__GetLowerBound); compilation.VerifyEmitDiagnostics( // (11,9): error CS0656: Missing compiler required member 'System.Array.GetLowerBound' // foreach (var x in values) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"foreach (var x in values) { System.Console.WriteLine(x); }").WithArguments("System.Array", "GetLowerBound").WithLocation(11, 9) ); } [Fact] public void System_Array__GetUpperBound() { var source = @" class C { static void Main() { double[,] values = { { 1.2, 2.3, 3.4, 4.5 }, { 5.6, 6.7, 7.8, 8.9 }, }; foreach (var x in values) { System.Console.WriteLine(x); } } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Array__GetUpperBound); compilation.VerifyEmitDiagnostics( // (11,9): error CS0656: Missing compiler required member 'System.Array.GetUpperBound' // foreach (var x in values) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"foreach (var x in values) { System.Console.WriteLine(x); }").WithArguments("System.Array", "GetUpperBound").WithLocation(11, 9) ); } [Fact] public void System_Decimal__op_Implicit_FromInt32() { var source = @"using System; using System.Linq.Expressions; public struct SampStruct { public static implicit operator int(SampStruct ss1) { return 1; } } public class Test { static void Main() { Expression<Func<SampStruct?, decimal, decimal>> testExpr = (x, y) => x ?? y; } }"; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }); compilation.MakeMemberMissing(SpecialMember.System_Decimal__op_Implicit_FromInt32); compilation.VerifyEmitDiagnostics( // (16,78): error CS0656: Missing compiler required member 'System.Decimal.op_Implicit' // Expression<Func<SampStruct?, decimal, decimal>> testExpr = (x, y) => x ?? y; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x ?? y").WithArguments("System.Decimal", "op_Implicit").WithLocation(16, 78) ); } [Fact] public void System_Nullable_T__ctor_10() { string source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System; class Test { static void LogCallerLineNumber5([CallerLineNumber] int? lineNumber = 5) { Console.WriteLine(""line: "" + lineNumber); } public static void Main() { LogCallerLineNumber5(); } }"; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemRef }); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (10,9): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // LogCallerLineNumber5(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "LogCallerLineNumber5()").WithArguments("System.Nullable`1", ".ctor").WithLocation(10, 9) ); } } }
1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/CSharp/Test/Symbol/Symbols/StaticAbstractMembersInInterfacesTests.cs
// 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. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class StaticAbstractMembersInInterfacesTests : CSharpTestBase { [Fact] public void MethodModifiers_01() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } private static void ValidateMethodModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<MethodSymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<MethodSymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<MethodSymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<MethodSymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<MethodSymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<MethodSymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<MethodSymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<MethodSymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<MethodSymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } [Fact] public void MethodModifiers_02() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_03() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_04() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_05() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static void M02() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static void M04() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static void M09() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_06() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static void M02() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static void M04() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static void M09() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void SealedStaticConstructor_01() { var source1 = @" interface I1 { sealed static I1() {} } partial interface I2 { partial sealed static I2(); } partial interface I2 { partial static I2() {} } partial interface I3 { partial static I3(); } partial interface I3 { partial sealed static I3() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,19): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I1").WithArguments("sealed").WithLocation(4, 19), // (9,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I2(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(9, 5), // (9,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I2(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(9, 5), // (9,27): error CS0106: The modifier 'sealed' is not valid for this item // partial sealed static I2(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(9, 27), // (14,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I2() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(14, 5), // (14,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I2() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(14, 5), // (14,20): error CS0111: Type 'I2' already defines a member called 'I2' with the same parameter types // partial static I2() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I2").WithArguments("I2", "I2").WithLocation(14, 20), // (19,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I3(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(19, 5), // (19,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I3(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(19, 5), // (24,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(24, 5), // (24,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(24, 5), // (24,27): error CS0106: The modifier 'sealed' is not valid for this item // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(24, 27), // (24,27): error CS0111: Type 'I3' already defines a member called 'I3' with the same parameter types // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I3").WithArguments("I3", "I3").WithLocation(24, 27) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); } [Fact] public void SealedStaticConstructor_02() { var source1 = @" partial interface I2 { sealed static partial I2(); } partial interface I2 { static partial I2() {} } partial interface I3 { static partial I3(); } partial interface I3 { sealed static partial I3() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,19): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // sealed static partial I2(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(4, 19), // (4,27): error CS0501: 'I2.I2()' must declare a body because it is not marked abstract, extern, or partial // sealed static partial I2(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I2").WithArguments("I2.I2()").WithLocation(4, 27), // (4,27): error CS0542: 'I2': member names cannot be the same as their enclosing type // sealed static partial I2(); Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I2").WithArguments("I2").WithLocation(4, 27), // (9,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I2() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(9, 12), // (9,20): error CS0542: 'I2': member names cannot be the same as their enclosing type // static partial I2() {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I2").WithArguments("I2").WithLocation(9, 20), // (9,20): error CS0111: Type 'I2' already defines a member called 'I2' with the same parameter types // static partial I2() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I2").WithArguments("I2", "I2").WithLocation(9, 20), // (9,20): error CS0161: 'I2.I2()': not all code paths return a value // static partial I2() {} Diagnostic(ErrorCode.ERR_ReturnExpected, "I2").WithArguments("I2.I2()").WithLocation(9, 20), // (14,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I3(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(14, 12), // (14,20): error CS0501: 'I3.I3()' must declare a body because it is not marked abstract, extern, or partial // static partial I3(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I3").WithArguments("I3.I3()").WithLocation(14, 20), // (14,20): error CS0542: 'I3': member names cannot be the same as their enclosing type // static partial I3(); Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I3").WithArguments("I3").WithLocation(14, 20), // (19,19): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(19, 19), // (19,27): error CS0542: 'I3': member names cannot be the same as their enclosing type // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I3").WithArguments("I3").WithLocation(19, 27), // (19,27): error CS0111: Type 'I3' already defines a member called 'I3' with the same parameter types // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I3").WithArguments("I3", "I3").WithLocation(19, 27), // (19,27): error CS0161: 'I3.I3()': not all code paths return a value // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_ReturnExpected, "I3").WithArguments("I3.I3()").WithLocation(19, 27) ); } [Fact] public void AbstractStaticConstructor_01() { var source1 = @" interface I1 { abstract static I1(); } interface I2 { abstract static I2() {} } interface I3 { static I3(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I1").WithArguments("abstract").WithLocation(4, 21), // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I2() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("abstract").WithLocation(9, 21), // (14,12): error CS0501: 'I3.I3()' must declare a body because it is not marked abstract, extern, or partial // static I3(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I3").WithArguments("I3.I3()").WithLocation(14, 12) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); } [Fact] public void PartialSealedStatic_01() { var source1 = @" partial interface I1 { sealed static partial void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Null(m01.PartialImplementationPart); } [Fact] public void PartialSealedStatic_02() { var source1 = @" partial interface I1 { sealed static partial void M01(); } partial interface I1 { sealed static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } private static void ValidatePartialSealedStatic_02(CSharpCompilation compilation1) { compilation1.VerifyDiagnostics(); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialSealedStatic_03() { var source1 = @" partial interface I1 { static partial void M01(); } partial interface I1 { sealed static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } [Fact] public void PartialSealedStatic_04() { var source1 = @" partial interface I1 { sealed static partial void M01(); } partial interface I1 { static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } [Fact] public void PartialAbstractStatic_01() { var source1 = @" partial interface I1 { abstract static partial void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Null(m01.PartialImplementationPart); } [Fact] public void PartialAbstractStatic_02() { var source1 = @" partial interface I1 { abstract static partial void M01(); } partial interface I1 { abstract static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34), // (8,34): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(8, 34), // (8,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(8, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialAbstractStatic_03() { var source1 = @" partial interface I1 { abstract static partial void M01(); } partial interface I1 { static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialAbstractStatic_04() { var source1 = @" partial interface I1 { static partial void M01(); } partial interface I1 { abstract static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,34): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(8, 34), // (8,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(8, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PrivateAbstractStatic_01() { var source1 = @" interface I1 { private abstract static void M01(); private abstract static bool P01 { get; } private abstract static event System.Action E01; private abstract static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0621: 'I1.M01()': virtual or abstract members cannot be private // private abstract static void M01(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "M01").WithArguments("I1.M01()").WithLocation(4, 34), // (5,34): error CS0621: 'I1.P01': virtual or abstract members cannot be private // private abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "P01").WithArguments("I1.P01").WithLocation(5, 34), // (6,49): error CS0621: 'I1.E01': virtual or abstract members cannot be private // private abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_VirtualPrivate, "E01").WithArguments("I1.E01").WithLocation(6, 49), // (7,40): error CS0558: User-defined operator 'I1.operator +(I1)' must be declared static and public // private abstract static I1 operator+ (I1 x); Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 40) ); } [Fact] public void PropertyModifiers_01() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } private static void ValidatePropertyModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); { var m01 = i1.GetMember<PropertySymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<PropertySymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<PropertySymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<PropertySymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<PropertySymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<PropertySymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<PropertySymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<PropertySymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<PropertySymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<PropertySymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } { var m01 = i1.GetMember<PropertySymbol>("M01").GetMethod; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<PropertySymbol>("M02").GetMethod; Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<PropertySymbol>("M03").GetMethod; Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<PropertySymbol>("M04").GetMethod; Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<PropertySymbol>("M05").GetMethod; Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<PropertySymbol>("M06").GetMethod; Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<PropertySymbol>("M07").GetMethod; Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<PropertySymbol>("M08").GetMethod; Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<PropertySymbol>("M09").GetMethod; Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<PropertySymbol>("M10").GetMethod; Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } } [Fact] public void PropertyModifiers_02() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_03() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_04() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_05() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static bool M04 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_06() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static bool M04 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void EventModifiers_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event D M01 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 29), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static event D M03 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static event D M07 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static event D M10 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } private static void ValidateEventModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); { var m01 = i1.GetMember<EventSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<EventSymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<EventSymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<EventSymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<EventSymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<EventSymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<EventSymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<EventSymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<EventSymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<EventSymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } foreach (var addAccessor in new[] { true, false }) { var m01 = getAccessor(i1.GetMember<EventSymbol>("M01"), addAccessor); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = getAccessor(i1.GetMember<EventSymbol>("M02"), addAccessor); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = getAccessor(i1.GetMember<EventSymbol>("M03"), addAccessor); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = getAccessor(i1.GetMember<EventSymbol>("M04"), addAccessor); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = getAccessor(i1.GetMember<EventSymbol>("M05"), addAccessor); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = getAccessor(i1.GetMember<EventSymbol>("M06"), addAccessor); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = getAccessor(i1.GetMember<EventSymbol>("M07"), addAccessor); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = getAccessor(i1.GetMember<EventSymbol>("M08"), addAccessor); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = getAccessor(i1.GetMember<EventSymbol>("M09"), addAccessor); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = getAccessor(i1.GetMember<EventSymbol>("M10"), addAccessor); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } static MethodSymbol getAccessor(EventSymbol e, bool addAccessor) { return addAccessor ? e.AddMethod : e.RemoveMethod; } } [Fact] public void EventModifiers_02() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 29), // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static event D M03 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_03() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_04() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_05() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static event D M01 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 29), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (7,28): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static event D M02 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static event D M03 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (13,29): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static event D M04 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static event D M07 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (28,37): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static event D M09 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static event D M10 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_06() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 29), // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (7,28): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static event D M03 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (13,29): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (28,37): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void OperatorModifiers_01() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "9.0", "preview").WithLocation(10, 30), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "9.0", "preview").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "9.0", "preview").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "9.0", "preview").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "9.0", "preview").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } private static void ValidateOperatorModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("op_UnaryPlus"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<MethodSymbol>("op_UnaryNegation"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<MethodSymbol>("op_Increment"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<MethodSymbol>("op_Decrement"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<MethodSymbol>("op_LogicalNot"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<MethodSymbol>("op_OnesComplement"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<MethodSymbol>("op_Addition"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<MethodSymbol>("op_Subtraction"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<MethodSymbol>("op_Multiply"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<MethodSymbol>("op_Division"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } [Fact] public void OperatorModifiers_02() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(4, 32), // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "9.0", "preview").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "9.0", "preview").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "9.0", "preview").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "9.0", "preview").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "9.0", "preview").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_03() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_04() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_05() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "7.3", "preview").WithLocation(10, 30), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "--").WithArguments("default interface implementation", "8.0").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "7.3", "preview").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "7.3", "preview").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "7.3", "preview").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "*").WithArguments("default interface implementation", "8.0").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "7.3", "preview").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_06() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(4, 32), // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "7.3", "preview").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "--").WithArguments("default interface implementation", "8.0").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "7.3", "preview").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "7.3", "preview").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "7.3", "preview").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "*").WithArguments("default interface implementation", "8.0").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "7.3", "preview").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_07() { var source1 = @" public interface I1 { abstract static bool operator== (I1 x, I1 y); abstract static bool operator!= (I1 x, I1 y) {return false;} } public interface I2 { sealed static bool operator== (I2 x, I2 y); sealed static bool operator!= (I2 x, I2 y) {return false;} } public interface I3 { abstract sealed static bool operator== (I3 x, I3 y); abstract sealed static bool operator!= (I3 x, I3 y) {return false;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool operator== (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "7.3", "preview").WithLocation(4, 34), // (6,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "7.3", "preview").WithLocation(6, 34), // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (18,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "7.3", "preview").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "7.3", "preview").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator== (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(4, 34), // (6,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(6, 34), // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (18,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); void validate() { foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I1").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I2").GetMembers()) { Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I3").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } } } [Fact] public void OperatorModifiers_08() { var source1 = @" public interface I1 { abstract static implicit operator int(I1 x); abstract static explicit operator I1(bool x) {return null;} } public interface I2 { sealed static implicit operator int(I2 x); sealed static explicit operator I2(bool x) {return null;} } public interface I3 { abstract sealed static implicit operator int(I3 x); abstract sealed static explicit operator I3(bool x) {return null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "7.3", "preview").WithLocation(4, 39), // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I1").WithArguments("abstract", "7.3", "preview").WithLocation(6, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "7.3", "preview").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I3").WithArguments("abstract", "7.3", "preview").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(4, 39), // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I1").WithArguments("abstract", "9.0", "preview").WithLocation(6, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I3").WithArguments("abstract", "9.0", "preview").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); void validate() { foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I1").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I2").GetMembers()) { Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I3").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } } } [Fact] public void FieldModifiers_01() { var source1 = @" public interface I1 { abstract static int F1; sealed static int F2; abstract int F3; sealed int F4; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,25): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract static int F1; Diagnostic(ErrorCode.ERR_AbstractField, "F1").WithLocation(4, 25), // (5,23): error CS0106: The modifier 'sealed' is not valid for this item // sealed static int F2; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F2").WithArguments("sealed").WithLocation(5, 23), // (6,18): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract int F3; Diagnostic(ErrorCode.ERR_AbstractField, "F3").WithLocation(6, 18), // (6,18): error CS0525: Interfaces cannot contain instance fields // abstract int F3; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F3").WithLocation(6, 18), // (7,16): error CS0106: The modifier 'sealed' is not valid for this item // sealed int F4; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F4").WithArguments("sealed").WithLocation(7, 16), // (7,16): error CS0525: Interfaces cannot contain instance fields // sealed int F4; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F4").WithLocation(7, 16) ); } [Fact] public void ExternAbstractStatic_01() { var source1 = @" interface I1 { extern abstract static void M01(); extern abstract static bool P01 { get; } extern abstract static event System.Action E01; extern abstract static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0180: 'I1.M01()' cannot be both extern and abstract // extern abstract static void M01(); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M01").WithArguments("I1.M01()").WithLocation(4, 33), // (5,33): error CS0180: 'I1.P01' cannot be both extern and abstract // extern abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P01").WithArguments("I1.P01").WithLocation(5, 33), // (6,48): error CS0180: 'I1.E01' cannot be both extern and abstract // extern abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E01").WithArguments("I1.E01").WithLocation(6, 48), // (7,39): error CS0180: 'I1.operator +(I1)' cannot be both extern and abstract // extern abstract static I1 operator+ (I1 x); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 39) ); } [Fact] public void ExternAbstractStatic_02() { var source1 = @" interface I1 { extern abstract static void M01() {} extern abstract static bool P01 { get => false; } extern abstract static event System.Action E01 { add {} remove {} } extern abstract static I1 operator+ (I1 x) => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0180: 'I1.M01()' cannot be both extern and abstract // extern abstract static void M01() {} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M01").WithArguments("I1.M01()").WithLocation(4, 33), // (5,33): error CS0180: 'I1.P01' cannot be both extern and abstract // extern abstract static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P01").WithArguments("I1.P01").WithLocation(5, 33), // (6,48): error CS0180: 'I1.E01' cannot be both extern and abstract // extern abstract static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E01").WithArguments("I1.E01").WithLocation(6, 48), // (6,52): error CS8712: 'I1.E01': abstract event cannot use event accessor syntax // extern abstract static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.E01").WithLocation(6, 52), // (7,39): error CS0180: 'I1.operator +(I1)' cannot be both extern and abstract // extern abstract static I1 operator+ (I1 x) => null; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 39) ); } [Fact] public void ExternSealedStatic_01() { var source1 = @" #pragma warning disable CS0626 // Method, operator, or accessor is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. interface I1 { extern sealed static void M01(); extern sealed static bool P01 { get; } extern sealed static event System.Action E01; extern sealed static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void AbstractStaticInClass_01() { var source1 = @" abstract class C1 { public abstract static void M01(); public abstract static bool P01 { get; } public abstract static event System.Action E01; public abstract static C1 operator+ (C1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static void M01(); Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M01").WithArguments("abstract").WithLocation(4, 33), // (5,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P01").WithArguments("abstract").WithLocation(5, 33), // (6,48): error CS0112: A static member cannot be marked as 'abstract' // public abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "E01").WithArguments("abstract").WithLocation(6, 48), // (7,39): error CS0106: The modifier 'abstract' is not valid for this item // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("abstract").WithLocation(7, 39), // (7,39): error CS0501: 'C1.operator +(C1)' must declare a body because it is not marked abstract, extern, or partial // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("C1.operator +(C1)").WithLocation(7, 39) ); } [Fact] public void SealedStaticInClass_01() { var source1 = @" class C1 { sealed static void M01() {} sealed static bool P01 { get => false; } sealed static event System.Action E01 { add {} remove {} } public sealed static C1 operator+ (C1 x) => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0238: 'C1.M01()' cannot be sealed because it is not an override // sealed static void M01() {} Diagnostic(ErrorCode.ERR_SealedNonOverride, "M01").WithArguments("C1.M01()").WithLocation(4, 24), // (5,24): error CS0238: 'C1.P01' cannot be sealed because it is not an override // sealed static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_SealedNonOverride, "P01").WithArguments("C1.P01").WithLocation(5, 24), // (6,39): error CS0238: 'C1.E01' cannot be sealed because it is not an override // sealed static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_SealedNonOverride, "E01").WithArguments("C1.E01").WithLocation(6, 39), // (7,37): error CS0106: The modifier 'sealed' is not valid for this item // public sealed static C1 operator+ (C1 x) => null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("sealed").WithLocation(7, 37) ); } [Fact] public void AbstractStaticInStruct_01() { var source1 = @" struct C1 { public abstract static void M01(); public abstract static bool P01 { get; } public abstract static event System.Action E01; public abstract static C1 operator+ (C1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static void M01(); Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M01").WithArguments("abstract").WithLocation(4, 33), // (5,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P01").WithArguments("abstract").WithLocation(5, 33), // (6,48): error CS0112: A static member cannot be marked as 'abstract' // public abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "E01").WithArguments("abstract").WithLocation(6, 48), // (7,39): error CS0106: The modifier 'abstract' is not valid for this item // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("abstract").WithLocation(7, 39), // (7,39): error CS0501: 'C1.operator +(C1)' must declare a body because it is not marked abstract, extern, or partial // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("C1.operator +(C1)").WithLocation(7, 39) ); } [Fact] public void SealedStaticInStruct_01() { var source1 = @" struct C1 { sealed static void M01() {} sealed static bool P01 { get => false; } sealed static event System.Action E01 { add {} remove {} } public sealed static C1 operator+ (C1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0238: 'C1.M01()' cannot be sealed because it is not an override // sealed static void M01() {} Diagnostic(ErrorCode.ERR_SealedNonOverride, "M01").WithArguments("C1.M01()").WithLocation(4, 24), // (5,24): error CS0238: 'C1.P01' cannot be sealed because it is not an override // sealed static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_SealedNonOverride, "P01").WithArguments("C1.P01").WithLocation(5, 24), // (6,39): error CS0238: 'C1.E01' cannot be sealed because it is not an override // sealed static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_SealedNonOverride, "E01").WithArguments("C1.E01").WithLocation(6, 39), // (7,37): error CS0106: The modifier 'sealed' is not valid for this item // public sealed static C1 operator+ (C1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("sealed").WithLocation(7, 37) ); } [Fact] public void DefineAbstractStaticMethod_01() { var source1 = @" interface I1 { abstract static void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); } } [Fact] public void DefineAbstractStaticMethod_02() { var source1 = @" interface I1 { abstract static void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 26) ); } [Theory] [InlineData("I1", "+", "(I1 x)")] [InlineData("I1", "-", "(I1 x)")] [InlineData("I1", "!", "(I1 x)")] [InlineData("I1", "~", "(I1 x)")] [InlineData("I1", "++", "(I1 x)")] [InlineData("I1", "--", "(I1 x)")] [InlineData("I1", "+", "(I1 x, I1 y)")] [InlineData("I1", "-", "(I1 x, I1 y)")] [InlineData("I1", "*", "(I1 x, I1 y)")] [InlineData("I1", "/", "(I1 x, I1 y)")] [InlineData("I1", "%", "(I1 x, I1 y)")] [InlineData("I1", "&", "(I1 x, I1 y)")] [InlineData("I1", "|", "(I1 x, I1 y)")] [InlineData("I1", "^", "(I1 x, I1 y)")] [InlineData("I1", "<<", "(I1 x, int y)")] [InlineData("I1", ">>", "(I1 x, int y)")] public void DefineAbstractStaticOperator_01(string type, string op, string paramList) { var source1 = @" interface I1 { abstract static " + type + " operator " + op + " " + paramList + @"; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); } } [Fact] public void DefineAbstractStaticOperator_02() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); abstract static I1 operator > (I1 x, I1 y); abstract static I1 operator < (I1 x, I1 y); abstract static I1 operator >= (I1 x, I1 y); abstract static I1 operator <= (I1 x, I1 y); abstract static I1 operator == (I1 x, I1 y); abstract static I1 operator != (I1 x, I1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(8, count); } } [Theory] [InlineData("I1", "+", "(I1 x)")] [InlineData("I1", "-", "(I1 x)")] [InlineData("I1", "!", "(I1 x)")] [InlineData("I1", "~", "(I1 x)")] [InlineData("I1", "++", "(I1 x)")] [InlineData("I1", "--", "(I1 x)")] [InlineData("I1", "+", "(I1 x, I1 y)")] [InlineData("I1", "-", "(I1 x, I1 y)")] [InlineData("I1", "*", "(I1 x, I1 y)")] [InlineData("I1", "/", "(I1 x, I1 y)")] [InlineData("I1", "%", "(I1 x, I1 y)")] [InlineData("I1", "&", "(I1 x, I1 y)")] [InlineData("I1", "|", "(I1 x, I1 y)")] [InlineData("I1", "^", "(I1 x, I1 y)")] [InlineData("I1", "<<", "(I1 x, int y)")] [InlineData("I1", ">>", "(I1 x, int y)")] public void DefineAbstractStaticOperator_03(string type, string op, string paramList) { var source1 = @" interface I1 { abstract static " + type + " operator " + op + " " + paramList + @"; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator + (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 31 + type.Length) ); } [Fact] public void DefineAbstractStaticOperator_04() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); abstract static I1 operator > (I1 x, I1 y); abstract static I1 operator < (I1 x, I1 y); abstract static I1 operator >= (I1 x, I1 y); abstract static I1 operator <= (I1 x, I1 y); abstract static I1 operator == (I1 x, I1 y); abstract static I1 operator != (I1 x, I1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(4, 35), // (5,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(5, 35), // (6,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator > (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, ">").WithLocation(6, 33), // (7,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator < (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "<").WithLocation(7, 33), // (8,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator >= (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, ">=").WithLocation(8, 33), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator <= (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "<=").WithLocation(9, 33), // (10,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator == (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "==").WithLocation(10, 33), // (11,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator != (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "!=").WithLocation(11, 33) ); } [Fact] public void DefineAbstractStaticConversion_01() { var source1 = @" interface I1<T> where T : I1<T> { abstract static implicit operator int(T x); abstract static explicit operator T(int x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticConversion_03() { var source1 = @" interface I1<T> where T : I1<T> { abstract static implicit operator int(T x); abstract static explicit operator T(int x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 39), // (5,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator T(int x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T").WithLocation(5, 39) ); } [Fact] public void DefineAbstractStaticProperty_01() { var source1 = @" interface I1 { abstract static int P01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var p01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.True(p01.IsAbstract); Assert.False(p01.IsVirtual); Assert.False(p01.IsSealed); Assert.True(p01.IsStatic); Assert.False(p01.IsOverride); int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticProperty_02() { var source1 = @" interface I1 { abstract static int P01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(4, 31), // (4,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(4, 36) ); } [Fact] public void DefineAbstractStaticEvent_01() { var source1 = @" interface I1 { abstract static event System.Action E01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var e01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.True(e01.IsAbstract); Assert.False(e01.IsVirtual); Assert.False(e01.IsSealed); Assert.True(e01.IsStatic); Assert.False(e01.IsOverride); int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticEvent_02() { var source1 = @" interface I1 { abstract static event System.Action E01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "E01").WithLocation(4, 41) ); } [Fact] public void ConstraintChecks_01() { var source1 = @" public interface I1 { abstract static void M01(); } public interface I2 : I1 { } public interface I3 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var source2 = @" class C1<T1> where T1 : I1 { void Test(C1<I2> x) { } } class C2 { void M<T2>() where T2 : I1 {} void Test(C2 x) { x.M<I2>(); } } class C3<T3> where T3 : I2 { void Test(C3<I2> x, C3<I3> y) { } } class C4 { void M<T4>() where T4 : I2 {} void Test(C4 x) { x.M<I2>(); x.M<I3>(); } } class C5<T5> where T5 : I3 { void Test(C5<I3> y) { } } class C6 { void M<T6>() where T6 : I3 {} void Test(C6 x) { x.M<I3>(); } } class C7<T7> where T7 : I1 { void Test(C7<I1> y) { } } class C8 { void M<T8>() where T8 : I1 {} void Test(C8 x) { x.M<I1>(); } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); var expected = new[] { // (4,22): error CS8920: The interface 'I2' cannot be used as type parameter 'T1' in the generic type or method 'C1<T1>'. The constraint interface 'I1' or its base interface has static abstract members. // void Test(C1<I2> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "x").WithArguments("C1<T1>", "I1", "T1", "I2").WithLocation(4, 22), // (15,11): error CS8920: The interface 'I2' cannot be used as type parameter 'T2' in the generic type or method 'C2.M<T2>()'. The constraint interface 'I1' or its base interface has static abstract members. // x.M<I2>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I2>").WithArguments("C2.M<T2>()", "I1", "T2", "I2").WithLocation(15, 11), // (21,22): error CS8920: The interface 'I2' cannot be used as type parameter 'T3' in the generic type or method 'C3<T3>'. The constraint interface 'I2' or its base interface has static abstract members. // void Test(C3<I2> x, C3<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "x").WithArguments("C3<T3>", "I2", "T3", "I2").WithLocation(21, 22), // (21,32): error CS8920: The interface 'I3' cannot be used as type parameter 'T3' in the generic type or method 'C3<T3>'. The constraint interface 'I2' or its base interface has static abstract members. // void Test(C3<I2> x, C3<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C3<T3>", "I2", "T3", "I3").WithLocation(21, 32), // (32,11): error CS8920: The interface 'I2' cannot be used as type parameter 'T4' in the generic type or method 'C4.M<T4>()'. The constraint interface 'I2' or its base interface has static abstract members. // x.M<I2>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I2>").WithArguments("C4.M<T4>()", "I2", "T4", "I2").WithLocation(32, 11), // (33,11): error CS8920: The interface 'I3' cannot be used as type parameter 'T4' in the generic type or method 'C4.M<T4>()'. The constraint interface 'I2' or its base interface has static abstract members. // x.M<I3>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I3>").WithArguments("C4.M<T4>()", "I2", "T4", "I3").WithLocation(33, 11), // (39,22): error CS8920: The interface 'I3' cannot be used as type parameter 'T5' in the generic type or method 'C5<T5>'. The constraint interface 'I3' or its base interface has static abstract members. // void Test(C5<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C5<T5>", "I3", "T5", "I3").WithLocation(39, 22), // (50,11): error CS8920: The interface 'I3' cannot be used as type parameter 'T6' in the generic type or method 'C6.M<T6>()'. The constraint interface 'I3' or its base interface has static abstract members. // x.M<I3>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I3>").WithArguments("C6.M<T6>()", "I3", "T6", "I3").WithLocation(50, 11), // (56,22): error CS8920: The interface 'I1' cannot be used as type parameter 'T7' in the generic type or method 'C7<T7>'. The constraint interface 'I1' or its base interface has static abstract members. // void Test(C7<I1> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C7<T7>", "I1", "T7", "I1").WithLocation(56, 22), // (67,11): error CS8920: The interface 'I1' cannot be used as type parameter 'T8' in the generic type or method 'C8.M<T8>()'. The constraint interface 'I1' or its base interface has static abstract members. // x.M<I1>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I1>").WithArguments("C8.M<T8>()", "I1", "T8", "I1").WithLocation(67, 11) }; compilation2.VerifyDiagnostics(expected); compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.EmitToImageReference() }); compilation2.VerifyDiagnostics(expected); } [Fact] public void ConstraintChecks_02() { var source1 = @" public interface I1 { abstract static void M01(); } public class C : I1 { public static void M01() {} } public struct S : I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var source2 = @" class C1<T1> where T1 : I1 { void Test(C1<C> x, C1<S> y, C1<T1> z) { } } class C2 { public void M<T2>(C2 x) where T2 : I1 { x.M<T2>(x); } void Test(C2 x) { x.M<C>(x); x.M<S>(x); } } class C3<T3> where T3 : I1 { void Test(C1<T3> z) { } } class C4 { void M<T4>(C2 x) where T4 : I1 { x.M<T4>(x); } } class C5<T5> { internal virtual void M<U5>() where U5 : T5 { } } class C6 : C5<I1> { internal override void M<U6>() { base.M<U6>(); } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyEmitDiagnostics(); compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.EmitToImageReference() }); compilation2.VerifyEmitDiagnostics(); } [Fact] public void VarianceSafety_01() { var source1 = @" interface I2<out T1, in T2> { abstract static T1 P1 { get; } abstract static T2 P2 { get; } abstract static T1 P3 { set; } abstract static T2 P4 { set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,21): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.P2'. 'T2' is contravariant. // abstract static T2 P2 { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I2<T1, T2>.P2", "T2", "contravariant", "covariantly").WithLocation(5, 21), // (6,21): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.P3'. 'T1' is covariant. // abstract static T1 P3 { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I2<T1, T2>.P3", "T1", "covariant", "contravariantly").WithLocation(6, 21) ); } [Fact] public void VarianceSafety_02() { var source1 = @" interface I2<out T1, in T2> { abstract static T1 M1(); abstract static T2 M2(); abstract static void M3(T1 x); abstract static void M4(T2 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,21): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.M2()'. 'T2' is contravariant. // abstract static T2 M2(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I2<T1, T2>.M2()", "T2", "contravariant", "covariantly").WithLocation(5, 21), // (6,29): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.M3(T1)'. 'T1' is covariant. // abstract static void M3(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I2<T1, T2>.M3(T1)", "T1", "covariant", "contravariantly").WithLocation(6, 29) ); } [Fact] public void VarianceSafety_03() { var source1 = @" interface I2<out T1, in T2> { abstract static event System.Action<System.Func<T1>> E1; abstract static event System.Action<System.Func<T2>> E2; abstract static event System.Action<System.Action<T1>> E3; abstract static event System.Action<System.Action<T2>> E4; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,58): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.E2'. 'T2' is contravariant. // abstract static event System.Action<System.Func<T2>> E2; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E2").WithArguments("I2<T1, T2>.E2", "T2", "contravariant", "covariantly").WithLocation(5, 58), // (6,60): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.E3'. 'T1' is covariant. // abstract static event System.Action<System.Action<T1>> E3; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E3").WithArguments("I2<T1, T2>.E3", "T1", "covariant", "contravariantly").WithLocation(6, 60) ); } [Fact] public void VarianceSafety_04() { var source1 = @" interface I2<out T2> { abstract static int operator +(I2<T2> x); } interface I3<out T3> { abstract static int operator +(I3<T3> x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,36): error CS1961: Invalid variance: The type parameter 'T2' must be contravariantly valid on 'I2<T2>.operator +(I2<T2>)'. 'T2' is covariant. // abstract static int operator +(I2<T2> x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "I2<T2>").WithArguments("I2<T2>.operator +(I2<T2>)", "T2", "covariant", "contravariantly").WithLocation(4, 36), // (9,36): error CS1961: Invalid variance: The type parameter 'T3' must be contravariantly valid on 'I3<T3>.operator +(I3<T3>)'. 'T3' is covariant. // abstract static int operator +(I3<T3> x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "I3<T3>").WithArguments("I3<T3>.operator +(I3<T3>)", "T3", "covariant", "contravariantly").WithLocation(9, 36) ); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("!")] [InlineData("~")] [InlineData("true")] [InlineData("false")] public void OperatorSignature_01(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x); } interface I13 { static abstract bool operator " + op + @"(I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,26): error CS0562: The parameter of a unary operator must be the containing type // static bool operator +(T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0562: The parameter of a unary operator must be the containing type // static bool operator +(T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T5 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T71 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T8 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T10 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator false(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11)").WithLocation(47, 18), // (51,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator false(int x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [InlineData("++")] [InlineData("--")] public void OperatorSignature_02(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static T1 operator " + op + @"(T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static T2? operator " + op + @"(T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract T3 operator " + op + @"(T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract T4? operator " + op + @"(T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract T5 operator " + op + @"(T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract T71 operator " + op + @"(T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract T8 operator " + op + @"(T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract T10 operator " + op + @"(T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract int operator " + op + @"(int x); } interface I13 { static abstract I13 operator " + op + @"(I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0559: The parameter type for ++ or -- operator must be the containing type // static T1 operator ++(T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, op).WithLocation(4, 24), // (9,25): error CS0559: The parameter type for ++ or -- operator must be the containing type // static T2? operator ++(T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, op).WithLocation(9, 25), // (26,37): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T5 operator ++(T5 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(26, 37), // (32,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T71 operator ++(T71 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(32, 34), // (37,33): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T8 operator ++(T8 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(37, 33), // (44,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T10 operator ++(T10 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(44, 34), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator --(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11)").WithLocation(47, 18), // (51,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract int operator ++(int x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(51, 34) ); } [Theory] [InlineData("++")] [InlineData("--")] public void OperatorSignature_03(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static T1 operator " + op + @"(I1<T1> x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static T2? operator " + op + @"(I2<T2> x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract T3 operator " + op + @"(I3<T3> x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract T4? operator " + op + @"(I4<T4> x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract T5 operator " + op + @"(I6 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract T71 operator " + op + @"(I7<T71, T72> x); } interface I8<T8> where T8 : I9<T8> { static abstract T8 operator " + op + @"(I8<T8> x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract T10 operator " + op + @"(I10<T10> x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract int operator " + op + @"(I12 x); } interface I13<T13> where T13 : struct, I13<T13> { static abstract T13? operator " + op + @"(T13 x); } interface I14<T14> where T14 : struct, I14<T14> { static abstract T14 operator " + op + @"(T14? x); } interface I15<T151, T152> where T151 : I15<T151, T152> where T152 : I15<T151, T152> { static abstract T151 operator " + op + @"(T152 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // static T1 operator ++(I1<T1> x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecRetType, op).WithLocation(4, 24), // (9,25): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // static T2? operator ++(I2<T2> x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecRetType, op).WithLocation(9, 25), // (19,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T4? operator ++(I4<T4> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(19, 34), // (26,37): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T5 operator ++(I6 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(26, 37), // (32,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T71 operator ++(I7<T71, T72> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(32, 34), // (37,33): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T8 operator ++(I8<T8> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(37, 33), // (44,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T10 operator ++(I10<T10> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(44, 34), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator ++(I10<T11>)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(I10<T11>)").WithLocation(47, 18), // (51,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract int operator ++(I12 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(51, 34), // (56,35): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T13? operator ++(T13 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(56, 35), // (61,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T14 operator ++(T14? x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(61, 34), // (66,35): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T151 operator ++(T152 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(66, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x, bool y) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x, bool y) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x, bool y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x, bool y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x, bool y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x, bool y); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x, bool y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x, bool y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x, bool y); } interface I13 { static abstract bool operator " + op + @"(I13 x, bool y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators)).Verify( // (4,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(T1 x, bool y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(T2? x, bool y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T5 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T71 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T8 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T10 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator /(T11, bool)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11, bool)").WithLocation(47, 18), // (51,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(int x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_05([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(bool y, T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(bool y, T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(bool y, T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(bool y, T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(bool y, T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(bool y, T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(bool y, T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(bool y, T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(bool y, int x); } interface I13 { static abstract bool operator " + op + @"(bool y, I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators)).Verify( // (4,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(bool y, T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(bool y, T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T5 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T71 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T8 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T10 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator <=(bool, T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(bool, T11)").WithLocation(47, 18), // (51,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, int x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [InlineData("<<")] [InlineData(">>")] public void OperatorSignature_06(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x, int y) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x, int y) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x, int y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x, int y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x, int y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x, int y); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x, int y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x, int y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x, int y); } interface I13 { static abstract bool operator " + op + @"(I13 x, int y); } interface I14 { static abstract bool operator " + op + @"(I14 x, bool y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,26): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // static bool operator <<(T1 x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // static bool operator <<(T2? x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T5 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T71 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T8 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T10 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator >>(T11, int)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11, int)").WithLocation(47, 18), // (51,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(int x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(51, 35), // (61,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(I14 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(61, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_07([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { abstract static " + op + @" operator T1(T1 y); } interface I2<T2> where T2 : I2<T2> { abstract static " + op + @" operator dynamic(T2 y); } interface I3<T3> where T3 : I3<T3> { static abstract " + op + @" operator T3(bool y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract " + op + @" operator T4?(bool y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract " + op + @" operator T5 (bool y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract " + op + @" operator T71 (bool y); } interface I8<T8> where T8 : I9<T8> { static abstract " + op + @" operator T8(bool y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract " + op + @" operator T10(bool y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract " + op + @" operator int(bool y); } interface I13 { static abstract " + op + @" operator I13(bool y); } interface I14<T14> where T14 : I14<T14> { abstract static " + op + @" operator object(T14 y); } class C15 {} class C16 : C15 {} interface I17<T17> where T17 : C15, I17<T17> { abstract static " + op + @" operator C16(T17 y); } interface I18<T18> where T18 : C16, I18<T18> { abstract static " + op + @" operator C15(T18 y); } interface I19<T19_1, T19_2> where T19_1 : I19<T19_1, T19_2>, T19_2 { abstract static " + op + @" operator T19_1(T19_2 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0555: User-defined operator cannot convert a type to itself // abstract static explicit operator T1(T1 y); Diagnostic(ErrorCode.ERR_IdentityConversion, "T1").WithLocation(4, 39), // (9,39): error CS1964: 'I2<T2>.explicit operator dynamic(T2)': user-defined conversions to or from the dynamic type are not allowed // abstract static explicit operator dynamic(T2 y); Diagnostic(ErrorCode.ERR_BadDynamicConversion, "dynamic").WithArguments("I2<T2>." + op + " operator dynamic(T2)").WithLocation(9, 39), // (26,43): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T5 (bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T5").WithLocation(26, 43), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T71 (bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T71").WithLocation(32, 39), // (37,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T8(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T8").WithLocation(37, 39), // (44,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T10(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T10").WithLocation(44, 39), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.explicit operator T11(bool)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>." + op + " operator T11(bool)").WithLocation(47, 18), // (51,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator int(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "int").WithLocation(51, 39), // (56,39): error CS0552: 'I13.explicit operator I13(bool)': user-defined conversions to or from an interface are not allowed // static abstract explicit operator I13(bool y); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I13").WithArguments("I13." + op + " operator I13(bool)").WithLocation(56, 39) ); } [Theory] [CombinatorialData] public void OperatorSignature_08([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { abstract static " + op + @" operator T1(T1 y); } interface I2<T2> where T2 : I2<T2> { abstract static " + op + @" operator T2(dynamic y); } interface I3<T3> where T3 : I3<T3> { static abstract " + op + @" operator bool(T3 y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract " + op + @" operator bool(T4? y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract " + op + @" operator bool(T5 y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract " + op + @" operator bool(T71 y); } interface I8<T8> where T8 : I9<T8> { static abstract " + op + @" operator bool(T8 y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract " + op + @" operator bool(T10 y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract " + op + @" operator bool(int y); } interface I13 { static abstract " + op + @" operator bool(I13 y); } interface I14<T14> where T14 : I14<T14> { abstract static " + op + @" operator T14(object y); } class C15 {} class C16 : C15 {} interface I17<T17> where T17 : C15, I17<T17> { abstract static " + op + @" operator T17(C16 y); } interface I18<T18> where T18 : C16, I18<T18> { abstract static " + op + @" operator T18(C15 y); } interface I19<T19_1, T19_2> where T19_1 : I19<T19_1, T19_2>, T19_2 { abstract static " + op + @" operator T19_2(T19_1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0555: User-defined operator cannot convert a type to itself // abstract static explicit operator T1(T1 y); Diagnostic(ErrorCode.ERR_IdentityConversion, "T1").WithLocation(4, 39), // (9,39): error CS1964: 'I2<T2>.explicit operator T2(dynamic)': user-defined conversions to or from the dynamic type are not allowed // abstract static explicit operator T2(dynamic y); Diagnostic(ErrorCode.ERR_BadDynamicConversion, "T2").WithArguments("I2<T2>." + op + " operator T2(dynamic)").WithLocation(9, 39), // (26,43): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T5 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(26, 43), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T71 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(32, 39), // (37,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T8 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(37, 39), // (44,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T10 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(44, 39), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.explicit operator bool(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>." + op + " operator bool(T11)").WithLocation(47, 18), // (51,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(int y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(51, 39), // (56,39): error CS0552: 'I13.explicit operator bool(I13)': user-defined conversions to or from an interface are not allowed // static abstract explicit operator bool(I13 y); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "bool").WithArguments("I13." + op + " operator bool(I13)").WithLocation(56, 39) ); } [Fact] public void ConsumeAbstractStaticMethod_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { M01(); M04(); } void M03() { this.M01(); this.M04(); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { I1.M01(); x.M01(); I1.M04(); x.M04(); } static void MT2<T>() where T : I1 { T.M03(); T.M04(); T.M00(); T.M05(); _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.M01()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // M01(); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "M01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // this.M01(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // this.M04(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.M01(); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.M01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // x.M01(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // x.M04(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M03(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M04(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M00(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.M05()' is inaccessible due to its protection level // T.M05(); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 11), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.M01()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01()").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticMethod_02() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = nameof(M01); _ = nameof(M04); } void M03() { _ = nameof(this.M01); _ = nameof(this.M04); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = nameof(I1.M01); _ = nameof(x.M01); _ = nameof(I1.M04); _ = nameof(x.M04); } static void MT2<T>() where T : I1 { _ = nameof(T.M03); _ = nameof(T.M04); _ = nameof(T.M00); _ = nameof(T.M05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = nameof(T.M05); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticMethod_03() { var source1 = @" public interface I1 { abstract static void M01(); abstract static void M04(int x); } class Test { static void M02<T, U>() where T : U where U : I1 { T.M01(); } static string M03<T, U>() where T : U where U : I1 { return nameof(T.M01); } static async void M05<T, U>() where T : U where U : I1 { T.M04(await System.Threading.Tasks.Task.FromResult(1)); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 14 (0xe) .maxstack 0 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""void I1.M01()"" IL_000c: nop IL_000d: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""M01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 12 (0xc) .maxstack 0 IL_0000: constrained. ""T"" IL_0006: call ""void I1.M01()"" IL_000b: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""M01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("T.M01()", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IInvocationOperation (virtual void I1.M01()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'T.M01()') Instance Receiver: null Arguments(0) "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("void I1.M01()", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("M01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticMethod_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.M01(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.M01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_05() { var source1 = @" public interface I1 { abstract static I1 Select(System.Func<int, int> p); } class Test { static void M02<T>() where T : I1 { _ = from t in T select t + 1; _ = from t in I1 select t + 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); // https://github.com/dotnet/roslyn/issues/53796: Confirm whether we want to enable the 'from t in T' scenario. compilation1.VerifyDiagnostics( // (11,23): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = from t in T select t + 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(11, 23), // (12,26): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = from t in I1 select t + 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "select t + 1").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.M01(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.M01(); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.M01(); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_01(string prefixOp, string postfixOp) { var source1 = @" interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); abstract static I1<T> operator" + prefixOp + postfixOp + @" (I1<T> x); static void M02(I1<T> x) { _ = " + prefixOp + "x" + postfixOp + @"; } void M03(I1<T> y) { _ = " + prefixOp + "y" + postfixOp + @"; } } class Test<T> where T : I1<T> { static void MT1(I1<T> a) { _ = " + prefixOp + "a" + postfixOp + @"; } static void MT2() { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (" + prefixOp + "b" + postfixOp + @").ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "x" + postfixOp).WithLocation(8, 13), // (13,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "y" + postfixOp).WithLocation(13, 13), // (21,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "a" + postfixOp).WithLocation(21, 13), (prefixOp + postfixOp).Length == 1 ? // (26,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (-b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, prefixOp + "b" + postfixOp).WithLocation(26, 78) : // (26,78): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b--).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, prefixOp + "b" + postfixOp).WithLocation(26, 78) ); } [Theory] [InlineData("+", "", "op_UnaryPlus", "Plus")] [InlineData("-", "", "op_UnaryNegation", "Minus")] [InlineData("!", "", "op_LogicalNot", "Not")] [InlineData("~", "", "op_OnesComplement", "BitwiseNegation")] [InlineData("++", "", "op_Increment", "Increment")] [InlineData("--", "", "op_Decrement", "Decrement")] [InlineData("", "++", "op_Increment", "Increment")] [InlineData("", "--", "op_Decrement", "Decrement")] public void ConsumeAbstractUnaryOperator_03(string prefixOp, string postfixOp, string metadataName, string opKind) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } class Test { static T M02<T, U>(T x) where T : U where U : I1<T> { return " + prefixOp + "x" + postfixOp + @"; } static T? M03<T, U>(T? y) where T : struct, U where U : I1<T> { return " + prefixOp + "y" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 21 (0x15) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: dup IL_000e: starg.s V_0 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: dup IL_002f: starg.s V_0 IL_0031: stloc.2 IL_0032: br.s IL_0034 IL_0034: ldloc.2 IL_0035: ret } "); break; case ("", "++"): case ("", "--"): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 21 (0x15) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: dup IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T)"" IL_000e: starg.s V_0 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: dup IL_0003: stloc.0 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: brtrue.s IL_0018 IL_000d: ldloca.s V_1 IL_000f: initobj ""T?"" IL_0015: ldloc.1 IL_0016: br.s IL_002f IL_0018: ldloca.s V_0 IL_001a: call ""readonly T T?.GetValueOrDefault()"" IL_001f: constrained. ""T"" IL_0025: call ""T I1<T>." + metadataName + @"(T)"" IL_002a: newobj ""T?..ctor(T)"" IL_002f: starg.s V_0 IL_0031: stloc.2 IL_0032: br.s IL_0034 IL_0034: ldloc.2 IL_0035: ret } "); break; default: verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); break; } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(T)"" IL_000c: dup IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0016 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: br.s IL_002d IL_0016: ldloca.s V_0 IL_0018: call ""readonly T T?.GetValueOrDefault()"" IL_001d: constrained. ""T"" IL_0023: call ""T I1<T>." + metadataName + @"(T)"" IL_0028: newobj ""T?..ctor(T)"" IL_002d: dup IL_002e: starg.s V_0 IL_0030: ret } "); break; case ("", "++"): case ("", "--"): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: dup IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: starg.s V_0 IL_0030: ret } "); break; default: verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(T)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""T I1<T>." + metadataName + @"(T)"" IL_0027: newobj ""T?..ctor(T)"" IL_002c: ret } "); break; } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = postfixOp != "" ? (ExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().First() : tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().First(); Assert.Equal(prefixOp + "x" + postfixOp, node.ToString()); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): case ("", "++"): case ("", "--"): VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IIncrementOrDecrementOperation (" + (prefixOp != "" ? "Prefix" : "Postfix") + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x)) (OperationKind." + opKind + @", Type: T) (Syntax: '" + prefixOp + "x" + postfixOp + @"') Target: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); break; default: VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IUnaryOperation (UnaryOperatorKind." + opKind + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x)) (OperationKind.Unary, Type: T) (Syntax: '" + prefixOp + "x" + postfixOp + @"') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); break; } } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_04(string prefixOp, string postfixOp) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1<T> { _ = " + prefixOp + "x" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = -x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, prefixOp + "x" + postfixOp).WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator- (T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, prefixOp + postfixOp).WithLocation(12, 31) ); } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_06(string prefixOp, string postfixOp) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1<T> { _ = " + prefixOp + "x" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = -x; Diagnostic(ErrorCode.ERR_FeatureInPreview, prefixOp + "x" + postfixOp).WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,31): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator- (T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, prefixOp + postfixOp).WithArguments("abstract", "9.0", "preview").WithLocation(12, 31) ); } [Fact] public void ConsumeAbstractTrueOperator_01() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); static void M02(I1 x) { _ = x ? true : false; } void M03(I1 y) { _ = y ? true : false; } } class Test { static void MT1(I1 a) { _ = a ? true : false; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b ? true : false).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x").WithLocation(9, 13), // (14,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y").WithLocation(14, 13), // (22,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a").WithLocation(22, 13), // (27,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b ? true : false).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b").WithLocation(27, 78) ); } [Fact] public void ConsumeAbstractTrueOperator_03() { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator true (T x); abstract static bool operator false (T x); } class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>.op_True(T)"" IL_000d: brtrue.s IL_0011 IL_000f: br.s IL_0011 IL_0011: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""bool I1<T>.op_True(T)"" IL_000c: pop IL_000d: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalExpressionSyntax>().First(); Assert.Equal("x ? true : false", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IConditionalOperation (OperationKind.Conditional, Type: System.Boolean) (Syntax: 'x ? true : false') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean I1<T>.op_True(T x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') WhenTrue: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') WhenFalse: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') "); } [Fact] public void ConsumeAbstractTrueOperator_04() { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1 { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(12, 35), // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(13, 35) ); } [Fact] public void ConsumeAbstractTrueOperator_06() { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1 { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(12, 35), // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); static void M02((int, C<I1>) x) { _ = x " + op + @" x; } void M03((int, C<I1>) y) { _ = y " + op + @" y; } } class Test { static void MT1((int, C<I1>) a) { _ = a " + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b " + op + @" b).ToString()); } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x == x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " x").WithLocation(9, 13), // (14,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y == y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " y").WithLocation(14, 13), // (22,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a == a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " a").WithLocation(22, 13), // (27,98): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(27, 98) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator true (T x); abstract static bool operator false (T x); } class Test { static void M02<T, U>((int, C<T>) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 55 (0x37) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0034 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_False(T)"" IL_002f: ldc.i4.0 IL_0030: ceq IL_0032: br.s IL_0035 IL_0034: ldc.i4.0 IL_0035: pop IL_0036: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_True(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.1 IL_0032: pop IL_0033: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0033 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_False(T)"" IL_002e: ldc.i4.0 IL_002f: ceq IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: pop IL_0035: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_True(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.1 IL_0031: pop IL_0032: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1 { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (21,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(21, 35), // (22,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(22, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1 { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (21,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(21, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" partial interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); static void M02(I1 x) { _ = x " + op + @" 1; } void M03(I1 y) { _ = y " + op + @" 2; } } class Test { static void MT1(I1 a) { _ = a " + op + @" 3; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + @" 4).ToString()); } } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator" + matchingOp + @" (I1 x, int y); } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x - 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " 1").WithLocation(8, 13), // (13,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y - 2; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " 2").WithLocation(13, 13), // (21,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a - 3; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " 3").WithLocation(21, 13), // (26,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b - 4).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b " + op + " 4").WithLocation(26, 78) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_01(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" static void M02(I1 x) { _ = x " + op + op + @" x; } void M03(I1 y) { _ = y " + op + op + @" y; } } class Test { static void MT1(I1 a) { _ = a " + op + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + op + @" b).ToString()); } static void MT3(I1 b, dynamic c) { _ = b " + op + op + @" c; } "; if (!success) { source1 += @" static void MT4<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T, dynamic>>)((T d, dynamic e) => (d " + op + op + @" e).ToString()); } "; } source1 += @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); if (success) { Assert.False(binaryIsAbstract); Assert.False(op == "&" ? falseIsAbstract : trueIsAbstract); var binaryMetadataName = op == "&" ? "op_BitwiseAnd" : "op_BitwiseOr"; var unaryMetadataName = op == "&" ? "op_False" : "op_True"; var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.MT1(I1)", @" { // Code size 22 (0x16) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0009: brtrue.s IL_0015 IL_000b: ldloc.0 IL_000c: ldarg.0 IL_000d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0012: pop IL_0013: br.s IL_0015 IL_0015: ret } "); if (op == "&") { verifier.VerifyIL("Test.MT3(I1, dynamic)", @" { // Code size 97 (0x61) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""bool I1.op_False(I1)"" IL_0007: brtrue.s IL_0060 IL_0009: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_000e: brfalse.s IL_0012 IL_0010: br.s IL_0047 IL_0012: ldc.i4.8 IL_0013: ldc.i4.2 IL_0014: ldtoken ""Test"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.2 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.1 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: dup IL_002f: ldc.i4.1 IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0037: stelem.ref IL_0038: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0042: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_004c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Target"" IL_0051: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0056: ldarg.0 IL_0057: ldarg.1 IL_0058: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, I1, dynamic)"" IL_005d: pop IL_005e: br.s IL_0060 IL_0060: ret } "); } else { verifier.VerifyIL("Test.MT3(I1, dynamic)", @" { // Code size 98 (0x62) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""bool I1.op_True(I1)"" IL_0007: brtrue.s IL_0061 IL_0009: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_000e: brfalse.s IL_0012 IL_0010: br.s IL_0048 IL_0012: ldc.i4.8 IL_0013: ldc.i4.s 36 IL_0015: ldtoken ""Test"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: ldc.i4.2 IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0025: dup IL_0026: ldc.i4.0 IL_0027: ldc.i4.1 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: dup IL_0030: ldc.i4.1 IL_0031: ldc.i4.0 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003e: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0043: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_004d: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Target"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0057: ldarg.0 IL_0058: ldarg.1 IL_0059: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, I1, dynamic)"" IL_005e: pop IL_005f: br.s IL_0061 IL_0061: ret } "); } } else { var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); builder.AddRange( // (10,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x && x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + op + " x").WithLocation(10, 13), // (15,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y && y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + op + " y").WithLocation(15, 13), // (23,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a && a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + op + " a").WithLocation(23, 13), // (28,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b && b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b " + op + op + " b").WithLocation(28, 78) ); if (op == "&" ? falseIsAbstract : trueIsAbstract) { builder.Add( // (33,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = b || c; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "b " + op + op + " c").WithLocation(33, 13) ); } builder.Add( // (38,98): error CS7083: Expression must be implicitly convertible to Boolean or its type 'T' must define operator 'true'. // _ = (System.Linq.Expressions.Expression<System.Action<T, dynamic>>)((T d, dynamic e) => (d || e).ToString()); Diagnostic(ErrorCode.ERR_InvalidDynamicCondition, "d").WithArguments("T", op == "&" ? "false" : "true").WithLocation(38, 98) ); compilation1.VerifyDiagnostics(builder.ToArrayAndFree()); } } [Theory] [CombinatorialData] public void ConsumeAbstractCompoundBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>")] string op) { var source1 = @" interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); static void M02(I1 x) { x " + op + @"= 1; } void M03(I1 y) { y " + op + @"= 2; } } interface I2<T> where T : I2<T> { abstract static T operator" + op + @" (T x, int y); } class Test { static void MT1(I1 a) { a " + op + @"= 3; } static void MT2<T>() where T : I2<T> { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + @"= 4).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x /= 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + "= 1").WithLocation(8, 9), // (13,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // y /= 2; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + "= 2").WithLocation(13, 9), // (26,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // a /= 3; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + "= 3").WithLocation(26, 9), // (31,78): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b /= 4).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b " + op + "= 4").WithLocation(31, 78) ); } private static string BinaryOperatorKind(string op) { switch (op) { case "+": return "Add"; case "-": return "Subtract"; case "*": return "Multiply"; case "/": return "Divide"; case "%": return "Remainder"; case "<<": return "LeftShift"; case ">>": return "RightShift"; case "&": return "And"; case "|": return "Or"; case "^": return "ExclusiveOr"; case "<": return "LessThan"; case "<=": return "LessThanOrEqual"; case "==": return "Equals"; case "!=": return "NotEquals"; case ">=": return "GreaterThanOrEqual"; case ">": return "GreaterThan"; } throw TestExceptionUtilities.UnexpectedValue(op); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); abstract static bool operator == (I1<T> x, I1<T> y); abstract static bool operator != (I1<T> x, I1<T> y); static void M02((int, I1<T>) x) { _ = x " + op + @" x; } void M03((int, I1<T>) y) { _ = y " + op + @" y; } } class Test { static void MT1<T>((int, I1<T>) a) where T : I1<T> { _ = a " + op + @" a; } static void MT2<T>() where T : I1<T> { _ = (System.Linq.Expressions.Expression<System.Action<(int, T)>>)(((int, T) b) => (b " + op + @" b).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x == x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " x").WithLocation(12, 13), // (17,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y == y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " y").WithLocation(17, 13), // (25,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a == a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " a").WithLocation(25, 13), // (30,92): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, T)>>)(((int, T) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(30, 92) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_03([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>")] string op) { string metadataName = BinaryOperatorName(op); bool isShiftOperator = op is "<<" or ">>"; var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static T0 operator" + op + @" (T0 x, int a); } partial class Test { static void M03<T, U>(T x) where T : U where U : I1<T> { _ = x " + op + @" 1; } static void M05<T, U>(T? y) where T : struct, U where U : I1<T> { _ = y " + op + @" 1; } } "; if (!isShiftOperator) { source1 += @" public partial interface I1<T0> { abstract static T0 operator" + op + @" (int a, T0 x); abstract static T0 operator" + op + @" (I1<T0> x, T0 a); abstract static T0 operator" + op + @" (T0 x, I1<T0> a); } partial class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = 1 " + op + @" x; } static void M04<T, U>(T? y) where T : struct, U where U : I1<T> { _ = 1 " + op + @" y; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { _ = x " + op + @" y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { _ = x " + op + @" y; } } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldarg.0 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(int, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_000e IL_000c: br.s IL_0022 IL_000e: ldc.i4.1 IL_000f: ldloca.s V_0 IL_0011: call ""readonly T T?.GetValueOrDefault()"" IL_0016: constrained. ""T"" IL_001c: call ""T I1<T>." + metadataName + @"(int, T)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: pop IL_000f: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_000e IL_000c: br.s IL_0022 IL_000e: ldloca.s V_0 IL_0010: call ""readonly T T?.GetValueOrDefault()"" IL_0015: ldc.i4.1 IL_0016: constrained. ""T"" IL_001c: call ""T I1<T>." + metadataName + @"(T, int)"" IL_0021: pop IL_0022: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 32 (0x20) .maxstack 2 .locals init (T? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brfalse.s IL_001f IL_000b: ldc.i4.1 IL_000c: ldloca.s V_0 IL_000e: call ""readonly T T?.GetValueOrDefault()"" IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + metadataName + @"(int, T)"" IL_001e: pop IL_001f: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: pop IL_000e: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 32 (0x20) .maxstack 2 .locals init (T? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brfalse.s IL_001f IL_000b: ldloca.s V_0 IL_000d: call ""readonly T T?.GetValueOrDefault()"" IL_0012: ldc.i4.1 IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + metadataName + @"(T, int)"" IL_001e: pop IL_001f: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " 1").Single(); Assert.Equal("x " + op + " 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.Binary, Type: T) (Syntax: 'x " + op + @" 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractComparisonBinaryOperator_03([CombinatorialValues("<", ">", "<=", ">=", "==", "!=")] string op) { string metadataName = BinaryOperatorName(op); var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static bool operator" + op + @" (T0 x, int a); abstract static bool operator" + op + @" (int a, T0 x); abstract static bool operator" + op + @" (I1<T0> x, T0 a); abstract static bool operator" + op + @" (T0 x, I1<T0> a); } partial class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = 1 " + op + @" x; } static void M03<T, U>(T x) where T : U where U : I1<T> { _ = x " + op + @" 1; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { _ = x " + op + @" y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { _ = x " + op + @" y; } } "; string matchingOp = MatchingBinaryOperator(op); source1 += @" public partial interface I1<T0> { abstract static bool operator" + matchingOp + @" (T0 x, int a); abstract static bool operator" + matchingOp + @" (int a, T0 x); abstract static bool operator" + matchingOp + @" (I1<T0> x, T0 a); abstract static bool operator" + matchingOp + @" (T0 x, I1<T0> a); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldarg.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(int, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(T, int)"" IL_000e: pop IL_000f: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(int, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(T, int)"" IL_000d: pop IL_000e: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " 1").Single(); Assert.Equal("x " + op + " 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @") (OperatorMethod: System.Boolean I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x " + op + @" 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractLiftedComparisonBinaryOperator_03([CombinatorialValues("<", ">", "<=", ">=", "==", "!=")] string op) { string metadataName = BinaryOperatorName(op); var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static bool operator" + op + @" (T0 x, T0 a); } partial class Test { static void M04<T, U>(T? x, T? y) where T : struct, U where U : I1<T> { _ = x " + op + @" y; } } "; string matchingOp = MatchingBinaryOperator(op); source1 += @" public partial interface I1<T0> { abstract static bool operator" + matchingOp + @" (T0 x, T0 a); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op is "==" or "!=") { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 61 (0x3d) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool T?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: beq.s IL_0017 IL_0015: br.s IL_003c IL_0017: ldloca.s V_0 IL_0019: call ""readonly bool T?.HasValue.get"" IL_001e: brtrue.s IL_0022 IL_0020: br.s IL_003c IL_0022: ldloca.s V_0 IL_0024: call ""readonly T T?.GetValueOrDefault()"" IL_0029: ldloca.s V_1 IL_002b: call ""readonly T T?.GetValueOrDefault()"" IL_0030: constrained. ""T"" IL_0036: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_003b: pop IL_003c: ret } "); } else { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool T?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: and IL_0014: brtrue.s IL_0018 IL_0016: br.s IL_0032 IL_0018: ldloca.s V_0 IL_001a: call ""readonly T T?.GetValueOrDefault()"" IL_001f: ldloca.s V_1 IL_0021: call ""readonly T T?.GetValueOrDefault()"" IL_0026: constrained. ""T"" IL_002c: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_0031: pop IL_0032: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op is "==" or "!=") { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 56 (0x38) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: bne.un.s IL_0037 IL_0014: ldloca.s V_0 IL_0016: call ""readonly bool T?.HasValue.get"" IL_001b: brfalse.s IL_0037 IL_001d: ldloca.s V_0 IL_001f: call ""readonly T T?.GetValueOrDefault()"" IL_0024: ldloca.s V_1 IL_0026: call ""readonly T T?.GetValueOrDefault()"" IL_002b: constrained. ""T"" IL_0031: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_0036: pop IL_0037: ret } "); } else { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 48 (0x30) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: and IL_0013: brfalse.s IL_002f IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: ldloca.s V_1 IL_001e: call ""readonly T T?.GetValueOrDefault()"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_002e: pop IL_002f: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " y").Single(); Assert.Equal("x " + op + " y", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @", IsLifted) (OperatorMethod: System.Boolean I1<T>." + metadataName + @"(T x, T a)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x " + op + @" y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T?) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T?) (Syntax: 'y') "); } [Theory] [InlineData("&", true, true)] [InlineData("|", true, true)] [InlineData("&", true, false)] [InlineData("|", true, false)] [InlineData("&", false, true)] [InlineData("|", false, true)] public void ConsumeAbstractLogicalBinaryOperator_03(string op, bool binaryIsAbstract, bool unaryIsAbstract) { var binaryMetadataName = op == "&" ? "op_BitwiseAnd" : "op_BitwiseOr"; var unaryMetadataName = op == "&" ? "op_False" : "op_True"; var opKind = op == "&" ? "ConditionalAnd" : "ConditionalOr"; if (binaryIsAbstract && unaryIsAbstract) { consumeAbstract(op); } else { consumeMixed(op, binaryIsAbstract, unaryIsAbstract); } void consumeAbstract(string op) { var source1 = @" public interface I1<T0> where T0 : I1<T0> { abstract static T0 operator" + op + @" (T0 a, T0 x); abstract static bool operator true (T0 x); abstract static bool operator false (T0 x); } public interface I2<T0> where T0 : struct, I2<T0> { abstract static T0 operator" + op + @" (T0 a, T0 x); abstract static bool operator true (T0? x); abstract static bool operator false (T0? x); } class Test { static void M03<T, U>(T x, T y) where T : U where U : I1<T> { _ = x " + op + op + @" y; } static void M04<T, U>(T? x, T? y) where T : struct, U where U : I2<T> { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 34 (0x22) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: constrained. ""T"" IL_000a: call ""bool I1<T>." + unaryMetadataName + @"(T)"" IL_000f: brtrue.s IL_0021 IL_0011: ldloc.0 IL_0012: ldarg.1 IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + binaryMetadataName + @"(T, T)"" IL_001e: pop IL_001f: br.s IL_0021 IL_0021: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 69 (0x45) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: constrained. ""T"" IL_000a: call ""bool I2<T>." + unaryMetadataName + @"(T?)"" IL_000f: brtrue.s IL_0044 IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldarg.1 IL_0014: stloc.2 IL_0015: ldloca.s V_1 IL_0017: call ""readonly bool T?.HasValue.get"" IL_001c: ldloca.s V_2 IL_001e: call ""readonly bool T?.HasValue.get"" IL_0023: and IL_0024: brtrue.s IL_0028 IL_0026: br.s IL_0042 IL_0028: ldloca.s V_1 IL_002a: call ""readonly T T?.GetValueOrDefault()"" IL_002f: ldloca.s V_2 IL_0031: call ""readonly T T?.GetValueOrDefault()"" IL_0036: constrained. ""T"" IL_003c: call ""T I2<T>." + binaryMetadataName + @"(T, T)"" IL_0041: pop IL_0042: br.s IL_0044 IL_0044: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + unaryMetadataName + @"(T)"" IL_000e: brtrue.s IL_001e IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: constrained. ""T"" IL_0018: call ""T I1<T>." + binaryMetadataName + @"(T, T)"" IL_001d: pop IL_001e: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 64 (0x40) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I2<T>." + unaryMetadataName + @"(T?)"" IL_000e: brtrue.s IL_003f IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: ldarg.1 IL_0013: stloc.2 IL_0014: ldloca.s V_1 IL_0016: call ""readonly bool T?.HasValue.get"" IL_001b: ldloca.s V_2 IL_001d: call ""readonly bool T?.HasValue.get"" IL_0022: and IL_0023: brfalse.s IL_003f IL_0025: ldloca.s V_1 IL_0027: call ""readonly T T?.GetValueOrDefault()"" IL_002c: ldloca.s V_2 IL_002e: call ""readonly T T?.GetValueOrDefault()"" IL_0033: constrained. ""T"" IL_0039: call ""T I2<T>." + binaryMetadataName + @"(T, T)"" IL_003e: pop IL_003f: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + op + " y").First(); Assert.Equal("x " + op + op + " y", node1.ToString()); VerifyOperationTreeForNode(compilation1, model, node1, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + opKind + @") (OperatorMethod: T I1<T>." + binaryMetadataName + @"(T a, T x)) (OperationKind.Binary, Type: T) (Syntax: 'x " + op + op + @" y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T) (Syntax: 'y') "); } void consumeMixed(string op, bool binaryIsAbstract, bool unaryIsAbstract) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 a, I1 x)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (unaryIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (unaryIsAbstract ? ";" : " => throw null;") + @" " + (unaryIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (unaryIsAbstract ? ";" : " => throw null;") + @" } class Test { static void M03<T, U>(T x, T y) where T : U where U : I1 { _ = x " + op + op + @" y; } static void M04<T, U>(T? x, T? y) where T : struct, U where U : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch (binaryIsAbstract, unaryIsAbstract) { case (true, false): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000e: brtrue.s IL_0025 IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: box ""T"" IL_0017: constrained. ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T?"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000e: brtrue.s IL_0025 IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: box ""T?"" IL_0017: constrained. ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); break; case (false, true): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: constrained. ""T"" IL_000f: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldarg.1 IL_0018: box ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T?"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: constrained. ""T"" IL_000f: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldarg.1 IL_0018: box ""T?"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); break; default: Assert.True(false); break; } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch (binaryIsAbstract, unaryIsAbstract) { case (true, false): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000d: brtrue.s IL_0022 IL_000f: ldloc.0 IL_0010: ldarg.1 IL_0011: box ""T"" IL_0016: constrained. ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000d: brtrue.s IL_0022 IL_000f: ldloc.0 IL_0010: ldarg.1 IL_0011: box ""T?"" IL_0016: constrained. ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); break; case (false, true): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: constrained. ""T"" IL_000e: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0013: brtrue.s IL_0022 IL_0015: ldloc.0 IL_0016: ldarg.1 IL_0017: box ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: constrained. ""T"" IL_000e: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0013: brtrue.s IL_0022 IL_0015: ldloc.0 IL_0016: ldarg.1 IL_0017: box ""T?"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); break; default: Assert.True(false); break; } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + op + " y").First(); Assert.Equal("x " + op + op + " y", node1.ToString()); VerifyOperationTreeForNode(compilation1, model, node1, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + opKind + @") (OperatorMethod: I1 I1." + binaryMetadataName + @"(I1 a, I1 x)) (OperationKind.Binary, Type: I1) (Syntax: 'x " + op + op + @" y') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: I1, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: I1, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T) (Syntax: 'y') "); } } [Theory] [InlineData("+", "op_Addition", "Add")] [InlineData("-", "op_Subtraction", "Subtract")] [InlineData("*", "op_Multiply", "Multiply")] [InlineData("/", "op_Division", "Divide")] [InlineData("%", "op_Modulus", "Remainder")] [InlineData("&", "op_BitwiseAnd", "And")] [InlineData("|", "op_BitwiseOr", "Or")] [InlineData("^", "op_ExclusiveOr", "ExclusiveOr")] [InlineData("<<", "op_LeftShift", "LeftShift")] [InlineData(">>", "op_RightShift", "RightShift")] public void ConsumeAbstractCompoundBinaryOperator_03(string op, string metadataName, string operatorKind) { bool isShiftOperator = op.Length == 2; var source1 = @" public interface I1<T0> where T0 : I1<T0> { "; if (!isShiftOperator) { source1 += @" abstract static int operator" + op + @" (int a, T0 x); abstract static I1<T0> operator" + op + @" (I1<T0> x, T0 a); abstract static T0 operator" + op + @" (T0 x, I1<T0> a); "; } source1 += @" abstract static T0 operator" + op + @" (T0 x, int a); } class Test { "; if (!isShiftOperator) { source1 += @" static void M02<T, U>(int a, T x) where T : U where U : I1<T> { a " + op + @"= x; } static void M04<T, U>(int? a, T? y) where T : struct, U where U : I1<T> { a " + op + @"= y; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { x " + op + @"= y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { x " + op + @"= y; } "; } source1 += @" static void M03<T, U>(T x) where T : U where U : I1<T> { x " + op + @"= 1; } static void M05<T, U>(T? y) where T : struct, U where U : I1<T> { y " + op + @"= 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(int, T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""int I1<T>." + metadataName + @"(int, T)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?, T?)", @" { // Code size 66 (0x42) .maxstack 2 .locals init (int? V_0, T? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool int?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: and IL_0014: brtrue.s IL_0021 IL_0016: ldloca.s V_2 IL_0018: initobj ""int?"" IL_001e: ldloc.2 IL_001f: br.s IL_003f IL_0021: ldloca.s V_0 IL_0023: call ""readonly int int?.GetValueOrDefault()"" IL_0028: ldloca.s V_1 IL_002a: call ""readonly T T?.GetValueOrDefault()"" IL_002f: constrained. ""T"" IL_0035: call ""int I1<T>." + metadataName + @"(int, T)"" IL_003a: newobj ""int?..ctor(int)"" IL_003f: starg.s V_0 IL_0041: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""I1<T> I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: starg.s V_0 IL_0010: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 50 (0x32) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002f IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: ldc.i4.1 IL_001f: constrained. ""T"" IL_0025: call ""T I1<T>." + metadataName + @"(T, int)"" IL_002a: newobj ""T?..ctor(T)"" IL_002f: starg.s V_0 IL_0031: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(int, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(int, T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?, T?)", @" { // Code size 65 (0x41) .maxstack 2 .locals init (int? V_0, T? V_1, int? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool int?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: and IL_0013: brtrue.s IL_0020 IL_0015: ldloca.s V_2 IL_0017: initobj ""int?"" IL_001d: ldloc.2 IL_001e: br.s IL_003e IL_0020: ldloca.s V_0 IL_0022: call ""readonly int int?.GetValueOrDefault()"" IL_0027: ldloca.s V_1 IL_0029: call ""readonly T T?.GetValueOrDefault()"" IL_002e: constrained. ""T"" IL_0034: call ""int I1<T>." + metadataName + @"(int, T)"" IL_0039: newobj ""int?..ctor(int)"" IL_003e: starg.s V_0 IL_0040: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""I1<T> I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: starg.s V_0 IL_000f: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0016 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: br.s IL_002e IL_0016: ldloca.s V_0 IL_0018: call ""readonly T T?.GetValueOrDefault()"" IL_001d: ldc.i4.1 IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T, int)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: starg.s V_0 IL_0030: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(n => n.ToString() == "x " + op + "= 1").Single(); Assert.Equal("x " + op + "= 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" ICompoundAssignmentOperation (BinaryOperatorKind." + operatorKind + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.CompoundAssignment, Type: T) (Syntax: 'x " + op + @"= 1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } class Test { static void M02<T, U>((int, T) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0011: bne.un.s IL_002c IL_0013: ldloc.0 IL_0014: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001f: constrained. ""T"" IL_0025: call ""bool I1<T>.op_Equality(T, T)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.0 IL_002d: pop IL_002e: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0011: bne.un.s IL_002c IL_0013: ldloc.0 IL_0014: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001f: constrained. ""T"" IL_0025: call ""bool I1<T>.op_Inequality(T, T)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.1 IL_002d: pop IL_002e: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0010: bne.un.s IL_002b IL_0012: ldloc.0 IL_0013: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001e: constrained. ""T"" IL_0024: call ""bool I1<T>.op_Equality(T, T)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0010: bne.un.s IL_002b IL_0012: ldloc.0 IL_0013: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001e: constrained. ""T"" IL_0024: call ""bool I1<T>.op_Inequality(T, T)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.1 IL_002c: pop IL_002d: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, T)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, T)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1 { _ = x " + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x - y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " y").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator- (I1 x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 32) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_04(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" } "; var source2 = @" class Test { static void M02<T>(T x, T y) where T : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); if (success) { compilation2.VerifyDiagnostics(); } else { compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x && y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + op + " y").WithLocation(6, 13) ); } var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); if (binaryIsAbstract) { builder.Add( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator& (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 32) ); } if (trueIsAbstract) { builder.Add( // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(13, 35) ); } if (falseIsAbstract) { builder.Add( // (14,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(14, 35) ); } compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation).Verify(builder.ToArrayAndFree()); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("*")] [InlineData("/")] [InlineData("%")] [InlineData("&")] [InlineData("|")] [InlineData("^")] [InlineData("<<")] [InlineData(">>")] public void ConsumeAbstractCompoundBinaryOperator_04(string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + op + @" (T x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1<T> { x " + op + @"= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // x *= y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + "= y").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator* (T x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 31) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } "; var source2 = @" class Test { static void M02<T>((int, T) x) where T : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator == (T x, T y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "==").WithLocation(12, 35), // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator != (T x, T y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "!=").WithLocation(13, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_06([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1 { _ = x " + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x - y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " y").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator- (I1 x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 32) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_06(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" } "; var source2 = @" class Test { static void M02<T>(T x, T y) where T : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); if (success) { compilation2.VerifyDiagnostics(); } else { compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x && y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + op + " y").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); } var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); if (binaryIsAbstract) { builder.Add( // (12,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator& (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 32) ); } if (trueIsAbstract) { builder.Add( // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } if (falseIsAbstract) { builder.Add( // (14,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(14, 35) ); } compilation3.VerifyDiagnostics(builder.ToArrayAndFree()); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("*")] [InlineData("/")] [InlineData("%")] [InlineData("&")] [InlineData("|")] [InlineData("^")] [InlineData("<<")] [InlineData(">>")] public void ConsumeAbstractCompoundBinaryOperator_06(string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + op + @" (T x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1<T> { x " + op + @"= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x <<= y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + "= y").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,31): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator<< (T x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 31) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } "; var source2 = @" class Test { static void M02<T>((int, T) x) where T : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator == (T x, T y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(12, 35), // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator != (T x, T y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { _ = P01; _ = P04; } void M03() { _ = this.P01; _ = this.P04; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { _ = I1.P01; _ = x.P01; _ = I1.P04; _ = x.P04; } static void MT2<T>() where T : I1 { _ = T.P03; _ = T.P04; _ = T.P00; _ = T.P05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01.ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = P01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 13), // (14,13): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = this.P01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 13), // (15,13): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = this.P04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 13), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = I1.P01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 13), // (28,13): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = x.P01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 13), // (30,13): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = x.P04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 13), // (35,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 13), // (36,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 13), // (37,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 13), // (38,15): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = T.P05; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 15), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01.ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticPropertySet_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { P01 = 1; P04 = 1; } void M03() { this.P01 = 1; this.P04 = 1; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { I1.P01 = 1; x.P01 = 1; I1.P04 = 1; x.P04 = 1; } static void MT2<T>() where T : I1 { T.P03 = 1; T.P04 = 1; T.P00 = 1; T.P05 = 1; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 = 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 = 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 = 1; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 = 1").WithLocation(40, 71), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { P01 += 1; P04 += 1; } void M03() { this.P01 += 1; this.P04 += 1; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { I1.P01 += 1; x.P01 += 1; I1.P04 += 1; x.P04 += 1; } static void MT2<T>() where T : I1 { T.P03 += 1; T.P04 += 1; T.P00 += 1; T.P05 += 1; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 += 1; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 += 1").WithLocation(40, 71), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticProperty_02() { var source1 = @" interface I1 { abstract static int P01 { get; set; } static void M02() { _ = nameof(P01); _ = nameof(P04); } void M03() { _ = nameof(this.P01); _ = nameof(this.P04); } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { _ = nameof(I1.P01); _ = nameof(x.P01); _ = nameof(I1.P04); _ = nameof(x.P04); } static void MT2<T>() where T : I1 { _ = nameof(T.P03); _ = nameof(T.P04); _ = nameof(T.P00); _ = nameof(T.P05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (14,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 20), // (15,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 20), // (28,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 20), // (30,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 20), // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = nameof(T.P05); Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""int I1.P01.get"" IL_000c: pop IL_000d: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: constrained. ""T"" IL_0006: call ""int I1.P01.get"" IL_000b: pop IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Right; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertySet_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 15 (0xf) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""void I1.P01.set"" IL_000d: nop IL_000e: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: constrained. ""T"" IL_0007: call ""void I1.P01.set"" IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertyCompound_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { T.P01 += 1; } static string M03<T, U>() where T : U where U : I1 { return nameof(T.P01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""int I1.P01.get"" IL_000c: ldc.i4.1 IL_000d: add IL_000e: constrained. ""T"" IL_0014: call ""void I1.P01.set"" IL_0019: nop IL_001a: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""P01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: constrained. ""T"" IL_0006: call ""int I1.P01.get"" IL_000b: ldc.i4.1 IL_000c: add IL_000d: constrained. ""T"" IL_0013: call ""void I1.P01.set"" IL_0018: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""P01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertyGet_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = T.P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertySet_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 = 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9), // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = T.P01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = T.P01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 13), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticPropertySet_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 = 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 = 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticEventAdd_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used interface I1 { abstract static event System.Action P01; static void M02() { P01 += null; P04 += null; } void M03() { this.P01 += null; this.P04 += null; } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { I1.P01 += null; x.P01 += null; I1.P04 += null; x.P04 += null; } static void MT2<T>() where T : I1 { T.P03 += null; T.P04 += null; T.P00 += null; T.P05 += null; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += null); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01 += null").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (14,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // this.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "this.P01 += null").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01 += null").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (28,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x.P01 += null").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += null); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 += null").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticEventRemove_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used interface I1 { abstract static event System.Action P01; static void M02() { P01 -= null; P04 -= null; } void M03() { this.P01 -= null; this.P04 -= null; } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { I1.P01 -= null; x.P01 -= null; I1.P04 -= null; x.P04 -= null; } static void MT2<T>() where T : I1 { T.P03 -= null; T.P04 -= null; T.P00 -= null; T.P05 -= null; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 -= null); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01 -= null").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (14,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // this.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "this.P01 -= null").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01 -= null").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (28,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x.P01 -= null").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 -= null); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 -= null").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticEvent_02() { var source1 = @" interface I1 { abstract static event System.Action P01; static void M02() { _ = nameof(P01); _ = nameof(P04); } void M03() { _ = nameof(this.P01); _ = nameof(this.P04); } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { _ = nameof(I1.P01); _ = nameof(x.P01); _ = nameof(I1.P04); _ = nameof(x.P04); } static void MT2<T>() where T : I1 { _ = nameof(T.P03); _ = nameof(T.P04); _ = nameof(T.P00); _ = nameof(T.P05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (14,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 20), // (15,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 20), // (28,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 20), // (30,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 20), // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = nameof(T.P05); Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticEvent_03() { var source1 = @" public interface I1 { abstract static event System.Action E01; } class Test { static void M02<T, U>() where T : U where U : I1 { T.E01 += null; T.E01 -= null; } static string M03<T, U>() where T : U where U : I1 { return nameof(T.E01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 28 (0x1c) .maxstack 1 IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: call ""void I1.E01.add"" IL_000d: nop IL_000e: ldnull IL_000f: constrained. ""T"" IL_0015: call ""void I1.E01.remove"" IL_001a: nop IL_001b: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""E01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 25 (0x19) .maxstack 1 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: call ""void I1.E01.add"" IL_000c: ldnull IL_000d: constrained. ""T"" IL_0013: call ""void I1.E01.remove"" IL_0018: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""E01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.E01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IEventReferenceOperation: event System.Action I1.E01 (Static) (OperationKind.EventReference, Type: System.Action) (Syntax: 'T.E01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "E01").Single().ToTestDisplayString()); Assert.Equal("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "E01").Single().ToTestDisplayString()); Assert.Contains("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("event System.Action I1.E01", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "E01").Single().ToTestDisplayString()); Assert.Equal("event System.Action I1.E01", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "E01").Single().ToTestDisplayString()); Assert.Contains("event System.Action I1.E01", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("event System.Action I1.E01", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("E01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticEventAdd_04() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01 += null").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "P01").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventRemove_04() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 -= null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01 -= null").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "P01").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventAdd_06() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventRemove_06() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 -= null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 -= null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticIndexedProperty_03() { var ilSource = @" .class interface public auto ansi abstract I1 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) // Methods .method public hidebysig specialname newslot abstract virtual static int32 get_Item ( int32 x ) cil managed { } // end of method I1::get_Item .method public hidebysig specialname newslot abstract virtual static void set_Item ( int32 x, int32 'value' ) cil managed { } // end of method I1::set_Item // Properties .property int32 Item( int32 x ) { .get int32 I1::get_Item(int32) .set void I1::set_Item(int32, int32) } } // end of class I1 "; var source1 = @" class Test { static void M02<T>() where T : I1 { T.Item[0] += 1; } static string M03<T>() where T : I1 { return nameof(T.Item); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.Item[0] += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(6, 9), // (11,23): error CS0119: 'T' is a type parameter, which is not valid in the given context // return nameof(T.Item); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(11, 23) ); var source2 = @" class Test { static void M02<T>() where T : I1 { T[0] += 1; } static void M03<T>() where T : I1 { T.set_Item(0, T.get_Item(0) + 1); } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,9): error CS0119: 'T' is a type, which is not valid in the given context // T[0] += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(6, 9), // (11,11): error CS0571: 'I1.this[int].set': cannot explicitly call operator or accessor // T.set_Item(0, T.get_Item(0) + 1); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Item").WithArguments("I1.this[int].set").WithLocation(11, 11), // (11,25): error CS0571: 'I1.this[int].get': cannot explicitly call operator or accessor // T.set_Item(0, T.get_Item(0) + 1); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("I1.this[int].get").WithLocation(11, 25) ); } [Fact] public void ConsumeAbstractStaticIndexedProperty_04() { var ilSource = @" .class interface public auto ansi abstract I1 { // Methods .method public hidebysig specialname newslot abstract virtual static int32 get_Item ( int32 x ) cil managed { } // end of method I1::get_Item .method public hidebysig specialname newslot abstract virtual static void set_Item ( int32 x, int32 'value' ) cil managed { } // end of method I1::set_Item // Properties .property int32 Item( int32 x ) { .get int32 I1::get_Item(int32) .set void I1::set_Item(int32, int32) } } // end of class I1 "; var source1 = @" class Test { static void M02<T>() where T : I1 { T.Item[0] += 1; } static string M03<T>() where T : I1 { return nameof(T.Item); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,11): error CS1545: Property, indexer, or event 'I1.Item[int]' is not supported by the language; try directly calling accessor methods 'I1.get_Item(int)' or 'I1.set_Item(int, int)' // T.Item[0] += 1; Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Item").WithArguments("I1.Item[int]", "I1.get_Item(int)", "I1.set_Item(int, int)").WithLocation(6, 11), // (11,25): error CS1545: Property, indexer, or event 'I1.Item[int]' is not supported by the language; try directly calling accessor methods 'I1.get_Item(int)' or 'I1.set_Item(int, int)' // return nameof(T.Item); Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Item").WithArguments("I1.Item[int]", "I1.get_Item(int)", "I1.set_Item(int, int)").WithLocation(11, 25) ); var source2 = @" class Test { static void M02<T>() where T : I1 { T.set_Item(0, T.get_Item(0) + 1); } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation2, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T>()", @" { // Code size 29 (0x1d) .maxstack 3 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: ldc.i4.0 IL_0003: constrained. ""T"" IL_0009: call ""int I1.get_Item(int)"" IL_000e: ldc.i4.1 IL_000f: add IL_0010: constrained. ""T"" IL_0016: call ""void I1.set_Item(int, int)"" IL_001b: nop IL_001c: ret } "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = (System.Action)M01; _ = (System.Action)M04; } void M03() { _ = (System.Action)this.M01; _ = (System.Action)this.M04; } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = (System.Action)I1.M01; _ = (System.Action)x.M01; _ = (System.Action)I1.M04; _ = (System.Action)x.M04; } static void MT2<T>() where T : I1 { _ = (System.Action)T.M03; _ = (System.Action)T.M04; _ = (System.Action)T.M00; _ = (System.Action)T.M05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.Action)T.M01).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (System.Action)M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(System.Action)M01").WithLocation(8, 13), // (14,28): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)this.M01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 28), // (15,28): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)this.M04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 28), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (System.Action)I1.M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(System.Action)I1.M01").WithLocation(27, 13), // (28,28): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)x.M01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 28), // (30,28): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)x.M04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 28), // (35,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 28), // (36,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 28), // (37,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 28), // (38,30): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = (System.Action)T.M05; Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 30), // (40,87): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.Action)T.M01).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01").WithLocation(40, 87) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_03() { var source1 = @" public interface I1 { abstract static void M01(); } class Test { static System.Action M02<T, U>() where T : U where U : I1 { return T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 24 (0x18) .maxstack 2 .locals init (System.Action V_0) IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: ldftn ""void I1.M01()"" IL_000e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0012: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = (System.Action)T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "(System.Action)T.M01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = (System.Action)T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,28): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 28) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,28): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 28), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = new System.Action(M01); _ = new System.Action(M04); } void M03() { _ = new System.Action(this.M01); _ = new System.Action(this.M04); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = new System.Action(I1.M01); _ = new System.Action(x.M01); _ = new System.Action(I1.M04); _ = new System.Action(x.M04); } static void MT2<T>() where T : I1 { _ = new System.Action(T.M03); _ = new System.Action(T.M04); _ = new System.Action(T.M00); _ = new System.Action(T.M05); _ = (System.Linq.Expressions.Expression<System.Action>)(() => new System.Action(T.M01).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,31): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = new System.Action(M01); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "M01").WithLocation(8, 31), // (14,31): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(this.M01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 31), // (15,31): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(this.M04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 31), // (27,31): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = new System.Action(I1.M01); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.M01").WithLocation(27, 31), // (28,31): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(x.M01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 31), // (30,31): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(x.M04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 31), // (35,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 31), // (36,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 31), // (37,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 31), // (38,33): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = new System.Action(T.M05); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 33), // (40,89): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => new System.Action(T.M01).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01").WithLocation(40, 89) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_03() { var source1 = @" public interface I1 { abstract static void M01(); } class Test { static System.Action M02<T, U>() where T : U where U : I1 { return new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 24 (0x18) .maxstack 2 .locals init (System.Action V_0) IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: ldftn ""void I1.M01()"" IL_000e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0012: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.M01").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_01() { var source1 = @" unsafe interface I1 { abstract static void M01(); static void M02() { _ = (delegate*<void>)&M01; _ = (delegate*<void>)&M04; } void M03() { _ = (delegate*<void>)&this.M01; _ = (delegate*<void>)&this.M04; } static void M04() {} protected abstract static void M05(); } unsafe class Test { static void MT1(I1 x) { _ = (delegate*<void>)&I1.M01; _ = (delegate*<void>)&x.M01; _ = (delegate*<void>)&I1.M04; _ = (delegate*<void>)&x.M04; } static void MT2<T>() where T : I1 { _ = (delegate*<void>)&T.M03; _ = (delegate*<void>)&T.M04; _ = (delegate*<void>)&T.M00; _ = (delegate*<void>)&T.M05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (delegate*<void>)&M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(delegate*<void>)&M01").WithLocation(8, 13), // (14,13): error CS8757: No overload for 'M01' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&this.M01; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&this.M01").WithArguments("M01", "delegate*<void>").WithLocation(14, 13), // (15,13): error CS8757: No overload for 'M04' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&this.M04; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&this.M04").WithArguments("M04", "delegate*<void>").WithLocation(15, 13), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (delegate*<void>)&I1.M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(delegate*<void>)&I1.M01").WithLocation(27, 13), // (28,13): error CS8757: No overload for 'M01' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&x.M01; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&x.M01").WithArguments("M01", "delegate*<void>").WithLocation(28, 13), // (30,13): error CS8757: No overload for 'M04' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&x.M04; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&x.M04").WithArguments("M04", "delegate*<void>").WithLocation(30, 13), // (35,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 31), // (36,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 31), // (37,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 31), // (38,33): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = (delegate*<void>)&T.M05; Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 33), // (40,88): error CS1944: An expression tree may not contain an unsafe pointer operation // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "(delegate*<void>)&T.M01").WithLocation(40, 88), // (40,106): error CS8810: '&' on method groups cannot be used in expression trees // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); Diagnostic(ErrorCode.ERR_AddressOfMethodGroupInExpressionTree, "T.M01").WithLocation(40, 106) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_03() { var source1 = @" public interface I1 { abstract static void M01(); } unsafe class Test { static delegate*<void> M02<T, U>() where T : U where U : I1 { return &T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 18 (0x12) .maxstack 1 .locals init (delegate*<void> V_0) IL_0000: nop IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: constrained. ""T"" IL_0006: ldftn ""void I1.M01()"" IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionFunctionPointer_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" unsafe class Test { static void M02<T>() where T : I1 { _ = (delegate*<void>)&T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "(delegate*<void>)&T.M01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" unsafe class Test { static void M02<T>() where T : I1 { _ = (delegate*<void>)&T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public void M01() {} } " + typeKeyword + @" C3 : I1 { static void M01() {} } " + typeKeyword + @" C4 : I1 { void I1.M01() {} } " + typeKeyword + @" C5 : I1 { public static int M01() => throw null; } " + typeKeyword + @" C6 : I1 { static int I1.M01() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01()' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01()").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01()'. 'C2.M01()' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01()", "C2.M01()").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01()'. 'C3.M01()' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01()", "C3.M01()").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01()' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01()").WithLocation(24, 10), // (26,13): error CS0539: 'C4.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01()").WithLocation(26, 13), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01()'. 'C5.M01()' cannot implement 'I1.M01()' because it does not have the matching return type of 'void'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01()", "C5.M01()", "void").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01()' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01()").WithLocation(36, 10), // (38,19): error CS0539: 'C6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01()").WithLocation(38, 19) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract void M01(); } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static void M01() {} } " + typeKeyword + @" C3 : I1 { void M01() {} } " + typeKeyword + @" C4 : I1 { static void I1.M01() {} } " + typeKeyword + @" C5 : I1 { public int M01() => throw null; } " + typeKeyword + @" C6 : I1 { int I1.M01() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01()' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01()").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01()'. 'C2.M01()' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01()", "C2.M01()").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01()'. 'C3.M01()' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01()", "C3.M01()").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01()' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01()").WithLocation(24, 10), // (26,20): error CS0539: 'C4.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01()").WithLocation(26, 20), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01()'. 'C5.M01()' cannot implement 'I1.M01()' because it does not have the matching return type of 'void'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01()", "C5.M01()", "void").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01()' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01()").WithLocation(36, 10), // (38,12): error CS0539: 'C6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01()").WithLocation(38, 12) ); } [Fact] public void ImplementAbstractStaticMethod_03() { var source1 = @" public interface I1 { abstract static void M01(); } interface I2 : I1 {} interface I3 : I1 { public virtual void M01() {} } interface I4 : I1 { static void M01() {} } interface I5 : I1 { void I1.M01() {} } interface I6 : I1 { static void I1.M01() {} } interface I7 : I1 { abstract static void M01(); } interface I8 : I1 { abstract static void I1.M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,25): warning CS0108: 'I3.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // public virtual void M01() {} Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01()", "I1.M01()").WithLocation(12, 25), // (17,17): warning CS0108: 'I4.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // static void M01() {} Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01()", "I1.M01()").WithLocation(17, 17), // (22,13): error CS0539: 'I5.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01()").WithLocation(22, 13), // (27,20): error CS0106: The modifier 'static' is not valid for this item // static void I1.M01() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 20), // (27,20): error CS0539: 'I6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01()").WithLocation(27, 20), // (32,26): warning CS0108: 'I7.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // abstract static void M01(); Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01()", "I1.M01()").WithLocation(32, 26), // (37,29): error CS0106: The modifier 'static' is not valid for this item // abstract static void I1.M01(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 29), // (37,29): error CS0539: 'I8.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static void I1.M01(); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01()").WithLocation(37, 29) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); abstract static void M02(); } "; var source2 = typeKeyword + @" Test: I1 { static void I1.M01() {} public static void M02() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,20): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 20) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,20): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 20), // (10,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 26), // (11,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M02(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = typeKeyword + @" Test1: I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01()' cannot implement interface member 'I1.M01()' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01()", "I1.M01()", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01()' cannot implement interface member 'I1.M01()' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01()", "I1.M01()", "Test1").WithLocation(2, 12), // (9,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = typeKeyword + @" Test1: I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,20): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 20) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,20): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 20), // (9,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C : I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, cM01.MethodKind); Assert.Equal("void C.M01()", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C : I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.Equal("void C.I1.M01()", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticMethod_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static void M01(); } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C2.I1.M01()", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticMethod_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig static abstract virtual void M01 () cil managed { } // end of method I1::M01 } // end of class I1 .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static void I1.M01 () cil managed { .override method void I1::M01() .maxstack 8 IL_0000: ret } // end of method C1::I1.M01 .method public hidebysig static void M01 () cil managed { IL_0000: ret } // end of method C1::M01 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } // end of method C1::.ctor } // end of class C1 .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static void M01 () cil managed { IL_0000: ret } // end of method C2::M01 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1.I1.M01()", c1M01.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); Assert.Equal("void C2.M01()", c5.FindImplementationForInterfaceMember(m01).ToTestDisplayString()); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticMethod_11() { // Ignore invalid metadata (non-abstract static virtual method). var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig virtual static void M01 () cil managed { IL_0000: ret } // end of method I1::M01 } // end of class I1 "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static void I1.M01() {} } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,19): error CS0539: 'C1.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01()").WithLocation(4, 19) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Fact] public void ImplementAbstractStaticMethod_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void M01 () cil managed { } // end of method I1::M01 } // end of class I1 .class interface public auto ansi abstract I2 implements I1 { // Methods .method private hidebysig static void I1.M01 () cil managed { .override method void I1::M01() IL_0000: ret } // end of method I2::I1.M01 } // end of class I2 "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01()' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01()").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticMethod_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static void M01(); } class C1 { public static void M01() {} } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("void C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1.M01"); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Ordinary, c2M01.MethodKind); Assert.Equal("void C1.M01()", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C1.M01()"" IL_0005: ret } "); } [Fact] public void ImplementAbstractStaticMethod_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void modopt(I1) M01 () cil managed { } // end of method I1::M01 } // end of class I1 "; var source1 = @" class C1 : I1 { public static void M01() {} } class C2 : I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("void modopt(I1) C1.I1.M01()", c1M01.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1.M01"); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("void modopt(I1) C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C1.M01()"" IL_0005: ret } "); } [Fact] public void ImplementAbstractStaticMethod_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static void M01(); abstract static void M02(); } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static void I1.M02() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<MethodSymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>("M01"); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<MethodSymbol>().Single(); var c2M02 = c3.BaseType().GetMember<MethodSymbol>("I1.M02"); Assert.Equal("void C2.I1.M02()", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Fact] public void ImplementAbstractStaticMethod_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static void M01(); } public class C1 : I1 { public static void M01() {} } public class C2 : C1 { new public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C2.M01()"" IL_0005: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<MethodSymbol>("M01"); Assert.Equal("void C2.M01()", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C3.I1.M01()", c3M01.ToTestDisplayString()); Assert.Same(m01, c3M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_17(bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(System.Int32 x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(System.Int32 x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_18(bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(T x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(T x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_19(bool genericFirst) { // Same as ImplementAbstractStaticMethod_17 only implementation is explicit in source. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" static void I1.M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.I1.M01(System.Int32 x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_20(bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implementation is explicit in source. var generic = @" static void I1<T>.M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.I1<T>.M01(T x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_21(bool genericFirst) { // Same as ImplementAbstractStaticMethod_17 only implicit implementation is in an intermediate base. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T> : C1<T>, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C11<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "void C11<T>.I1.M01(System.Int32 x)" : "void C1<T>.M01(System.Int32 x)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_22(bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implicit implementation is in an intermediate base. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T> : C1<T>, I1<T> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C11<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "void C11<T>.I1<T>.M01(T x)" : "void C1<T>.M01(T x)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } private static string UnaryOperatorName(string op) => OperatorFacts.UnaryOperatorNameFromSyntaxKindIfAny(SyntaxFactory.ParseToken(op).Kind()); private static string BinaryOperatorName(string op) => op switch { ">>" => WellKnownMemberNames.RightShiftOperatorName, _ => OperatorFacts.BinaryOperatorNameFromSyntaxKindIfAny(SyntaxFactory.ParseToken(op).Kind()) }; [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = UnaryOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public C2 operator " + op + @"(C2 x) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static C3 operator " + op + @"(C3 x) => throw null; } " + typeKeyword + @" C4 : I1<C4> { C4 I1<C4>.operator " + op + @"(C4 x) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static int operator " + op + @" (C5 x) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static int I1<C6>.operator " + op + @" (C6 x) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static C7 " + opName + @"(C7 x) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static C8 I1<C8>." + opName + @"(C8 x) => throw null; } public interface I2<T> where T : I2<T> { abstract static T " + opName + @"(T x); } " + typeKeyword + @" C9 : I2<C9> { public static C9 operator " + op + @"(C9 x) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static C10 I2<C10>.operator " + op + @"(C10 x) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_BadIncDecRetType or (int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.operator +(C1)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>.operator " + op + "(C1)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.operator +(C2)'. 'C2.operator +(C2)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>.operator " + op + "(C2)", "C2.operator " + op + "(C2)").WithLocation(12, 10), // (14,24): error CS0558: User-defined operator 'C2.operator +(C2)' must be declared static and public // public C2 operator +(C2 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C2.operator " + op + "(C2)").WithLocation(14, 24), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.operator +(C3)'. 'C3.operator +(C3)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>.operator " + op + "(C3)", "C3.operator " + op + "(C3)").WithLocation(18, 10), // (20,24): error CS0558: User-defined operator 'C3.operator +(C3)' must be declared static and public // static C3 operator +(C3 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C3.operator " + op + "(C3)").WithLocation(20, 24), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.operator +(C4)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>.operator " + op + "(C4)").WithLocation(24, 10), // (26,24): error CS8930: Explicit implementation of a user-defined operator 'C4.operator +(C4)' must be declared static // C4 I1<C4>.operator +(C4 x) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("C4.operator " + op + "(C4)").WithLocation(26, 24), // (26,24): error CS0539: 'C4.operator +(C4)' in explicit interface declaration is not found among members of the interface that can be implemented // C4 I1<C4>.operator +(C4 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C4.operator " + op + "(C4)").WithLocation(26, 24), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.operator +(C5)'. 'C5.operator +(C5)' cannot implement 'I1<C5>.operator +(C5)' because it does not have the matching return type of 'C5'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>.operator " + op + "(C5)", "C5.operator " + op + "(C5)", "C5").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.operator +(C6)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>.operator " + op + "(C6)").WithLocation(36, 10), // (38,32): error CS0539: 'C6.operator +(C6)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C6>.operator + (C6 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C6.operator " + op + "(C6)").WithLocation(38, 32), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.operator +(C7)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>.operator " + op + "(C7)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.operator +(C8)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>.operator " + op + "(C8)").WithLocation(48, 10), // (50,22): error CS0539: 'C8.op_UnaryPlus(C8)' in explicit interface declaration is not found among members of the interface that can be implemented // static C8 I1<C8>.op_UnaryPlus(C8 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8)").WithLocation(50, 22), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_UnaryPlus(C9)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_UnaryPlus(C10)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10)").WithLocation(65, 11), // (67,33): error CS0539: 'C10.operator +(C10)' in explicit interface declaration is not found among members of the interface that can be implemented // static C10 I2<C10>.operator +(C10 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C10.operator " + op + "(C10)").WithLocation(67, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = BinaryOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public C2 operator " + op + @"(C2 x, int y) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static C3 operator " + op + @"(C3 x, int y) => throw null; } " + typeKeyword + @" C4 : I1<C4> { C4 I1<C4>.operator " + op + @"(C4 x, int y) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static int operator " + op + @" (C5 x, int y) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static int I1<C6>.operator " + op + @" (C6 x, int y) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static C7 " + opName + @"(C7 x, int y) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static C8 I1<C8>." + opName + @"(C8 x, int y) => throw null; } public interface I2<T> where T : I2<T> { abstract static T " + opName + @"(T x, int y); } " + typeKeyword + @" C9 : I2<C9> { public static C9 operator " + op + @"(C9 x, int y) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static C10 I2<C10>.operator " + op + @"(C10 x, int y) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.operator >>(C1, int)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>.operator " + op + "(C1, int)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.operator >>(C2, int)'. 'C2.operator >>(C2, int)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>.operator " + op + "(C2, int)", "C2.operator " + op + "(C2, int)").WithLocation(12, 10), // (14,24): error CS0558: User-defined operator 'C2.operator >>(C2, int)' must be declared static and public // public C2 operator >>(C2 x, int y) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C2.operator " + op + "(C2, int)").WithLocation(14, 24), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.operator >>(C3, int)'. 'C3.operator >>(C3, int)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>.operator " + op + "(C3, int)", "C3.operator " + op + "(C3, int)").WithLocation(18, 10), // (20,24): error CS0558: User-defined operator 'C3.operator >>(C3, int)' must be declared static and public // static C3 operator >>(C3 x, int y) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C3.operator " + op + "(C3, int)").WithLocation(20, 24), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.operator >>(C4, int)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>.operator " + op + "(C4, int)").WithLocation(24, 10), // (26,24): error CS8930: Explicit implementation of a user-defined operator 'C4.operator >>(C4, int)' must be declared static // C4 I1<C4>.operator >>(C4 x, int y) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("C4.operator " + op + "(C4, int)").WithLocation(26, 24), // (26,24): error CS0539: 'C4.operator >>(C4, int)' in explicit interface declaration is not found among members of the interface that can be implemented // C4 I1<C4>.operator >>(C4 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C4.operator " + op + "(C4, int)").WithLocation(26, 24), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.operator >>(C5, int)'. 'C5.operator >>(C5, int)' cannot implement 'I1<C5>.operator >>(C5, int)' because it does not have the matching return type of 'C5'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>.operator " + op + "(C5, int)", "C5.operator " + op + "(C5, int)", "C5").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.operator >>(C6, int)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>.operator " + op + "(C6, int)").WithLocation(36, 10), // (38,32): error CS0539: 'C6.operator >>(C6, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C6>.operator >> (C6 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C6.operator " + op + "(C6, int)").WithLocation(38, 32), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.operator >>(C7, int)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>.operator " + op + "(C7, int)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.operator >>(C8, int)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>.operator " + op + "(C8, int)").WithLocation(48, 10), // (50,22): error CS0539: 'C8.op_RightShift(C8, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static C8 I1<C8>.op_RightShift(C8 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8, int)").WithLocation(50, 22), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_RightShift(C9, int)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9, int)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_RightShift(C10, int)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10, int)").WithLocation(65, 11), // (67,33): error CS0539: 'C10.operator >>(C10, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static C10 I2<C10>.operator >>(C10 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C10.operator " + op + "(C10, int)").WithLocation(67, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_03([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } interface I2 : I1 {} interface I3 : I1 { I1 operator " + op + @"(I1 x) => default; } interface I4 : I1 { static I1 operator " + op + @"(I1 x) => default; } interface I5 : I1 { I1 I1.operator " + op + @"(I1 x) => default; } interface I6 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } interface I7 : I1 { abstract static I1 operator " + op + @"(I1 x); } public interface I11<T> where T : I11<T> { abstract static T operator " + op + @"(T x); } interface I8<T> : I11<T> where T : I8<T> { T operator " + op + @"(T x) => default; } interface I9<T> : I11<T> where T : I9<T> { static T operator " + op + @"(T x) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static T operator " + op + @"(T x); } interface I12<T> : I11<T> where T : I12<T> { static T I11<T>.operator " + op + @"(T x) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static T I11<T>.operator " + op + @"(T x); } interface I14 : I1 { abstract static I1 I1.operator " + op + @"(I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ErrorCode badSignatureError = op.Length != 2 ? ErrorCode.ERR_BadUnaryOperatorSignature : ErrorCode.ERR_BadIncDecSignature; ErrorCode badAbstractSignatureError = op.Length != 2 ? ErrorCode.ERR_BadAbstractUnaryOperatorSignature : ErrorCode.ERR_BadAbstractIncDecSignature; compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (12,17): error CS0558: User-defined operator 'I3.operator +(I1)' must be declared static and public // I1 operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I3.operator " + op + "(I1)").WithLocation(12, 17), // (12,17): error CS0562: The parameter of a unary operator must be the containing type // I1 operator +(I1 x) => default; Diagnostic(badSignatureError, op).WithLocation(12, 17), // (17,24): error CS0562: The parameter of a unary operator must be the containing type // static I1 operator +(I1 x) => default; Diagnostic(badSignatureError, op).WithLocation(17, 24), // (22,20): error CS8930: Explicit implementation of a user-defined operator 'I5.operator +(I1)' must be declared static // I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("I5.operator " + op + "(I1)").WithLocation(22, 20), // (22,20): error CS0539: 'I5.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I5.operator " + op + "(I1)").WithLocation(22, 20), // (27,27): error CS0539: 'I6.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I6.operator " + op + "(I1)").WithLocation(27, 27), // (32,33): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // abstract static I1 operator +(I1 x); Diagnostic(badAbstractSignatureError, op).WithLocation(32, 33), // (42,16): error CS0558: User-defined operator 'I8<T>.operator +(T)' must be declared static and public // T operator +(T x) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I8<T>.operator " + op + "(T)").WithLocation(42, 16), // (42,16): error CS0562: The parameter of a unary operator must be the containing type // T operator +(T x) => default; Diagnostic(badSignatureError, op).WithLocation(42, 16), // (47,23): error CS0562: The parameter of a unary operator must be the containing type // static T operator +(T x) => default; Diagnostic(badSignatureError, op).WithLocation(47, 23), // (57,30): error CS0539: 'I12<T>.operator +(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static T I11<T>.operator +(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I12<T>.operator " + op + "(T)").WithLocation(57, 30), // (62,39): error CS0106: The modifier 'abstract' is not valid for this item // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(62, 39), // (62,39): error CS0501: 'I13<T>.operator +(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I13<T>.operator " + op + "(T)").WithLocation(62, 39), // (62,39): error CS0539: 'I13<T>.operator +(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I13<T>.operator " + op + "(T)").WithLocation(62, 39), // (67,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(67, 36), // (67,36): error CS0501: 'I14.operator +(I1)' must declare a body because it is not marked abstract, extern, or partial // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I14.operator " + op + "(I1)").WithLocation(67, 36), // (67,36): error CS0539: 'I14.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I14.operator " + op + "(I1)").WithLocation(67, 36) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_03([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } interface I2 : I1 {} interface I3 : I1 { I1 operator " + op + @"(I1 x, int y) => default; } interface I4 : I1 { static I1 operator " + op + @"(I1 x, int y) => default; } interface I5 : I1 { I1 I1.operator " + op + @"(I1 x, int y) => default; } interface I6 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } interface I7 : I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public interface I11<T> where T : I11<T> { abstract static T operator " + op + @"(T x, int y); } interface I8<T> : I11<T> where T : I8<T> { T operator " + op + @"(T x, int y) => default; } interface I9<T> : I11<T> where T : I9<T> { static T operator " + op + @"(T x, int y) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static T operator " + op + @"(T x, int y); } interface I12<T> : I11<T> where T : I12<T> { static T I11<T>.operator " + op + @"(T x, int y) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static T I11<T>.operator " + op + @"(T x, int y); } interface I14 : I1 { abstract static I1 I1.operator " + op + @"(I1 x, int y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); bool isShift = op == "<<" || op == ">>"; ErrorCode badSignatureError = isShift ? ErrorCode.ERR_BadShiftOperatorSignature : ErrorCode.ERR_BadBinaryOperatorSignature; ErrorCode badAbstractSignatureError = isShift ? ErrorCode.ERR_BadAbstractShiftOperatorSignature : ErrorCode.ERR_BadAbstractBinaryOperatorSignature; var expected = new[] { // (12,17): error CS0563: One of the parameters of a binary operator must be the containing type // I1 operator |(I1 x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(12, 17), // (17,24): error CS0563: One of the parameters of a binary operator must be the containing type // static I1 operator |(I1 x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(17, 24), // (22,20): error CS8930: Explicit implementation of a user-defined operator 'I5.operator |(I1, int)' must be declared static // I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("I5.operator " + op + "(I1, int)").WithLocation(22, 20), // (22,20): error CS0539: 'I5.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I5.operator " + op + "(I1, int)").WithLocation(22, 20), // (27,27): error CS0539: 'I6.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I6.operator " + op + "(I1, int)").WithLocation(27, 27), // (32,33): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // abstract static I1 operator |(I1 x, int y); Diagnostic(badAbstractSignatureError, op).WithLocation(32, 33), // (42,16): error CS0563: One of the parameters of a binary operator must be the containing type // T operator |(T x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(42, 16), // (47,23): error CS0563: One of the parameters of a binary operator must be the containing type // static T operator |(T x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(47, 23), // (57,30): error CS0539: 'I12<T>.operator |(T, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static T I11<T>.operator |(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I12<T>.operator " + op + "(T, int)").WithLocation(57, 30), // (62,39): error CS0106: The modifier 'abstract' is not valid for this item // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(62, 39), // (62,39): error CS0501: 'I13<T>.operator |(T, int)' must declare a body because it is not marked abstract, extern, or partial // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I13<T>.operator " + op + "(T, int)").WithLocation(62, 39), // (62,39): error CS0539: 'I13<T>.operator |(T, int)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I13<T>.operator " + op + "(T, int)").WithLocation(62, 39), // (67,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(67, 36), // (67,36): error CS0501: 'I14.operator |(I1, int)' must declare a body because it is not marked abstract, extern, or partial // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I14.operator " + op + "(I1, int)").WithLocation(67, 36), // (67,36): error CS0539: 'I14.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I14.operator " + op + "(I1, int)").WithLocation(67, 36) }; if (op is "==" or "!=") { expected = expected.Concat( new[] { // (12,17): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // I1 operator ==(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(12, 17), // (17,24): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static I1 operator ==(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(17, 24), // (42,16): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // T operator ==(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(42, 16), // (47,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static T operator ==(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(47, 23), } ).ToArray(); } else { expected = expected.Concat( new[] { // (12,17): error CS0558: User-defined operator 'I3.operator |(I1, int)' must be declared static and public // I1 operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I3.operator " + op + "(I1, int)").WithLocation(12, 17), // (42,16): error CS0558: User-defined operator 'I8<T>.operator |(T, int)' must be declared static and public // T operator |(T x, int y) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I8<T>.operator " + op + "(T, int)").WithLocation(42, 16) } ).ToArray(); } compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify(expected); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_04([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public interface I2<T> where T : I2<T> { abstract static T operator " + op + @"(T x); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static Test2 operator " + op + @"(Test2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15), // (14,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator +(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(14, 33), // (19,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator +(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(19, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public interface I2<T> where T : I2<T> { abstract static T operator " + op + @"(T x, int y); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static Test2 operator " + op + @"(Test2 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15), // (14,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator +(I1 x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(14, 33), // (19,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator +(T x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(19, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_05([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static Test1 operator " + op + @"(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (2,12): error CS8929: 'Test1.operator +(Test1)' cannot implement interface member 'I1<Test1>.operator +(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1)", "I1<Test1>.operator " + op + "(Test1)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (2,12): error CS8929: 'Test1.operator +(Test1)' cannot implement interface member 'I1<Test1>.operator +(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1)", "I1<Test1>.operator " + op + "(Test1)", "Test1").WithLocation(2, 12), // (9,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator +(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_05([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static Test1 operator " + op + @"(Test1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (2,12): error CS8929: 'Test1.operator >>(Test1, int)' cannot implement interface member 'I1<Test1>.operator >>(Test1, int)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1, int)", "I1<Test1>.operator " + op + "(Test1, int)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (2,12): error CS8929: 'Test1.operator >>(Test1, int)' cannot implement interface member 'I1<Test1>.operator >>(Test1, int)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1, int)", "I1<Test1>.operator " + op + "(Test1, int)", "Test1").WithLocation(2, 12), // (9,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator >>(T x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_06([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator +(I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_06([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator +(I1 x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_07([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } " + typeKeyword + @" C : I1<C> { public static C operator " + op + @"(C x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("C C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_07([CombinatorialValues("true", "false")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static bool operator " + op + @"(T x); } partial " + typeKeyword + @" C : I1<C> { public static bool operator " + op + @"(C x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1<T> where T : I1<T> { abstract static bool operator " + matchingOp + @"(T x); } partial " + typeKeyword + @" C { public static bool operator " + matchingOp + @"(C x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("System.Boolean C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_07([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() partial " + typeKeyword + @" C : I1<C> { public static C operator " + op + @"(C x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + matchingOp + @"(T x, int y); } partial " + typeKeyword + @" C { public static C operator " + matchingOp + @"(C x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.Equal(matchingOp is null ? 1 : 2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("C C." + opName + "(C x, System.Int32 y)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_08([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } " + typeKeyword + @" C : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal("default", node.ToString()); Assert.Equal("I1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("I1 C.I1." + opName + "(I1 x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("I1 C.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_08([CombinatorialValues("true", "false")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1 { abstract static bool operator " + op + @"(I1 x); } partial " + typeKeyword + @" C : I1 { static bool I1.operator " + op + @"(I1 x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1 { abstract static bool operator " + matchingOp + @"(I1 x); } partial " + typeKeyword + @" C { static bool I1.operator " + matchingOp + @"(I1 x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", node.ToString()); Assert.Equal("System.Boolean", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("System.Boolean C.I1." + opName + "(I1 x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers(opName).OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("System.Boolean C.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_08([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } partial " + typeKeyword + @" C : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator " + matchingOp + @"(I1 x, int y); } partial " + typeKeyword + @" C { static I1 I1.operator " + matchingOp + @"(I1 x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", node.ToString()); Assert.Equal("I1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("I1 C.I1." + opName + "(I1 x, System.Int32 y)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers(opName).OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(matchingOp is null ? 1 : 2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("I1 C.I1." + opName + "(I1 x, System.Int32 y)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_09([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public class C2 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_09([CombinatorialValues("true", "false")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public partial interface I1 { abstract static bool operator " + op + @"(I1 x); } public partial class C2 : I1 { static bool I1.operator " + op + @"(I1 x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1 { abstract static bool operator " + matchingOp + @"(I1 x); } public partial class C2 { static bool I1.operator " + matchingOp + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Boolean C2.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_09([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public partial interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public partial class C2 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator " + matchingOp + @"(I1 x, int y); } public partial class C2 { static I1 I1.operator " + matchingOp + @"(I1 x, int y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2.I1." + opName + "(I1 x, System.Int32 y)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_10([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x) cil managed { .override method class I1 I1::" + opName + @"(class I1) IL_0000: ldnull IL_0001: ret } .method public hidebysig static specialname class I1 " + opName + @" (class I1 x) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static specialname class I1 " + opName + @" (class I1 x) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Equal(MethodKind.UserDefinedOperator, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C1.I1." + opName + "(I1 x)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2." + opName + "(I1 x)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_10([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x, int32 y) cil managed { .override method class I1 I1::" + opName + @"(class I1, int32) IL_0000: ldnull IL_0001: ret } .method public hidebysig static specialname class I1 " + opName + @" (class I1 x, int32 y) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static specialname class I1 " + opName + @" (class I1 x, int32 y) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Equal(MethodKind.UserDefinedOperator, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C1.I1." + opName + "(I1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2." + opName + "(I1 x, System.Int32 y)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_11([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname virtual static class I1 " + opName + @" ( class I1 x ) cil managed { IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,27): error CS0539: 'C1.operator ~(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator ~(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C1.operator " + op + "(I1)").WithLocation(4, 27) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("I1 I1." + opName + "(I1 x)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_11([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,27): error CS0539: 'C1.operator <(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator <(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C1.operator " + op + "(I1, int)").WithLocation(4, 27) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("I1 I1." + opName + "(I1 x, System.Int32 y)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_12([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x ) cil managed { } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x) cil managed { .override method class I1 I1::" + opName + @"(class I1) IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.operator ~(I1)' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.operator " + op + "(I1)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_12([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x, int32 y) cil managed { .override method class I1 I1::" + opName + @"(class I1, int32) IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.operator /(I1, int)' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.operator " + op + "(I1, int)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_13([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public class C2 : C1, I1<C2> { } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); } public partial class C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var i1 = c2.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.False(c2M01.HasSpecialName); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.False(c1M01.HasRuntimeSpecialName); Assert.True(c1M01.HasSpecialName); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.True(c2M01.HasSpecialName); Assert.Equal("C2 C1." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1<C2>." + opName + "(C2, C1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C2 C1." + opName + @"(C2, C1)"" IL_0007: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_14([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static !T modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static C1 operator " + op + @"(C1 x) => default; } class C2 : I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("C1 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("C1 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("C1 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("C2 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""C1 C1." + opName + @"(C1)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_14([CombinatorialValues("true", "false")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static bool modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static bool operator " + op + @"(C1 x) => default; public static bool operator " + (op == "true" ? "false" : "true") + @"(C1 x) => default; } class C2 : I1<C2> { static bool I1<C2>.operator " + op + @"(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("System.Boolean modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("System.Boolean C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("System.Boolean C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("System.Boolean modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""bool C1." + opName + @"(C1)"" IL_0006: ret } "); } private static string MatchingBinaryOperator(string op) { return op switch { "<" => ">", ">" => "<", "<=" => ">=", ">=" => "<=", "==" => "!=", "!=" => "==", _ => null }; } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_14([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static !T modopt(I1`1) " + opName + @" ( !T x, int32 y ) cil managed { } } "; string matchingOp = MatchingBinaryOperator(op); string additionalMethods = ""; if (matchingOp is object) { additionalMethods = @" public static C1 operator " + matchingOp + @"(C1 x, int y) => default; "; } var source1 = @" #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() class C1 : I1<C1> { public static C1 operator " + op + @"(C1 x, int y) => default; " + additionalMethods + @" } class C2 : I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x, int y) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("C1 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("C1 C1." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("C1 C1." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("C2 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x, System.Int32 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1, int)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C1 C1." + opName + @"(C1, int)"" IL_0007: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_15([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public partial class C2 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M02 = c3.BaseType().GetMembers("I1." + opName).OfType<MethodSymbol>().Single(); Assert.Equal("I1 C2.I1." + opName + "(I1 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Fact] public void ImplementAbstractStaticUnaryTrueFalseOperator_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static bool operator true(I1 x); abstract static bool operator false(I1 x); } public partial class C2 : I1 { static bool I1.operator true(I1 x) => default; static bool I1.operator false(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("op_True").OfType<MethodSymbol>().Single(); var m02 = c3.Interfaces().Single().GetMembers("op_False").OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMembers("I1.op_True").OfType<MethodSymbol>().Single(); Assert.Equal("System.Boolean C2.I1.op_True(I1 x)", c2M01.ToTestDisplayString()); Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); var c2M02 = c3.BaseType().GetMembers("I1.op_False").OfType<MethodSymbol>().Single(); Assert.Equal("System.Boolean C2.I1.op_False(I1 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_15([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); abstract static T operator " + op + @"(T x, C2 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public partial class C2 : C1, I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x, C2 y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); abstract static T operator " + matchingOp + @"(T x, C2 y); } public partial class C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } public partial class C2 { static C2 I1<C2>.operator " + matchingOp + @"(C2 x, C2 y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().First(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C2 C1." + opName + "(C2 x, C1 y)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().ElementAt(1); var c2M02 = c3.BaseType().GetMembers("I1<C2>." + opName).OfType<MethodSymbol>().First(); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C2 y)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_16([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A new implicit implementation is properly considered. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 : I1<C2> { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public partial class C2 : C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); } public partial class C1 : I1<C2> { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } public partial class C2 : C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1<C2>." + opName + "(C2, C1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C2 C2." + opName + @"(C2, C1)"" IL_0007: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C2 C2." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C2 C3.I1<C2>." + opName + "(C2 x, C1 y)", c3M01.ToTestDisplayString()); Assert.Equal(m01, c3M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_18([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, U y) => default; "; var nonGeneric = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, int y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> { public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, U y) => default; public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>." + opName + "(C1<T, U> x, U y)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>." + opName + "(C1<T, U> x, U y)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_20([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // Same as ImplementAbstractStaticBinaryOperator_18 only implementation is explicit in source. var generic = @" static C1<T, U> I1<C1<T, U>, U>.operator " + op + @"(C1<T, U> x, U y) => default; "; var nonGeneric = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, int y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> : I1<C1<T, U>, U> { public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, int y) => default; static C1<T, U> I1<C1<T, U>, U>.operator " + matchingOp + @"(C1<T, U> x, U y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>.I1<C1<T, U>, U>." + opName + "(C1<T, U> x, U y)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_22([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implicit implementation is in an intermediate base. var generic = @" public static C11<T, U> operator " + op + @"(C11<T, U> x, C1<T, U> y) => default; "; var nonGeneric = @" public static C11<T, U> operator " + op + @"(C11<T, int> x, C1<T, U> y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T, U> : C1<T, U>, I1<C11<T, U>, C1<T, U>> { } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> { public static C11<T, U> operator " + matchingOp + @"(C11<T, U> x, C1<T, U> y) => default; public static C11<T, U> operator " + matchingOp + @"(C11<T, int> x, C1<T, U> y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C11<int, int>, I1<C11<int, int>, C1<int, int>> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "C11<T, U> C11<T, U>.I1<C11<T, U>, C1<T, U>>." + opName + "(C11<T, U> x, C1<T, U> y)" : "C11<T, U> C1<T, U>." + opName + "(C11<T, U> x, C1<T, U> y)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } class C1 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } class C2 : I1 { private static I1 I1.operator " + op + @"(I1 x) => default; } class C3 : I1 { protected static I1 I1.operator " + op + @"(I1 x) => default; } class C4 : I1 { internal static I1 I1.operator " + op + @"(I1 x) => default; } class C5 : I1 { protected internal static I1 I1.operator " + op + @"(I1 x) => default; } class C6 : I1 { private protected static I1 I1.operator " + op + @"(I1 x) => default; } class C7 : I1 { public static I1 I1.operator " + op + @"(I1 x) => default; } class C8 : I1 { static partial I1 I1.operator " + op + @"(I1 x) => default; } class C9 : I1 { async static I1 I1.operator " + op + @"(I1 x) => default; } class C10 : I1 { unsafe static I1 I1.operator " + op + @"(I1 x) => default; } class C11 : I1 { static readonly I1 I1.operator " + op + @"(I1 x) => default; } class C12 : I1 { extern static I1 I1.operator " + op + @"(I1 x); } class C13 : I1 { abstract static I1 I1.operator " + op + @"(I1 x) => default; } class C14 : I1 { virtual static I1 I1.operator " + op + @"(I1 x) => default; } class C15 : I1 { sealed static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.WRN_ExternMethodNoImplementation or (int)ErrorCode.ERR_OpTFRetType or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (16,35): error CS0106: The modifier 'private' is not valid for this item // private static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private").WithLocation(16, 35), // (22,37): error CS0106: The modifier 'protected' is not valid for this item // protected static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected").WithLocation(22, 37), // (28,36): error CS0106: The modifier 'internal' is not valid for this item // internal static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("internal").WithLocation(28, 36), // (34,46): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected internal").WithLocation(34, 46), // (40,45): error CS0106: The modifier 'private protected' is not valid for this item // private protected static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private protected").WithLocation(40, 45), // (46,34): error CS0106: The modifier 'public' is not valid for this item // public static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("public").WithLocation(46, 34), // (52,12): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // static partial I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(52, 12), // (58,33): error CS0106: The modifier 'async' is not valid for this item // async static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("async").WithLocation(58, 33), // (70,36): error CS0106: The modifier 'readonly' is not valid for this item // static readonly I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("readonly").WithLocation(70, 36), // (82,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(82, 36), // (88,35): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("virtual").WithLocation(88, 35), // (94,34): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("sealed").WithLocation(94, 34) ); } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } struct C1 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C2 : I1 { private static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C3 : I1 { protected static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C4 : I1 { internal static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C5 : I1 { protected internal static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C6 : I1 { private protected static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C7 : I1 { public static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C8 : I1 { static partial I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C9 : I1 { async static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C10 : I1 { unsafe static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C11 : I1 { static readonly I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C12 : I1 { extern static I1 I1.operator " + op + @"(I1 x, int y); } struct C13 : I1 { abstract static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C14 : I1 { virtual static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C15 : I1 { sealed static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.WRN_ExternMethodNoImplementation or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (16,35): error CS0106: The modifier 'private' is not valid for this item // private static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private").WithLocation(16, 35), // (22,37): error CS0106: The modifier 'protected' is not valid for this item // protected static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected").WithLocation(22, 37), // (28,36): error CS0106: The modifier 'internal' is not valid for this item // internal static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("internal").WithLocation(28, 36), // (34,46): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected internal").WithLocation(34, 46), // (40,45): error CS0106: The modifier 'private protected' is not valid for this item // private protected static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private protected").WithLocation(40, 45), // (46,34): error CS0106: The modifier 'public' is not valid for this item // public static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("public").WithLocation(46, 34), // (52,12): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // static partial I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(52, 12), // (58,33): error CS0106: The modifier 'async' is not valid for this item // async static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("async").WithLocation(58, 33), // (70,36): error CS0106: The modifier 'readonly' is not valid for this item // static readonly I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("readonly").WithLocation(70, 36), // (82,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(82, 36), // (88,35): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("virtual").WithLocation(88, 35), // (94,34): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("sealed").WithLocation(94, 34) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1<T> where T : struct { abstract static I1<T> operator " + op + @"(I1<T> x); } class C1 { static I1<int> I1<int>.operator " + op + @"(I1<int> x) => default; } class C2 : I1<C2> { static I1<C2> I1<C2>.operator " + op + @"(I1<C2> x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OpTFRetType or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (9,20): error CS0540: 'C1.I1<int>.operator -(I1<int>)': containing type does not implement interface 'I1<int>' // static I1<int> I1<int>.operator -(I1<int> x) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<int>").WithArguments("C1.I1<int>.operator " + op + "(I1<int>)", "I1<int>").WithLocation(9, 20), // (12,7): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // class C2 : I1<C2> Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 7), // (14,19): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 19), // (14,35): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, op).WithArguments("I1<T>", "T", "C2").WithLocation(14, 35), // (14,44): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("I1<T>", "T", "C2").WithLocation(14, 44 + op.Length - 1) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1<T> where T : class { abstract static I1<T> operator " + op + @"(I1<T> x, int y); } struct C1 { static I1<string> I1<string>.operator " + op + @"(I1<string> x, int y) => default; } struct C2 : I1<C2> { static I1<C2> I1<C2>.operator " + op + @"(I1<C2> x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (9,23): error CS0540: 'C1.I1<string>.operator %(I1<string>, int)': containing type does not implement interface 'I1<string>' // static I1<string> I1<string>.operator %(I1<string> x, int y) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<string>").WithArguments("C1.I1<string>.operator " + op + "(I1<string>, int)", "I1<string>").WithLocation(9, 23), // (12,8): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // struct C2 : I1<C2> Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 8), // (14,19): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 19), // (14,35): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, op).WithArguments("I1<T>", "T", "C2").WithLocation(14, 35), // (14,44): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "x").WithArguments("I1<T>", "T", "C2").WithLocation(14, 44 + op.Length - 1) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public int M01 { get; set; } } " + typeKeyword + @" C3 : I1 { static int M01 { get; set; } } " + typeKeyword + @" C4 : I1 { int I1.M01 { get; set; } } " + typeKeyword + @" C5 : I1 { public static long M01 { get; set; } } " + typeKeyword + @" C6 : I1 { static long I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,12): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 12), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'int'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,20): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static long I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 20) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract int M01 { get; set; } } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static int M01 { get; set; } } " + typeKeyword + @" C3 : I1 { int M01 { get; set; } } " + typeKeyword + @" C4 : I1 { static int I1.M01 { get; set; } } " + typeKeyword + @" C5 : I1 { public long M01 { get; set; } } " + typeKeyword + @" C6 : I1 { long I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,19): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 19), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'int'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,13): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // long I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 13) ); } [Fact] public void ImplementAbstractStaticProperty_03() { var source1 = @" public interface I1 { abstract static int M01 { get; set; } } interface I2 : I1 {} interface I3 : I1 { public virtual int M01 { get => 0; set{} } } interface I4 : I1 { static int M01 { get; set; } } interface I5 : I1 { int I1.M01 { get => 0; set{} } } interface I6 : I1 { static int I1.M01 { get => 0; set{} } } interface I7 : I1 { abstract static int M01 { get; set; } } interface I8 : I1 { abstract static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,24): warning CS0108: 'I3.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // public virtual int M01 { get => 0; set{} } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01", "I1.M01").WithLocation(12, 24), // (17,16): warning CS0108: 'I4.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // static int M01 { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01", "I1.M01").WithLocation(17, 16), // (22,12): error CS0539: 'I5.M01' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01").WithLocation(22, 12), // (27,19): error CS0106: The modifier 'static' is not valid for this item // static int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 19), // (27,19): error CS0539: 'I6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01").WithLocation(27, 19), // (32,25): warning CS0108: 'I7.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01", "I1.M01").WithLocation(32, 25), // (37,28): error CS0106: The modifier 'static' is not valid for this item // abstract static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 28), // (37,28): error CS0539: 'I8.M01' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01").WithLocation(37, 28) ); foreach (var m01 in compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers()) { Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } abstract static int M02 { get; set; } } "; var source2 = typeKeyword + @" Test: I1 { static int I1.M01 { get; set; } public static int M02 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,19): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 19) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,19): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 19), // (10,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 25), // (11,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int M02 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 25) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } "; var source2 = typeKeyword + @" Test1: I1 { public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.set' cannot implement interface member 'I1.M01.set' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.set", "I1.M01.set", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.get' cannot implement interface member 'I1.M01.get' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.get", "I1.M01.get", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.set' cannot implement interface member 'I1.M01.set' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.set", "I1.M01.set", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.get' cannot implement interface member 'I1.M01.get' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.get", "I1.M01.get", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12), // (9,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(9, 31), // (9,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(9, 36) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } "; var source2 = typeKeyword + @" Test1: I1 { static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,19): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 19) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,19): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 19), // (9,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(9, 31), // (9,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(9, 36) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C : I1 { public static int M01 { get => 0; set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.False(cM01Get.HasRuntimeSpecialName); Assert.True(cM01Get.HasSpecialName); Assert.Equal("System.Int32 C.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.False(cM01Set.HasRuntimeSpecialName); Assert.True(cM01Set.HasSpecialName); Assert.Equal("void C.M01.set", cM01Set.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticReadonlyProperty_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; } } " + typeKeyword + @" C : I1 { public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Null(m01.SetMethod); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C.M01.set", cM01Set.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C : I1 { static int I1.M01 { get => 0; set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.I1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.False(cM01Get.HasRuntimeSpecialName); Assert.True(cM01Get.HasSpecialName); Assert.Equal("System.Int32 C.I1.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.False(cM01Set.HasRuntimeSpecialName); Assert.True(cM01Set.HasSpecialName); Assert.Equal("void C.I1.M01.set", cM01Set.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<PropertySymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var cM01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.I1.M01 { get; set; }", cM01.ToTestDisplayString()); Assert.Same(cM01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(cM01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, cM01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, cM01.SetMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig specialname static int32 I1.get_M01 () cil managed { .override method int32 I1::get_M01() IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static void I1.set_M01 ( int32 'value' ) cil managed { .override method void I1::set_M01(int32) IL_0000: ret } .property instance int32 I1.M01() { .get int32 C1::I1.get_M01() .set void C1::I1.set_M01(int32) } .method public hidebysig specialname static int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname static void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 C1::get_M01() .set void C1::set_M01(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig specialname static int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname static void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 C2::get_M01() .set void C2::set_M01(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = (PropertySymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1.I1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.Same(c1M01.GetMethod, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c2.FindImplementationForInterfaceMember(m01.SetMethod)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c4.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c4.FindImplementationForInterfaceMember(m01.SetMethod)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (PropertySymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.Same(c2M01.GetMethod, c5.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c2M01.SetMethod, c5.FindImplementationForInterfaceMember(m01.SetMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticProperty_11() { // Ignore invalid metadata (non-abstract static virtual method). scenario1(); scenario2(); scenario3(); void scenario1() { var ilSource = @" .class interface public auto ansi abstract I1 { .method private hidebysig specialname static virtual int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static virtual void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,18): error CS0539: 'C1.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01").WithLocation(4, 18) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c.FindImplementationForInterfaceMember(m01)); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); } } void scenario2() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method private hidebysig specialname static virtual void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source2 = @" public class C1 : I1 { static int I1.M01 { get; } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, sourceSymbolValidator: validate2, symbolValidator: validate2, verify: Verification.Skipped).VerifyDiagnostics(); void validate2(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.I1.M01 { get; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.I1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(cM01.SetMethod); Assert.Null(c.FindImplementationForInterfaceMember(m01Set)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,29): error CS0550: 'C1.I1.M01.set' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("C1.I1.M01.set", "I1.M01").WithLocation(4, 29) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static int M01 { get; } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation5, sourceSymbolValidator: validate5, symbolValidator: validate5, verify: Verification.Skipped).VerifyDiagnostics(); void validate5(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } } var source6 = @" public class C1 : I1 { public static int M01 { set{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.get' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.get").WithLocation(2, 19) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); var source7 = @" public class C1 : I1 { static int I1.M01 { set{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.get' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.get").WithLocation(2, 19), // (4,18): error CS0551: Explicit interface implementation 'C1.I1.M01' is missing accessor 'I1.M01.get' // static int I1.M01 { set{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M01").WithArguments("C1.I1.M01", "I1.M01.get").WithLocation(4, 18), // (4,24): error CS0550: 'C1.I1.M01.set' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { set{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("C1.I1.M01.set", "I1.M01").WithLocation(4, 24) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); } void scenario3() { var ilSource = @" .class interface public auto ansi abstract I1 { .method private hidebysig specialname static virtual int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source2 = @" public class C1 : I1 { static int I1.M01 { set{} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, sourceSymbolValidator: validate2, symbolValidator: validate2, verify: Verification.Skipped).VerifyDiagnostics(); void validate2(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.I1.M01 { set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.I1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(cM01.GetMethod); Assert.Null(c.FindImplementationForInterfaceMember(m01Get)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,24): error CS0550: 'C1.I1.M01.get' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C1.I1.M01.get", "I1.M01").WithLocation(4, 24) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.SetMethod, c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static int M01 { set{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation5, sourceSymbolValidator: validate5, symbolValidator: validate5, verify: Verification.Skipped).VerifyDiagnostics(); void validate5(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } var source6 = @" public class C1 : I1 { public static int M01 { get; } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.set' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.set").WithLocation(2, 19) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); var source7 = @" public class C1 : I1 { static int I1.M01 { get; } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.set' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.set").WithLocation(2, 19), // (4,18): error CS0551: Explicit interface implementation 'C1.I1.M01' is missing accessor 'I1.M01.set' // static int I1.M01 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M01").WithArguments("C1.I1.M01", "I1.M01.set").WithLocation(4, 18), // (4,24): error CS0550: 'C1.I1.M01.get' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C1.I1.M01.get", "I1.M01").WithLocation(4, 24) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig specialname static int32 I1.get_M01 () cil managed { .override method int32 I1::get_M01() IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static void I1.set_M01 ( int32 'value' ) cil managed { .override method void I1::set_M01(int32) IL_0000: ret } .property instance int32 I1.M01() { .get int32 I2::I1.get_M01() .set void I2::I1.set_M01(int32) } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.SetMethod)); var i2M01 = i2.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, i2M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, i2M01.SetMethod.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticProperty_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static int M01 { get; set; } } class C1 { public static int M01 { get; set; } } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Get = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.GetMethod); var c2M01Set = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.SetMethod); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Get.MethodKind); Assert.False(c2M01Get.HasRuntimeSpecialName); Assert.False(c2M01Get.HasSpecialName); Assert.Equal("System.Int32 C2.I1.get_M01()", c2M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c2M01Get.ExplicitInterfaceImplementations.Single()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Set.MethodKind); Assert.False(c2M01Set.HasRuntimeSpecialName); Assert.False(c2M01Set.HasSpecialName); Assert.Equal("void C2.I1.set_M01(System.Int32 value)", c2M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c2M01Set.ExplicitInterfaceImplementations.Single()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c2M01); var c1M01 = module.GlobalNamespace.GetMember<PropertySymbol>("C1.M01"); var c1M01Get = c1M01.GetMethod; var c1M01Set = c1M01.SetMethod; Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c1M01Get.MethodKind); Assert.False(c1M01Get.HasRuntimeSpecialName); Assert.True(c1M01Get.HasSpecialName); Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c1M01Set.MethodKind); Assert.False(c1M01Set.HasRuntimeSpecialName); Assert.True(c1M01Set.HasSpecialName); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); } else { Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.PropertyGet, c2M01Get.MethodKind); Assert.False(c2M01Get.HasRuntimeSpecialName); Assert.True(c2M01Get.HasSpecialName); Assert.Same(c2M01.GetMethod, c2M01Get); Assert.Empty(c2M01Get.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.PropertySet, c2M01Set.MethodKind); Assert.False(c2M01Set.HasRuntimeSpecialName); Assert.True(c2M01Set.HasSpecialName); Assert.Same(c2M01.SetMethod, c2M01Set); Assert.Empty(c2M01Set.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.get_M01", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C1.M01.get"" IL_0005: ret } "); verifier.VerifyIL("C2.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.set"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticProperty_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void modopt(I1) set_M01 ( int32 modopt(I1) 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void modopt(I1) I1::set_M01(int32 modopt(I1)) } } .class interface public auto ansi abstract I2 { .method public hidebysig specialname abstract virtual static int32 modopt(I2) get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 modopt(I2) 'value' ) cil managed { } .property int32 modopt(I2) M01() { .get int32 modopt(I2) I2::get_M01() .set void I2::set_M01(int32 modopt(I2)) } } "; var source1 = @" class C1 : I1 { public static int M01 { get; set; } } class C2 : I1 { static int I1.M01 { get; set; } } class C3 : I2 { static int I2.M01 { get; set; } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = (PropertySymbol)c1.FindImplementationForInterfaceMember(m01); var c1M01Get = c1M01.GetMethod; var c1M01Set = c1M01.SetMethod; Assert.Equal("System.Int32 C1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Equal(MethodKind.PropertyGet, c1M01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", c1M01Get.ToTestDisplayString()); Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Same(c1M01Get, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Equal(MethodKind.PropertySet, c1M01Set.MethodKind); Assert.Equal("void C1.M01.set", c1M01Set.ToTestDisplayString()); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Same(m01.GetMethod, c1M01Get.ExplicitInterfaceImplementations.Single()); c1M01Set = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Set.MethodKind); Assert.Equal("void modopt(I1) C1.I1.set_M01(System.Int32 modopt(I1) value)", c1M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c1M01Set.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); } else { Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); Assert.Same(c1M01Set, c1.FindImplementationForInterfaceMember(m01.SetMethod)); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Get = c2M01.GetMethod; var c2M01Set = c2M01.SetMethod; Assert.Equal("System.Int32 C2.I1.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c2M01Get.MethodKind); Assert.Equal("System.Int32 C2.I1.M01.get", c2M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c2M01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Get, c2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c2M01Set.MethodKind); Assert.Equal("void modopt(I1) C2.I1.M01.set", c2M01Set.ToTestDisplayString()); Assert.Equal("System.Int32 modopt(I1) value", c2M01Set.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.SetMethod, c2M01Set.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Set, c2.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(c2M01, c2.GetMembers().OfType<PropertySymbol>().Single()); Assert.Equal(2, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var c3 = module.GlobalNamespace.GetTypeMember("C3"); m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c3M01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); var c3M01Get = c3M01.GetMethod; var c3M01Set = c3M01.SetMethod; Assert.Equal("System.Int32 modopt(I2) C3.I2.M01 { get; set; }", c3M01.ToTestDisplayString()); Assert.True(c3M01.IsStatic); Assert.False(c3M01.IsAbstract); Assert.False(c3M01.IsVirtual); Assert.Same(m01, c3M01.ExplicitInterfaceImplementations.Single()); Assert.True(c3M01Get.IsStatic); Assert.False(c3M01Get.IsAbstract); Assert.False(c3M01Get.IsVirtual); Assert.False(c3M01Get.IsMetadataVirtual()); Assert.False(c3M01Get.IsMetadataFinal); Assert.False(c3M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c3M01Get.MethodKind); Assert.Equal("System.Int32 modopt(I2) C3.I2.M01.get", c3M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c3M01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(c3M01Get, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.True(c3M01Set.IsStatic); Assert.False(c3M01Set.IsAbstract); Assert.False(c3M01Set.IsVirtual); Assert.False(c3M01Set.IsMetadataVirtual()); Assert.False(c3M01Set.IsMetadataFinal); Assert.False(c3M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c3M01Set.MethodKind); Assert.Equal("void C3.I2.M01.set", c3M01Set.ToTestDisplayString()); Assert.Equal("System.Int32 modopt(I2) value", c3M01Set.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.SetMethod, c3M01Set.ExplicitInterfaceImplementations.Single()); Assert.Same(c3M01Set, c3.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(c3M01, c3.GetMembers().OfType<PropertySymbol>().Single()); Assert.Equal(2, c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); } verifier.VerifyIL("C1.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.set"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStatiProperty_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static int M01 { get; set; } abstract static int M02 { get; set; } } public class C1 { public static int M01 { get; set; } } public class C2 : C1, I1 { static int I1.M02 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<PropertySymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<PropertySymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<PropertySymbol>("M01"); Assert.Equal("System.Int32 C1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); var c1M01Get = c1M01.GetMethod; Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); var c1M01Set = c1M01.SetMethod; Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01Get = c3.FindImplementationForInterfaceMember(m01.GetMethod); Assert.Equal("System.Int32 C2.I1.get_M01()", c2M01Get.ToTestDisplayString()); var c2M01Set = c3.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal("void C2.I1.set_M01(System.Int32 value)", c2M01Set.ToTestDisplayString()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c3.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<PropertySymbol>().Single(); var c2M02 = c3.BaseType().GetMember<PropertySymbol>("I1.M02"); Assert.Equal("System.Int32 C2.I1.M02 { get; set; }", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c2M02.GetMethod, c3.FindImplementationForInterfaceMember(m02.GetMethod)); Assert.Same(c2M02.SetMethod, c3.FindImplementationForInterfaceMember(m02.SetMethod)); } } [Fact] public void ImplementAbstractStaticProperty_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1 : I1 { public static int M01 { get; set; } } public class C2 : C1 { new public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.get_M01", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C2.M01.get"" IL_0005: ret } "); verifier.VerifyIL("C3.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.set"" IL_0006: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c2M01 = c3.BaseType().GetMember<PropertySymbol>("M01"); var c2M01Get = c2M01.GetMethod; var c2M01Set = c2M01.SetMethod; Assert.Equal("System.Int32 C2.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.Empty(c2M01Get.ExplicitInterfaceImplementations); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); Assert.Empty(c2M01Set.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); // Forwarding methods for accessors aren't tied to a property Assert.Null(c3M01); var c3M01Get = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.GetMethod); Assert.Equal("System.Int32 C3.I1.get_M01()", c3M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c3M01Get.ExplicitInterfaceImplementations.Single()); var c3M01Set = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal("void C3.I1.set_M01(System.Int32 value)", c3M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c3M01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c2M01Get, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c2M01Set, c3.FindImplementationForInterfaceMember(m01.SetMethod)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_19(bool genericFirst) { // An "ambiguity" in implicit/explicit implementation declared in generic base class. var generic = @" public static T M01 { get; set; } "; var nonGeneric = @" static int I1.M01 { get; set; } "; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<PropertySymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1<T>.I1.M01 { get; set; }", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_20(bool genericFirst) { // Same as ImplementAbstractStaticProperty_19 only interface is generic too. var generic = @" static T I1<T>.M01 { get; set; } "; var nonGeneric = @" public static int M01 { get; set; } "; var source1 = @" public interface I1<T> { abstract static T M01 { get; set; } } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<PropertySymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("T C1<T>.I1<T>.M01 { get; set; }", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public event System.Action M01; } " + typeKeyword + @" C3 : I1 { static event System.Action M01; } " + typeKeyword + @" C4 : I1 { event System.Action I1.M01 { add{} remove{}} } " + typeKeyword + @" C5 : I1 { public static event System.Action<int> M01; } " + typeKeyword + @" C6 : I1 { static event System.Action<int> I1.M01 { add{} remove{}} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,28): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.M01 { add{} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 28), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'Action'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "System.Action").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,40): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action<int> I1.M01 { add{} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 40) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract event System.Action M01; } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static event System.Action M01; } " + typeKeyword + @" C3 : I1 { event System.Action M01; } " + typeKeyword + @" C4 : I1 { static event System.Action I1.M01 { add{} remove{} } } " + typeKeyword + @" C5 : I1 { public event System.Action<int> M01; } " + typeKeyword + @" C6 : I1 { event System.Action<int> I1.M01 { add{} remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,35): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 35), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'Action'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "System.Action").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,33): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action<int> I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 33) ); } [Fact] public void ImplementAbstractStaticEvent_03() { var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract static event System.Action M01; } interface I2 : I1 {} interface I3 : I1 { public virtual event System.Action M01 { add{} remove{} } } interface I4 : I1 { static event System.Action M01; } interface I5 : I1 { event System.Action I1.M01 { add{} remove{} } } interface I6 : I1 { static event System.Action I1.M01 { add{} remove{} } } interface I7 : I1 { abstract static event System.Action M01; } interface I8 : I1 { abstract static event System.Action I1.M01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,40): warning CS0108: 'I3.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // public virtual event System.Action M01 { add{} remove{} } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01", "I1.M01").WithLocation(12, 40), // (17,32): warning CS0108: 'I4.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // static event System.Action M01; Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01", "I1.M01").WithLocation(17, 32), // (22,28): error CS0539: 'I5.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01").WithLocation(22, 28), // (27,35): error CS0106: The modifier 'static' is not valid for this item // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 35), // (27,35): error CS0539: 'I6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01").WithLocation(27, 35), // (32,41): warning CS0108: 'I7.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // abstract static event System.Action M01; Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01", "I1.M01").WithLocation(32, 41), // (37,44): error CS0106: The modifier 'static' is not valid for this item // abstract static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 44), // (37,44): error CS0539: 'I8.M01' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static event System.Action I1.M01; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01").WithLocation(37, 44) ); foreach (var m01 in compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers()) { Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; abstract static event System.Action M02; } "; var source2 = typeKeyword + @" Test: I1 { static event System.Action I1.M01 { add{} remove => throw null; } public static event System.Action M02; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,35): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static event System.Action I1.M01 { add{} remove => throw null; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 35), // (5,39): warning CS0067: The event 'Test.M02' is never used // public static event System.Action M02; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "M02").WithArguments("Test.M02").WithLocation(5, 39) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,35): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static event System.Action I1.M01 { add{} remove => throw null; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 35), // (5,39): warning CS0067: The event 'Test.M02' is never used // public static event System.Action M02; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "M02").WithArguments("Test.M02").WithLocation(5, 39), // (10,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 41), // (11,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action M02; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } "; var source2 = typeKeyword + @" Test1: I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.remove' cannot implement interface member 'I1.M01.remove' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.remove", "I1.M01.remove", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.add' cannot implement interface member 'I1.M01.add' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.add", "I1.M01.add", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.remove' cannot implement interface member 'I1.M01.remove' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.remove", "I1.M01.remove", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.add' cannot implement interface member 'I1.M01.add' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.add", "I1.M01.add", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12), // (9,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } "; var source2 = typeKeyword + @" Test1: I1 { static event System.Action I1.M01 { add => throw null; remove => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static event System.Action I1.M01 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 35) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static event System.Action I1.M01 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 35), // (9,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C : I1 { public static event System.Action M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; var m01Remove = m01.RemoveMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.False(cM01Add.HasRuntimeSpecialName); Assert.True(cM01Add.HasSpecialName); Assert.Equal("void C.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.False(cM01Remove.HasRuntimeSpecialName); Assert.True(cM01Remove.HasSpecialName); Assert.Equal("void C.M01.remove", cM01Remove.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Add.ExplicitInterfaceImplementations); Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C : I1 { static event System.Action I1.M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; var m01Remove = m01.RemoveMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C.I1.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.False(cM01Add.HasRuntimeSpecialName); Assert.True(cM01Add.HasSpecialName); Assert.Equal("void C.I1.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.False(cM01Remove.HasRuntimeSpecialName); Assert.True(cM01Remove.HasSpecialName); Assert.Equal("void C.I1.M01.remove", cM01Remove.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static event System.Action M01; } public class C1 { public static event System.Action M01 { add => throw null; remove {} } } public class C2 : C1, I1 { static event System.Action I1.M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<EventSymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var cM01 = (EventSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C2.I1.M01", cM01.ToTestDisplayString()); Assert.Same(cM01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(cM01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, cM01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, cM01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig specialname static void I1.add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::add_M01(class [mscorlib]System.Action) IL_0000: ret } .method private hidebysig specialname static void I1.remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::remove_M01(class [mscorlib]System.Action) IL_0000: ret } .event [mscorlib]System.Action I1.M01 { .addon void C1::I1.add_M01(class [mscorlib]System.Action) .removeon void C1::I1.remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void C1::add_M01(class [mscorlib]System.Action) .removeon void C1::remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig specialname static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void C2::add_M01(class [mscorlib]System.Action) .removeon void C2::remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c1M01 = (EventSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C1.I1.M01", c1M01.ToTestDisplayString()); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c2.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c4.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c4.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (EventSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C2.M01", c2M01.ToTestDisplayString()); Assert.Same(c2M01.AddMethod, c5.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c2M01.RemoveMethod, c5.FindImplementationForInterfaceMember(m01.RemoveMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticEvent_11() { // Ignore invalid metadata (non-abstract static virtual method). scenario1(); scenario2(); scenario3(); void scenario1() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname static virtual void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static virtual void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,34): error CS0539: 'C1.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c.FindImplementationForInterfaceMember(m01)); Assert.Null(c.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c.FindImplementationForInterfaceMember(m01.RemoveMethod)); } } void scenario2() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname static virtual void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { add {} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C1.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.Equal("void C1.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.Equal("void C1.M01.remove", cM01Remove.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.RemoveMethod)); if (module is PEModuleSymbol) { Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01Add.ExplicitInterfaceImplementations); } Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,46): error CS0550: 'C1.I1.M01.remove' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "remove").WithArguments("C1.I1.M01.remove", "I1.M01").WithLocation(4, 46) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static event System.Action M01 { add{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { add{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation5.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source6 = @" public class C1 : I1 { public static event System.Action M01 { remove{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.add' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.add").WithLocation(2, 19), // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source7 = @" public class C1 : I1 { static event System.Action I1.M01 { remove{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.add' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.add").WithLocation(2, 19), // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34), // (4,40): error CS0550: 'C1.I1.M01.remove' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "remove").WithArguments("C1.I1.M01.remove", "I1.M01").WithLocation(4, 40) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } void scenario3() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname static virtual void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { remove {} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var m01Remove = m01.RemoveMethod; Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C1.M01", cM01.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.Equal("void C1.M01.remove", cM01Remove.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.Equal("void C1.M01.add", cM01Add.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.AddMethod)); if (module is PEModuleSymbol) { Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Add.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,40): error CS0550: 'C1.I1.M01.add' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "add").WithArguments("C1.I1.M01.add", "I1.M01").WithLocation(4, 40) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static event System.Action M01 { remove{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation5.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); var source6 = @" public class C1 : I1 { public static event System.Action M01 { add{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.remove' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.remove").WithLocation(2, 19), // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source7 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.remove' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.remove").WithLocation(2, 19), // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34), // (4,40): error CS0550: 'C1.I1.M01.add' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "add").WithArguments("C1.I1.M01.add", "I1.M01").WithLocation(4, 40) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig specialname static void I1.add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::add_M01(class [mscorlib]System.Action) IL_0000: ret } .method private hidebysig specialname static void I1.remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::remove_M01(class [mscorlib]System.Action) IL_0000: ret } .event [mscorlib]System.Action I1.M01 { .addon void I2::I1.add_M01(class [mscorlib]System.Action) .removeon void I2::I1.remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.RemoveMethod)); var i2M01 = i2.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, i2M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, i2M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticEvent_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static event System.Action M01; } class C1 { public static event System.Action M01 { add => throw null; remove{} } } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Add = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.AddMethod); var c2M01Remove = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Add.MethodKind); Assert.False(c2M01Add.HasRuntimeSpecialName); Assert.False(c2M01Add.HasSpecialName); Assert.Equal("void C2.I1.add_M01(System.Action value)", c2M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c2M01Add.ExplicitInterfaceImplementations.Single()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Remove.MethodKind); Assert.False(c2M01Remove.HasRuntimeSpecialName); Assert.False(c2M01Remove.HasSpecialName); Assert.Equal("void C2.I1.remove_M01(System.Action value)", c2M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c2M01Remove.ExplicitInterfaceImplementations.Single()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c2M01); var c1M01 = module.GlobalNamespace.GetMember<EventSymbol>("C1.M01"); var c1M01Add = c1M01.AddMethod; var c1M01Remove = c1M01.RemoveMethod; Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c1M01Add.MethodKind); Assert.False(c1M01Add.HasRuntimeSpecialName); Assert.True(c1M01Add.HasSpecialName); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c1M01Remove.MethodKind); Assert.False(c1M01Remove.HasRuntimeSpecialName); Assert.True(c1M01Remove.HasSpecialName); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); } else { Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Equal("event System.Action C1.M01", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.EventAdd, c2M01Add.MethodKind); Assert.False(c2M01Add.HasRuntimeSpecialName); Assert.True(c2M01Add.HasSpecialName); Assert.Same(c2M01.AddMethod, c2M01Add); Assert.Empty(c2M01Add.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.EventRemove, c2M01Remove.MethodKind); Assert.False(c2M01Remove.HasRuntimeSpecialName); Assert.True(c2M01Remove.HasSpecialName); Assert.Same(c2M01.RemoveMethod, c2M01Remove); Assert.Empty(c2M01Remove.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C2.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.remove"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticEvent_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action`1<int32 modopt(I1)> 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action`1<int32 modopt(I1)> 'value' ) cil managed { } .event class [mscorlib]System.Action`1<int32 modopt(I1)> M01 { .addon void I1::add_M01(class [mscorlib]System.Action`1<int32 modopt(I1)>) .removeon void I1::remove_M01(class [mscorlib]System.Action`1<int32 modopt(I1)>) } } .class interface public auto ansi abstract I2 { .method public hidebysig specialname abstract virtual static void add_M02 ( class [mscorlib]System.Action modopt(I1) 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void modopt(I2) remove_M02 ( class [mscorlib]System.Action 'value' ) cil managed { } .event class [mscorlib]System.Action M02 { .addon void I2::add_M02(class [mscorlib]System.Action modopt(I1)) .removeon void modopt(I2) I2::remove_M02(class [mscorlib]System.Action) } } "; var source1 = @" class C1 : I1 { public static event System.Action<int> M01 { add => throw null; remove{} } } class C2 : I1 { static event System.Action<int> I1.M01 { add => throw null; remove{} } } #pragma warning disable CS0067 // The event 'C3.M02' is never used class C3 : I2 { public static event System.Action M02; } class C4 : I2 { static event System.Action I2.M02 { add => throw null; remove{} } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); var c1M01Add = c1M01.AddMethod; var c1M01Remove = c1M01.RemoveMethod; Assert.Equal("event System.Action<System.Int32> C1.M01", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Equal(MethodKind.EventAdd, c1M01Add.MethodKind); Assert.Equal("void C1.M01.add", c1M01Add.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32> value", c1M01Add.Parameters.Single().ToTestDisplayString()); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c1M01Remove.MethodKind); Assert.Equal("void C1.M01.remove", c1M01Remove.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32> value", c1M01Remove.Parameters.Single().ToTestDisplayString()); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { c1M01Add = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Add.MethodKind); Assert.Equal("void C1.I1.add_M01(System.Action<System.Int32 modopt(I1)> value)", c1M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c1M01Add.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); c1M01Remove = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Remove.MethodKind); Assert.Equal("void C1.I1.remove_M01(System.Action<System.Int32 modopt(I1)> value)", c1M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c1M01Remove.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); // Forwarding methods aren't tied to an event Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01Add, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01Remove, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Add = c2M01.AddMethod; var c2M01Remove = c2M01.RemoveMethod; Assert.Equal("event System.Action<System.Int32 modopt(I1)> C2.I1.M01", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c2M01Add.MethodKind); Assert.Equal("void C2.I1.M01.add", c2M01Add.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32 modopt(I1)> value", c2M01Add.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.AddMethod, c2M01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Add, c2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c2M01Remove.MethodKind); Assert.Equal("void C2.I1.M01.remove", c2M01Remove.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32 modopt(I1)> value", c2M01Remove.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c2M01Remove.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Remove, c2.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(c2M01, c2.GetMembers().OfType<EventSymbol>().Single()); Assert.Equal(2, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m02 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c3M02 = c3.GetMembers().OfType<EventSymbol>().Single(); var c3M02Add = c3M02.AddMethod; var c3M02Remove = c3M02.RemoveMethod; Assert.Equal("event System.Action C3.M02", c3M02.ToTestDisplayString()); Assert.Empty(c3M02.ExplicitInterfaceImplementations); Assert.True(c3M02.IsStatic); Assert.False(c3M02.IsAbstract); Assert.False(c3M02.IsVirtual); Assert.Equal(MethodKind.EventAdd, c3M02Add.MethodKind); Assert.Equal("void C3.M02.add", c3M02Add.ToTestDisplayString()); Assert.Equal("System.Action value", c3M02Add.Parameters.Single().ToTestDisplayString()); Assert.Empty(c3M02Add.ExplicitInterfaceImplementations); Assert.True(c3M02Add.IsStatic); Assert.False(c3M02Add.IsAbstract); Assert.False(c3M02Add.IsVirtual); Assert.False(c3M02Add.IsMetadataVirtual()); Assert.False(c3M02Add.IsMetadataFinal); Assert.False(c3M02Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c3M02Remove.MethodKind); Assert.Equal("void C3.M02.remove", c3M02Remove.ToTestDisplayString()); Assert.Equal("System.Void", c3M02Remove.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Empty(c3M02Remove.ExplicitInterfaceImplementations); Assert.True(c3M02Remove.IsStatic); Assert.False(c3M02Remove.IsAbstract); Assert.False(c3M02Remove.IsVirtual); Assert.False(c3M02Remove.IsMetadataVirtual()); Assert.False(c3M02Remove.IsMetadataFinal); Assert.False(c3M02Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { c3M02Add = (MethodSymbol)c3.FindImplementationForInterfaceMember(m02.AddMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c3M02Add.MethodKind); Assert.Equal("void C3.I2.add_M02(System.Action modopt(I1) value)", c3M02Add.ToTestDisplayString()); Assert.Same(m02.AddMethod, c3M02Add.ExplicitInterfaceImplementations.Single()); Assert.True(c3M02Add.IsStatic); Assert.False(c3M02Add.IsAbstract); Assert.False(c3M02Add.IsVirtual); Assert.False(c3M02Add.IsMetadataVirtual()); Assert.False(c3M02Add.IsMetadataFinal); Assert.False(c3M02Add.IsMetadataNewSlot()); c3M02Remove = (MethodSymbol)c3.FindImplementationForInterfaceMember(m02.RemoveMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c3M02Remove.MethodKind); Assert.Equal("void modopt(I2) C3.I2.remove_M02(System.Action value)", c3M02Remove.ToTestDisplayString()); Assert.Same(m02.RemoveMethod, c3M02Remove.ExplicitInterfaceImplementations.Single()); Assert.True(c3M02Remove.IsStatic); Assert.False(c3M02Remove.IsAbstract); Assert.False(c3M02Remove.IsVirtual); Assert.False(c3M02Remove.IsMetadataVirtual()); Assert.False(c3M02Remove.IsMetadataFinal); Assert.False(c3M02Remove.IsMetadataNewSlot()); // Forwarding methods aren't tied to an event Assert.Null(c3.FindImplementationForInterfaceMember(m02)); } else { Assert.Same(c3M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c3M02Add, c3.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.Same(c3M02Remove, c3.FindImplementationForInterfaceMember(m02.RemoveMethod)); } var c4 = module.GlobalNamespace.GetTypeMember("C4"); var c4M02 = (EventSymbol)c4.FindImplementationForInterfaceMember(m02); var c4M02Add = c4M02.AddMethod; var c4M02Remove = c4M02.RemoveMethod; Assert.Equal("event System.Action C4.I2.M02", c4M02.ToTestDisplayString()); // Signatures of accessors are lacking custom modifiers due to https://github.com/dotnet/roslyn/issues/53390. Assert.True(c4M02.IsStatic); Assert.False(c4M02.IsAbstract); Assert.False(c4M02.IsVirtual); Assert.Same(m02, c4M02.ExplicitInterfaceImplementations.Single()); Assert.True(c4M02Add.IsStatic); Assert.False(c4M02Add.IsAbstract); Assert.False(c4M02Add.IsVirtual); Assert.False(c4M02Add.IsMetadataVirtual()); Assert.False(c4M02Add.IsMetadataFinal); Assert.False(c4M02Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c4M02Add.MethodKind); Assert.Equal("void C4.I2.M02.add", c4M02Add.ToTestDisplayString()); Assert.Equal("System.Action value", c4M02Add.Parameters.Single().ToTestDisplayString()); Assert.Equal("System.Void", c4M02Add.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Same(m02.AddMethod, c4M02Add.ExplicitInterfaceImplementations.Single()); Assert.Same(c4M02Add, c4.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.True(c4M02Remove.IsStatic); Assert.False(c4M02Remove.IsAbstract); Assert.False(c4M02Remove.IsVirtual); Assert.False(c4M02Remove.IsMetadataVirtual()); Assert.False(c4M02Remove.IsMetadataFinal); Assert.False(c4M02Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c4M02Remove.MethodKind); Assert.Equal("void C4.I2.M02.remove", c4M02Remove.ToTestDisplayString()); Assert.Equal("System.Action value", c4M02Remove.Parameters.Single().ToTestDisplayString()); Assert.Equal("System.Void", c4M02Remove.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Same(m02.RemoveMethod, c4M02Remove.ExplicitInterfaceImplementations.Single()); Assert.Same(c4M02Remove, c4.FindImplementationForInterfaceMember(m02.RemoveMethod)); Assert.Same(c4M02, c4.GetMembers().OfType<EventSymbol>().Single()); Assert.Equal(2, c4.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); } verifier.VerifyIL("C1.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C1.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.remove"" IL_0006: ret } "); verifier.VerifyIL("C3.I2.add_M02", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C3.M02.add"" IL_0006: ret } "); verifier.VerifyIL("C3.I2.remove_M02", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C3.M02.remove"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticEvent_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static event System.Action M01; abstract static event System.Action M02; } public class C1 { public static event System.Action M01 { add => throw null; remove{} } } public class C2 : C1, I1 { static event System.Action I1.M02 { add => throw null; remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<EventSymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<EventSymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<EventSymbol>("M01"); Assert.Equal("event System.Action C1.M01", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); var c1M01Add = c1M01.AddMethod; Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); var c1M01Remove = c1M01.RemoveMethod; Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01Add = c3.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal("void C2.I1.add_M01(System.Action value)", c2M01Add.ToTestDisplayString()); var c2M01Remove = c3.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal("void C2.I1.remove_M01(System.Action value)", c2M01Remove.ToTestDisplayString()); // Forwarding methods for accessors aren't tied to an event Assert.Null(c3.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<EventSymbol>().Single(); var c2M02 = c3.BaseType().GetMember<EventSymbol>("I1.M02"); Assert.Equal("event System.Action C2.I1.M02", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c2M02.AddMethod, c3.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.Same(c2M02.RemoveMethod, c3.FindImplementationForInterfaceMember(m02.RemoveMethod)); } } [Fact] public void ImplementAbstractStaticEvent_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static event System.Action M01; } public class C1 : I1 { public static event System.Action M01 { add{} remove => throw null; } } public class C2 : C1 { new public static event System.Action M01 { add{} remove => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C3.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.remove"" IL_0006: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<EventSymbol>("M01"); var c2M01Add = c2M01.AddMethod; var c2M01Remove = c2M01.RemoveMethod; Assert.Equal("event System.Action C2.M01", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.Empty(c2M01Add.ExplicitInterfaceImplementations); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); Assert.Empty(c2M01Remove.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (EventSymbol)c3.FindImplementationForInterfaceMember(m01); // Forwarding methods for accessors aren't tied to an event Assert.Null(c3M01); var c3M01Add = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal("void C3.I1.add_M01(System.Action value)", c3M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c3M01Add.ExplicitInterfaceImplementations.Single()); var c3M01Remove = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal("void C3.I1.remove_M01(System.Action value)", c3M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c3M01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c2M01Add, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c2M01Remove, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_19(bool genericFirst) { // An "ambiguity" in implicit/explicit implementation declared in generic base class. var generic = @" public static event System.Action<T> M01 { add{} remove{} } "; var nonGeneric = @" static event System.Action<int> I1.M01 { add{} remove{} } "; var source1 = @" public interface I1 { abstract static event System.Action<int> M01; } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<EventSymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action<System.Int32> C1<T>.I1.M01", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_20(bool genericFirst) { // Same as ImplementAbstractStaticEvent_19 only interface is generic too. var generic = @" static event System.Action<T> I1<T>.M01 { add{} remove{} } "; var nonGeneric = @" public static event System.Action<int> M01 { add{} remove{} } "; var source1 = @" public interface I1<T> { abstract static event System.Action<T> M01; } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<EventSymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action<T> C1<T>.I1<T>.M01", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } private static string ConversionOperatorName(string op) => op switch { "implicit" => WellKnownMemberNames.ImplicitConversionName, "explicit" => WellKnownMemberNames.ExplicitConversionName, _ => throw TestExceptionUtilities.UnexpectedValue(op) }; [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = ConversionOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public " + op + @" operator int(C2 x) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static " + op + @" operator int(C3 x) => throw null; } " + typeKeyword + @" C4 : I1<C4> { " + op + @" I1<C4>.operator int(C4 x) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static " + op + @" operator long(C5 x) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static " + op + @" I1<C6>.operator long(C6 x) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static int " + opName + @"(C7 x) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static int I1<C8>." + opName + @"(C8 x) => throw null; } public interface I2<T> where T : I2<T> { abstract static int " + opName + @"(T x); } " + typeKeyword + @" C9 : I2<C9> { public static " + op + @" operator int(C9 x) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static " + op + @" I2<C10>.operator int(C10 x) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.explicit operator int(C1)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>." + op + " operator int(C1)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.explicit operator int(C2)'. 'C2.explicit operator int(C2)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>." + op + " operator int(C2)", "C2." + op + " operator int(C2)").WithLocation(12, 10), // (14,30): error CS0558: User-defined operator 'C2.explicit operator int(C2)' must be declared static and public // public explicit operator int(C2 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("C2." + op + " operator int(C2)").WithLocation(14, 30), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.explicit operator int(C3)'. 'C3.explicit operator int(C3)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>." + op + " operator int(C3)", "C3." + op + " operator int(C3)").WithLocation(18, 10), // (20,30): error CS0558: User-defined operator 'C3.explicit operator int(C3)' must be declared static and public // static explicit operator int(C3 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("C3." + op + " operator int(C3)").WithLocation(20, 30), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.explicit operator int(C4)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>." + op + " operator int(C4)").WithLocation(24, 10), // (26,30): error CS8930: Explicit implementation of a user-defined operator 'C4.explicit operator int(C4)' must be declared static // explicit I1<C4>.operator int(C4 x) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, "int").WithArguments("C4." + op + " operator int(C4)").WithLocation(26, 30), // (26,30): error CS0539: 'C4.explicit operator int(C4)' in explicit interface declaration is not found among members of the interface that can be implemented // explicit I1<C4>.operator int(C4 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C4." + op + " operator int(C4)").WithLocation(26, 30), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.explicit operator int(C5)'. 'C5.explicit operator long(C5)' cannot implement 'I1<C5>.explicit operator int(C5)' because it does not have the matching return type of 'int'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>." + op + " operator int(C5)", "C5." + op + " operator long(C5)", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.explicit operator int(C6)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>." + op + " operator int(C6)").WithLocation(36, 10), // (38,37): error CS0539: 'C6.explicit operator long(C6)' in explicit interface declaration is not found among members of the interface that can be implemented // static explicit I1<C6>.operator long(C6 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "long").WithArguments("C6." + op + " operator long(C6)").WithLocation(38, 37), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.explicit operator int(C7)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>." + op + " operator int(C7)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.explicit operator int(C8)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>." + op + " operator int(C8)").WithLocation(48, 10), // (50,23): error CS0539: 'C8.op_Explicit(C8)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C8>.op_Explicit(C8 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8)").WithLocation(50, 23), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_Explicit(C9)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_Explicit(C10)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10)").WithLocation(65, 11), // (67,38): error CS0539: 'C10.explicit operator int(C10)' in explicit interface declaration is not found among members of the interface that can be implemented // static explicit I2<C10>.operator int(C10 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C10." + op + " operator int(C10)").WithLocation(67, 38) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_03([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } interface I2<T> : I1<T> where T : I1<T> {} interface I3<T> : I1<T> where T : I1<T> { " + op + @" operator int(T x) => default; } interface I4<T> : I1<T> where T : I1<T> { static " + op + @" operator int(T x) => default; } interface I5<T> : I1<T> where T : I1<T> { " + op + @" I1<T>.operator int(T x) => default; } interface I6<T> : I1<T> where T : I1<T> { static " + op + @" I1<T>.operator int(T x) => default; } interface I7<T> : I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public interface I11<T> where T : I11<T> { abstract static " + op + @" operator int(T x); } interface I8<T> : I11<T> where T : I8<T> { " + op + @" operator int(T x) => default; } interface I9<T> : I11<T> where T : I9<T> { static " + op + @" operator int(T x) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static " + op + @" operator int(T x); } interface I12<T> : I11<T> where T : I12<T> { static " + op + @" I11<T>.operator int(T x) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static " + op + @" I11<T>.operator int(T x); } interface I14<T> : I1<T> where T : I1<T> { abstract static " + op + @" I1<T>.operator int(T x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,23): error CS0556: User-defined conversion must convert to or from the enclosing type // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(12, 23), // (12,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(12, 23), // (17,30): error CS0556: User-defined conversion must convert to or from the enclosing type // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(17, 30), // (17,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(17, 30), // (22,29): error CS8930: Explicit implementation of a user-defined operator 'I5<T>.implicit operator int(T)' must be declared static // implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, "int").WithArguments("I5<T>." + op + " operator int(T)").WithLocation(22, 29), // (22,29): error CS0539: 'I5<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I5<T>." + op + " operator int(T)").WithLocation(22, 29), // (27,36): error CS0539: 'I6<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I6<T>." + op + " operator int(T)").WithLocation(27, 36), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "int").WithLocation(32, 39), // (42,23): error CS0556: User-defined conversion must convert to or from the enclosing type // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(42, 23), // (42,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(42, 23), // (47,30): error CS0556: User-defined conversion must convert to or from the enclosing type // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(47, 30), // (47,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(47, 30), // (57,37): error CS0539: 'I12<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I11<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I12<T>." + op + " operator int(T)").WithLocation(57, 37), // (62,46): error CS0106: The modifier 'abstract' is not valid for this item // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(62, 46), // (62,46): error CS0501: 'I13<T>.implicit operator int(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "int").WithArguments("I13<T>." + op + " operator int(T)").WithLocation(62, 46), // (62,46): error CS0539: 'I13<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I13<T>." + op + " operator int(T)").WithLocation(62, 46), // (67,45): error CS0106: The modifier 'abstract' is not valid for this item // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(67, 45), // (67,45): error CS0501: 'I14<T>.implicit operator int(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "int").WithArguments("I14<T>." + op + " operator int(T)").WithLocation(67, 45), // (67,45): error CS0539: 'I14<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I14<T>." + op + " operator int(T)").WithLocation(67, 45) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_04([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I2<T> where T : I2<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1 : I2<Test1> { static " + op + @" I2<Test1>.operator int(Test1 x) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static " + op + @" operator int(Test2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,21): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static explicit I2<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I2<Test1>.").WithArguments("static abstract members in interfaces").WithLocation(4, 21) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,21): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static explicit I2<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I2<Test1>.").WithArguments("static abstract members in interfaces").WithLocation(4, 21), // (14,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(14, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_05([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static " + op + @" operator int(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.explicit operator int(Test1)' cannot implement interface member 'I1<Test1>.explicit operator int(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1." + op + " operator int(Test1)", "I1<Test1>." + op + " operator int(Test1)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.explicit operator int(Test1)' cannot implement interface member 'I1<Test1>.explicit operator int(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1." + op + " operator int(Test1)", "I1<Test1>." + op + " operator int(Test1)", "Test1").WithLocation(2, 12), // (9,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(9, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_06([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1 : I1<Test1> { static " + op + @" I1<Test1>.operator int(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,40): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static explicit I1<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 40) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,40): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static explicit I1<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 40), // (9,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(9, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_07([CombinatorialValues("implicit", "explicit")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); abstract static " + op + @" operator long(T x); } " + typeKeyword + @" C : I1<C> { public static " + op + @" operator long(C x) => default; public static " + op + @" operator int(C x) => default; } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = i1.GetMembers().OfType<MethodSymbol>().First(); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("System.Int32 C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } var m02 = i1.GetMembers().OfType<MethodSymbol>().ElementAt(1); var cM02 = (MethodSymbol)c.FindImplementationForInterfaceMember(m02); Assert.True(cM02.IsStatic); Assert.False(cM02.IsAbstract); Assert.False(cM02.IsVirtual); Assert.False(cM02.IsMetadataVirtual()); Assert.False(cM02.IsMetadataFinal); Assert.False(cM02.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, cM02.MethodKind); Assert.False(cM02.HasRuntimeSpecialName); Assert.True(cM02.HasSpecialName); Assert.Equal("System.Int64 C." + opName + "(C x)", cM02.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m02, cM02.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM02.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_08([CombinatorialValues("implicit", "explicit")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" interface I1<T> where T : I1<T> { abstract static " + op + @" operator C(T x); abstract static " + op + @" operator int(T x); } " + typeKeyword + @" C : I1<C> { static " + op + @" I1<C>.operator int(C x) => int.MaxValue; static " + op + @" I1<C>.operator C(C x) => default; } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal("default", node.ToString()); Assert.Equal("C", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<ConversionOperatorDeclarationSyntax>()); Assert.Equal("C C.I1<C>." + opName + "(C x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<MethodSymbol>().First(); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("C C.I1<C>." + opName + "(C x)", cM01.ToTestDisplayString()); Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); var m02 = c.Interfaces().Single().GetMembers().OfType<MethodSymbol>().ElementAt(1); var cM02 = (MethodSymbol)c.FindImplementationForInterfaceMember(m02); Assert.True(cM02.IsStatic); Assert.False(cM02.IsAbstract); Assert.False(cM02.IsVirtual); Assert.False(cM02.IsMetadataVirtual()); Assert.False(cM02.IsMetadataFinal); Assert.False(cM02.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM02.MethodKind); Assert.False(cM02.HasRuntimeSpecialName); Assert.False(cM02.HasSpecialName); Assert.Equal("System.Int32 C.I1<C>." + opName + "(C x)", cM02.ToTestDisplayString()); Assert.Equal(m02, cM02.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_09([CombinatorialValues("implicit", "explicit")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = ConversionOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.I1<C2>." + opName + "(C2 x)", cM01.ToTestDisplayString()); Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_10([CombinatorialValues("implicit", "explicit")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 " + opName + @" ( !T x ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements class I1`1<class C1> { .method private hidebysig static int32 'I1<C1>." + opName + @"' ( class C1 x ) cil managed { .override method int32 class I1`1<class C1>::" + opName + @"(!0) IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig static specialname int32 " + opName + @" ( class C1 x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2053 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: nop IL_0007: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements class I1`1<class C1> { .method public hidebysig static specialname int32 " + opName + @" ( class C1 x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1<C1> { } public class C5 : C2, I1<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Equal(MethodKind.Conversion, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2." + opName + "(C1 x)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.Conversion, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_11([CombinatorialValues("implicit", "explicit")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname virtual static int32 " + opName + @" ( !T x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } } "; var source1 = @" public class C1 : I1<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1<C1> { static " + op + @" I1<C1>.operator int(C1 x) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,37): error CS0539: 'C1.implicit operator int(C1)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I1<C1>.operator int(C1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C1." + op + " operator int(C1)").WithLocation(4, 37) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("System.Int32 I1<C1>." + opName + "(C1 x)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_12([CombinatorialValues("implicit", "explicit")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 " + opName + @" ( !T x ) cil managed { } } .class interface public auto ansi abstract I2`1<(class I1`1<!T>) T> implements class I1`1<!T> { .method private hidebysig static int32 'I1<!T>." + opName + @"' ( !T x ) cil managed { .override method int32 class I1`1<!T>::" + opName + @"(!0) IL_0000: ldc.i4.0 IL_0001: ret } } "; var source1 = @" public class C1 : I2<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1<C1>.explicit operator int(C1)' // public class C1 : I2<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C1>").WithArguments("C1", "I1<C1>." + op + " operator int(C1)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_13([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static " + op + @" operator C1<T>(T x); } public partial class C1<T> { public static " + op + @" operator C1<T>(T x) => default; } public class C2 : C1<C2>, I1<C2> { } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var i1 = c2.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.False(c2M01.HasSpecialName); Assert.Equal("C1<C2> C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.False(c1M01.HasRuntimeSpecialName); Assert.True(c1M01.HasSpecialName); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Conversion, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.True(c2M01.HasSpecialName); Assert.Equal("C1<C2> C1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1<C2>." + opName + "(C2)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""C1<C2> C1<C2>." + opName + @"(C2)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_14([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static " + op + @" operator int(C1 x) => default; } class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("System.Int32 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("System.Int32 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.Equal("System.Int32 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("System.Int32 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int C1." + opName + @"(C1)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_15([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static " + op + @" operator C1<T>(T x); abstract static " + op + @" operator T(int x); } public partial class C1<T> { public static " + op + @" operator C1<T>(T x) => default; } public class C2 : C1<C2>, I1<C2> { static " + op + @" I1<C2>.operator C2(int x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = ConversionOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().First(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C1<C2> C1<C2>." + opName + "(C2 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<C2> C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Equal(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().ElementAt(1); var c2M02 = c3.BaseType().GetMembers("I1<C2>." + opName).OfType<MethodSymbol>().First(); Assert.Equal("C2 C2.I1<C2>." + opName + "(System.Int32 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_18([CombinatorialValues("implicit", "explicit")] string op, bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static " + op + @" operator U(C1<T, U> x) => default; "; var nonGeneric = @" public static " + op + @" operator int(C1<T, U> x) => default; "; var source1 = @" public interface I1<T, U> where T : I1<T, U> { abstract static " + op + @" operator U(T x); } public class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>." + opName + "(C1<T, U> x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>." + opName + "(C1<T, U> x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_20([CombinatorialValues("implicit", "explicit")] string op, bool genericFirst) { // Same as ImplementAbstractStaticConversionOperator_18 only implementation is explicit in source. var generic = @" static " + op + @" I1<C1<T, U>, U>.operator U(C1<T, U> x) => default; "; var nonGeneric = @" public static " + op + @" operator int(C1<T, U> x) => default; "; var source1 = @" public interface I1<T, U> where T : I1<T, U> { abstract static " + op + @" operator U(T x); } public class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>.I1<C1<T, U>, U>." + opName + "(C1<T, U> x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class C1 : I1<C1> { static " + op + @" I1<C1>.operator int(C1 x) => default; } class C2 : I1<C2> { private static " + op + @" I1<C2>.operator int(C2 x) => default; } class C3 : I1<C3> { protected static " + op + @" I1<C3>.operator int(C3 x) => default; } class C4 : I1<C4> { internal static " + op + @" I1<C4>.operator int(C4 x) => default; } class C5 : I1<C5> { protected internal static " + op + @" I1<C5>.operator int(C5 x) => default; } class C6 : I1<C6> { private protected static " + op + @" I1<C6>.operator int(C6 x) => default; } class C7 : I1<C7> { public static " + op + @" I1<C7>.operator int(C7 x) => default; } class C9 : I1<C9> { async static " + op + @" I1<C9>.operator int(C9 x) => default; } class C10 : I1<C10> { unsafe static " + op + @" I1<C10>.operator int(C10 x) => default; } class C11 : I1<C11> { static readonly " + op + @" I1<C11>.operator int(C11 x) => default; } class C12 : I1<C12> { extern static " + op + @" I1<C12>.operator int(C12 x); } class C13 : I1<C13> { abstract static " + op + @" I1<C13>.operator int(C13 x) => default; } class C14 : I1<C14> { virtual static " + op + @" I1<C14>.operator int(C14 x) => default; } class C15 : I1<C15> { sealed static " + op + @" I1<C15>.operator int(C15 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.WRN_ExternMethodNoImplementation).Verify( // (16,45): error CS0106: The modifier 'private' is not valid for this item // private static explicit I1<C2>.operator int(C2 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("private").WithLocation(16, 45), // (22,47): error CS0106: The modifier 'protected' is not valid for this item // protected static explicit I1<C3>.operator int(C3 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("protected").WithLocation(22, 47), // (28,46): error CS0106: The modifier 'internal' is not valid for this item // internal static explicit I1<C4>.operator int(C4 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("internal").WithLocation(28, 46), // (34,56): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static explicit I1<C5>.operator int(C5 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("protected internal").WithLocation(34, 56), // (40,55): error CS0106: The modifier 'private protected' is not valid for this item // private protected static explicit I1<C6>.operator int(C6 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("private protected").WithLocation(40, 55), // (46,44): error CS0106: The modifier 'public' is not valid for this item // public static explicit I1<C7>.operator int(C7 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("public").WithLocation(46, 44), // (52,43): error CS0106: The modifier 'async' is not valid for this item // async static explicit I1<C9>.operator int(C9 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("async").WithLocation(52, 43), // (64,47): error CS0106: The modifier 'readonly' is not valid for this item // static readonly explicit I1<C11>.operator int(C11 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("readonly").WithLocation(64, 47), // (76,47): error CS0106: The modifier 'abstract' is not valid for this item // abstract static explicit I1<C13>.operator int(C13 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(76, 47), // (82,46): error CS0106: The modifier 'virtual' is not valid for this item // virtual static explicit I1<C14>.operator int(C14 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("virtual").WithLocation(82, 46), // (88,45): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit I1<C15>.operator int(C15 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(88, 45) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : struct, I1<T> { abstract static " + op + @" operator int(T x); } class C1 { static " + op + @" I1<int>.operator int(int x) => default; } class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,21): error CS0540: 'C1.I1<int>.implicit operator int(int)': containing type does not implement interface 'I1<int>' // static implicit I1<int>.operator int(int x) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<int>").WithArguments("C1.I1<int>." + op + " operator int(int)", "I1<int>").WithLocation(9, 21), // (9,21): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion from 'int' to 'I1<int>'. // static implicit I1<int>.operator int(int x) => default; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "I1<int>").WithArguments("I1<T>", "I1<int>", "T", "int").WithLocation(9, 21), // (12,7): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // class C2 : I1<C2> Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 7), // (14,21): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static implicit I1<C2>.operator int(C2 x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 21) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { string cast = (op == "explicit" ? "(int)" : ""); var source1 = @" interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); static int M02(I1<T> x) { return " + cast + @"x; } int M03(I1<T> y) { return " + cast + @"y; } } class Test<T> where T : I1<T> { static int MT1(I1<T> a) { return " + cast + @"a; } static void MT2() { _ = (System.Linq.Expressions.Expression<System.Func<T, int>>)((T b) => " + cast + @"b); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (8,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)x; Diagnostic(error, cast + "x").WithArguments("I1<T>", "int").WithLocation(8, 16), // (13,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)y; Diagnostic(error, cast + "y").WithArguments("I1<T>", "int").WithLocation(13, 16), // (21,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)a; Diagnostic(error, cast + "a").WithArguments("I1<T>", "int").WithLocation(21, 16), // (26,80): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Func<T, int>>)((T b) => (int)b); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, cast + "b").WithLocation(26, 80) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1 { abstract static implicit operator bool(I1 x); static void M02((int, C<I1>) x) { _ = x " + op + @" x; } void M03((int, C<I1>) y) { _ = y " + op + @" y; } } class Test { static void MT1((int, C<I1>) a) { _ = a " + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b " + op + @" b).ToString()); } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0552: 'I1.implicit operator bool(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator bool(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "bool").WithArguments("I1.implicit operator bool(I1)").WithLocation(4, 39), // (9,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = x == x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x " + op + " x").WithArguments("I1", "bool").WithLocation(9, 13), // (14,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = y == y; Diagnostic(ErrorCode.ERR_NoImplicitConv, "y " + op + " y").WithArguments("I1", "bool").WithLocation(14, 13), // (22,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = a == a; Diagnostic(ErrorCode.ERR_NoImplicitConv, "a " + op + " a").WithArguments("I1", "bool").WithLocation(22, 13), // (27,98): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(27, 98) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_03([CombinatorialValues("implicit", "explicit")] string op) { string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class Test { static int M02<T, U>(T x) where T : U where U : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int? M03<T, U>(T y) where T : U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"y; } static int? M04<T, U>(T? y) where T : struct, U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"y; } static int? M05<T, U>() where T : struct, U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"(T?)new T(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 23 (0x17) .maxstack 1 .locals init (int? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: newobj ""int?..ctor(int)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (T? V_0, int? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""int?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""int I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""int?..ctor(int)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 27 (0x1b) .maxstack 1 .locals init (int? V_0) IL_0000: nop IL_0001: call ""T System.Activator.CreateInstance<T>()"" IL_0006: constrained. ""T"" IL_000c: call ""int I1<T>." + metadataName + @"(T)"" IL_0011: newobj ""int?..ctor(int)"" IL_0016: stloc.0 IL_0017: br.s IL_0019 IL_0019: ldloc.0 IL_001a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""int I1<T>." + metadataName + @"(T)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""int I1<T>." + metadataName + @"(T)"" IL_000c: newobj ""int?..ctor(int)"" IL_0011: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (T? V_0, int? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""int?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""int I1<T>." + metadataName + @"(T)"" IL_0027: newobj ""int?..ctor(int)"" IL_002c: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 22 (0x16) .maxstack 1 IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: constrained. ""T"" IL_000b: call ""int I1<T>." + metadataName + @"(T)"" IL_0010: newobj ""int?..ctor(int)"" IL_0015: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().First(); Assert.Equal("return " + (needCast ? "(int)" : "") + @"x;", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return " + (needCast ? "(int)" : "") + @"x;') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 I1<T>." + metadataName + @"(T x)) (OperationKind.Conversion, Type: System.Int32" + (needCast ? "" : ", IsImplicit") + @") (Syntax: '" + (needCast ? "(int)" : "") + @"x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 I1<T>." + metadataName + @"(T x)) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool (T x); } class Test { static void M02<T, U>((int, C<T>) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_Implicit(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.0 IL_0032: pop IL_0033: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_Implicit(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.1 IL_0032: pop IL_0033: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_Implicit(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.0 IL_0031: pop IL_0032: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_Implicit(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.1 IL_0031: pop IL_0032: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_04([CombinatorialValues("implicit", "explicit")] string op) { bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = @" class Test { static int M02<T>(T x) where T : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,16): error CS8919: Target runtime doesn't support static abstract members in interfaces. // return (int)x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, (needCast ? "(int)" : "") + "x").WithLocation(6, 16) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(12, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool(T x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (21,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static implicit operator bool(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "bool").WithLocation(21, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_06([CombinatorialValues("implicit", "explicit")] string op) { bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = @" class Test { static int M02<T>(T x) where T : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,16): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // return x; Diagnostic(ErrorCode.ERR_FeatureInPreview, (needCast ? "(int)" : "") + "x").WithArguments("static abstract members in interfaces").WithLocation(6, 16) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(12, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool(T x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (21,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator bool(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "bool").WithArguments("abstract", "9.0", "preview").WithLocation(21, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_07([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_03 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } class Test { static T M02<T, U>(int x) where T : U where U : I1<T> { return " + (needCast ? "(T)" : "") + @"x; } static T? M03<T, U>(int y) where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"y; } static T? M04<T, U>(int? y) where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"y; } static T? M05<T, U>() where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"(T?)0; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(int)", @" { // Code size 23 (0x17) .maxstack 1 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: newobj ""T?..ctor(T)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (int? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool int?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly int int?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(int)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 23 (0x17) .maxstack 1 .locals init (T? V_0) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: newobj ""T?..ctor(T)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: newobj ""T?..ctor(T)"" IL_0011: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (int? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool int?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly int int?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""T I1<T>." + metadataName + @"(int)"" IL_0027: newobj ""T?..ctor(T)"" IL_002c: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: newobj ""T?..ctor(T)"" IL_0011: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().First(); Assert.Equal("return " + (needCast ? "(T)" : "") + @"x;", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return " + (needCast ? "(T)" : "") + @"x;') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: T I1<T>." + metadataName + @"(System.Int32 x)) (OperationKind.Conversion, Type: T" + (needCast ? "" : ", IsImplicit") + @") (Syntax: '" + (needCast ? "(T)" : "") + @"x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: T I1<T>." + metadataName + @"(System.Int32 x)) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_08([CombinatorialValues("implicit", "explicit")] string op) { // Don't look in interfaces of the effective base string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class C1<T> : I1<C1<T>> { static " + op + @" I1<C1<T>>.operator int(C1<T> x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int M03<T>(C1<T> y) where T : I1<C1<T>> { return " + (needCast ? "(int)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (16,16): error CS0030: Cannot convert type 'T' to 'int' // return (int)x; Diagnostic(error, (needCast ? "(int)" : "") + "x").WithArguments("T", "int").WithLocation(16, 16), // (21,16): error CS0030: Cannot convert type 'C1<T>' to 'int' // return (int)y; Diagnostic(error, (needCast ? "(int)" : "") + "y").WithArguments("C1<T>", "int").WithLocation(21, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_09([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_08 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } class C1<T> : I1<C1<T>> { static " + op + @" I1<C1<T>>.operator C1<T>(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1<T> { return " + (needCast ? "(T)" : "") + @"x; } static C1<T> M03<T>(int y) where T : I1<C1<T>> { return " + (needCast ? "(C1<T>)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (16,16): error CS0030: Cannot convert type 'int' to 'T' // return (T)x; Diagnostic(error, (needCast ? "(T)" : "") + "x").WithArguments("int", "T").WithLocation(16, 16), // (21,16): error CS0030: Cannot convert type 'int' to 'C1<T>' // return (C1<T>)y; Diagnostic(error, (needCast ? "(C1<T>)" : "") + "y").WithArguments("int", "C1<T>").WithLocation(21, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_10([CombinatorialValues("implicit", "explicit")] string op) { // Look in derived interfaces string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public interface I2<T> : I1<T> where T : I1<T> {} class Test { static int M02<T, U>(T x) where T : U where U : I2<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_11([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_10 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } public interface I2<T> : I1<T> where T : I1<T> {} class Test { static T M02<T, U>(int x) where T : U where U : I2<T> { return " + (needCast ? "(T)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_12([CombinatorialValues("implicit", "explicit")] string op) { // Ignore duplicate candidates string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T, U> where T : I1<T, U> where U : I1<T, U> { abstract static " + op + @" operator U(T x); } class Test { static U M02<T, U>(T x) where T : I1<T, U> where U : I1<T, U> { return " + (needCast ? "(U)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (U V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""U I1<T, U>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_13([CombinatorialValues("implicit", "explicit")] string op) { // Look in effective base string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public class C1<T> { public static " + op + @" operator int(C1<T> x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: call ""int C1<T>." + metadataName + @"(C1<T>)"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Fact] public void ConsumeAbstractConversionOperator_14() { // Same as ConsumeAbstractConversionOperator_13 only direction of conversion is flipped var source1 = @" public class C1<T> { public static explicit operator C1<T>(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1<T> { return (T)x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""C1<T> C1<T>.op_Explicit(int)"" IL_0007: unbox.any ""T"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_15([CombinatorialValues("implicit", "explicit")] string op) { // If there is a non-trivial class constraint, interfaces are not looked at. string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C1 : I1<C1> { public static " + op + @" operator int(C1 x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1, I1<C1> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: call ""int C1." + metadataName + @"(C1)"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Fact] public void ConsumeAbstractConversionOperator_16() { // Same as ConsumeAbstractConversionOperator_15 only direction of conversion is flipped var source1 = @" public interface I1<T> where T : I1<T> { abstract static explicit operator T(int x); } public class C1 : I1<C1> { public static explicit operator C1(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1, I1<C1> { return (T)x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""C1 C1.op_Explicit(int)"" IL_0007: unbox.any ""T"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_17([CombinatorialValues("implicit", "explicit")] string op) { // If there is a non-trivial class constraint, interfaces are not looked at. bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C1 { } class Test { static int M02<T, U>(T x) where T : U where U : C1, I1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int M03<T, U>(T y) where T : U where U : I1<T> { return " + (needCast ? "(int)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (15,16): error CS0030: Cannot convert type 'T' to 'int' // return (int)x; Diagnostic((op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv), (needCast ? "(int)" : "") + "x").WithArguments("T", "int").WithLocation(15, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_18([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_17 only direction of conversion is flipped bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } public class C1 { } class Test { static T M02<T, U>(int x) where T : U where U : C1, I1<T> { return " + (needCast ? "(T)" : "") + @"x; } static T M03<T, U>(int y) where T : U where U : I1<T> { return " + (needCast ? "(T)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (15,16): error CS0030: Cannot convert type 'int' to 'T' // return (T)x; Diagnostic((op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv), (needCast ? "(T)" : "") + "x").WithArguments("int", "T").WithLocation(15, 16) ); } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_01() { var source1 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } public class Derived : Base<int>, Interface<int, int> { } class YetAnother : Interface<int, int> { public static void Method(int i) { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var b = module.GlobalNamespace.GetTypeMember("Base"); var bI = b.Interfaces().Single(); var biMethods = bI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", biMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", biMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", biMethods[2].OriginalDefinition.ToTestDisplayString()); var bM1 = b.FindImplementationForInterfaceMember(biMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", bM1.ToTestDisplayString()); var bM2 = b.FindImplementationForInterfaceMember(biMethods[1]); Assert.Equal("void Base<T>.Method(T i)", bM2.ToTestDisplayString()); Assert.Same(bM2, b.FindImplementationForInterfaceMember(biMethods[2])); var bM1Impl = ((MethodSymbol)bM1).ExplicitInterfaceImplementations; var bM2Impl = ((MethodSymbol)bM2).ExplicitInterfaceImplementations; if (module is PEModuleSymbol) { Assert.Equal(biMethods[0], bM1Impl.Single()); Assert.Equal(2, bM2Impl.Length); Assert.Equal(biMethods[1], bM2Impl[0]); Assert.Equal(biMethods[2], bM2Impl[1]); } else { Assert.Empty(bM1Impl); Assert.Empty(bM2Impl); } var d = module.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Same(bM1, dM1.OriginalDefinition); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Same(bM2, dM2.OriginalDefinition); Assert.Same(bM2, d.FindImplementationForInterfaceMember(diMethods[2]).OriginalDefinition); } } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_02() { var source0 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var source1 = @" public class Derived : Base<int>, Interface<int, int> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation0.EmitToImageReference() }); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var d = module.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", dM1.OriginalDefinition.ToTestDisplayString()); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Equal("void Base<T>.Method(T i)", dM2.OriginalDefinition.ToTestDisplayString()); Assert.Same(dM2, d.FindImplementationForInterfaceMember(diMethods[2])); var dM1Impl = ((MethodSymbol)dM1).ExplicitInterfaceImplementations; var dM2Impl = ((MethodSymbol)dM2).ExplicitInterfaceImplementations; Assert.Equal(diMethods[0], dM1Impl.Single()); Assert.Equal(2, dM2Impl.Length); Assert.Equal(diMethods[1], dM2Impl[0]); Assert.Equal(diMethods[2], dM2Impl[1]); } } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_03() { var source0 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateEmptyCompilation("").ToMetadataReference() }); compilation0.VerifyDiagnostics(); var source1 = @" public class Derived : Base<int>, Interface<int, int> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation0.ToMetadataReference() }); var d = compilation1.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.IsType<RetargetingNamedTypeSymbol>(dB.OriginalDefinition); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", dM1.OriginalDefinition.ToTestDisplayString()); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Equal("void Base<T>.Method(T i)", dM2.OriginalDefinition.ToTestDisplayString()); Assert.Equal(dM2, d.FindImplementationForInterfaceMember(diMethods[2])); var dM1Impl = ((MethodSymbol)dM1).ExplicitInterfaceImplementations; var dM2Impl = ((MethodSymbol)dM2).ExplicitInterfaceImplementations; Assert.Empty(dM1Impl); Assert.Empty(dM2Impl); } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_04() { var source2 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } class Other : Interface<int, int> { static void Interface<int, int>.Method(int i) { } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (9,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(9, 15), // (9,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(9, 15), // (11,37): warning CS0473: Explicit interface implementation 'Other.Interface<int, int>.Method(int)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // static void Interface<int, int>.Method(int i) { } Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Other.Interface<int, int>.Method(int)").WithLocation(11, 37) ); } [Fact] public void UnmanagedCallersOnly_01() { var source2 = @" using System.Runtime.InteropServices; public interface I1 { [UnmanagedCallersOnly] abstract static void M1(); [UnmanagedCallersOnly] abstract static int operator +(I1 x); [UnmanagedCallersOnly] abstract static int operator +(I1 x, I1 y); } public interface I2<T> where T : I2<T> { [UnmanagedCallersOnly] abstract static implicit operator int(T i); [UnmanagedCallersOnly] abstract static explicit operator T(int i); } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static void M1(); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(6, 6), // (7,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static int operator +(I1 x); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 6), // (8,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static int operator +(I1 x, I1 y); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(8, 6), // (13,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static implicit operator int(T i); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(13, 6), // (14,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static explicit operator T(int i); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(14, 6) ); } [Fact] [WorkItem(54113, "https://github.com/dotnet/roslyn/issues/54113")] public void UnmanagedCallersOnly_02() { var ilSource = @" .class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72 69 74 65 64 00 ) .field public class [mscorlib]System.Type[] CallConvs .field public string EntryPoint .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void M1 () cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static int32 op_UnaryPlus ( class I1 x ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static int32 op_Addition ( class I1 x, class I1 y ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } } .class interface public auto ansi abstract I2`1<(class I2`1<!T>) T> { .method public hidebysig specialname abstract virtual static int32 op_Implicit ( !T i ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static !T op_Explicit ( int32 i ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } } "; var source1 = @" class Test { static void M02<T>(T x, T y) where T : I1 { T.M1(); _ = +x; _ = x + y; } static int M03<T>(T x) where T : I2<T> { _ = (T)x; return x; } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); // Conversions aren't flagged due to https://github.com/dotnet/roslyn/issues/54113. compilation1.VerifyDiagnostics( // (6,11): error CS0570: 'I1.M1()' is not supported by the language // T.M1(); Diagnostic(ErrorCode.ERR_BindToBogus, "M1").WithArguments("I1.M1()").WithLocation(6, 11), // (7,13): error CS0570: 'I1.operator +(I1)' is not supported by the language // _ = +x; Diagnostic(ErrorCode.ERR_BindToBogus, "+x").WithArguments("I1.operator +(I1)").WithLocation(7, 13), // (8,13): error CS0570: 'I1.operator +(I1, I1)' is not supported by the language // _ = x + y; Diagnostic(ErrorCode.ERR_BindToBogus, "x + y").WithArguments("I1.operator +(I1, I1)").WithLocation(8, 13) ); } [Fact] public void UnmanagedCallersOnly_03() { var source2 = @" using System.Runtime.InteropServices; public interface I1<T> where T : I1<T> { abstract static void M1(); abstract static int operator +(T x); abstract static int operator +(T x, T y); abstract static implicit operator int(T i); abstract static explicit operator T(int i); } class C : I1<C> { [UnmanagedCallersOnly] public static void M1() {} [UnmanagedCallersOnly] public static int operator +(C x) => 0; [UnmanagedCallersOnly] public static int operator +(C x, C y) => 0; [UnmanagedCallersOnly] public static implicit operator int(C i) => 0; [UnmanagedCallersOnly] public static explicit operator C(int i) => null; } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (15,47): error CS8932: 'UnmanagedCallersOnly' method 'C.M1()' cannot implement interface member 'I1<C>.M1()' in type 'C' // [UnmanagedCallersOnly] public static void M1() {} Diagnostic(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, "M1").WithArguments("C.M1()", "I1<C>.M1()", "C").WithLocation(15, 47), // (16,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static int operator +(C x) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(16, 6), // (17,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static int operator +(C x, C y) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(17, 6), // (18,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static implicit operator int(C i) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(18, 6), // (19,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static explicit operator C(int i) => null; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(19, 6) ); } [Fact] public void UnmanagedCallersOnly_04() { var source2 = @" using System.Runtime.InteropServices; public interface I1<T> where T : I1<T> { abstract static void M1(); abstract static int operator +(T x); abstract static int operator +(T x, T y); abstract static implicit operator int(T i); abstract static explicit operator T(int i); } class C : I1<C> { [UnmanagedCallersOnly] static void I1<C>.M1() {} [UnmanagedCallersOnly] static int I1<C>.operator +(C x) => 0; [UnmanagedCallersOnly] static int I1<C>.operator +(C x, C y) => 0; [UnmanagedCallersOnly] static implicit I1<C>.operator int(C i) => 0; [UnmanagedCallersOnly] static explicit I1<C>.operator C(int i) => null; } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (15,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static void I1<C>.M1() {} Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(15, 6), // (16,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static int I1<C>.operator +(C x) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(16, 6), // (17,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static int I1<C>.operator +(C x, C y) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(17, 6), // (18,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static implicit I1<C>.operator int(C i) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(18, 6), // (19,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static explicit I1<C>.operator C(int i) => null; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(19, 6) ); } } }
// 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. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class StaticAbstractMembersInInterfacesTests : CSharpTestBase { private const TargetFramework _supportingFramework = TargetFramework.Net60; [Fact] public void MethodModifiers_01() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } private static void ValidateMethodModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<MethodSymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<MethodSymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<MethodSymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<MethodSymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<MethodSymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<MethodSymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<MethodSymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<MethodSymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<MethodSymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } [Fact] public void MethodModifiers_02() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_03() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_04() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_05() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static void M02() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static void M04() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static void M09() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_06() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static void M02() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static void M04() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static void M09() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void SealedStaticConstructor_01() { var source1 = @" interface I1 { sealed static I1() {} } partial interface I2 { partial sealed static I2(); } partial interface I2 { partial static I2() {} } partial interface I3 { partial static I3(); } partial interface I3 { partial sealed static I3() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,19): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I1").WithArguments("sealed").WithLocation(4, 19), // (9,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I2(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(9, 5), // (9,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I2(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(9, 5), // (9,27): error CS0106: The modifier 'sealed' is not valid for this item // partial sealed static I2(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(9, 27), // (14,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I2() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(14, 5), // (14,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I2() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(14, 5), // (14,20): error CS0111: Type 'I2' already defines a member called 'I2' with the same parameter types // partial static I2() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I2").WithArguments("I2", "I2").WithLocation(14, 20), // (19,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I3(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(19, 5), // (19,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I3(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(19, 5), // (24,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(24, 5), // (24,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(24, 5), // (24,27): error CS0106: The modifier 'sealed' is not valid for this item // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(24, 27), // (24,27): error CS0111: Type 'I3' already defines a member called 'I3' with the same parameter types // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I3").WithArguments("I3", "I3").WithLocation(24, 27) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); } [Fact] public void SealedStaticConstructor_02() { var source1 = @" partial interface I2 { sealed static partial I2(); } partial interface I2 { static partial I2() {} } partial interface I3 { static partial I3(); } partial interface I3 { sealed static partial I3() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,19): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // sealed static partial I2(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(4, 19), // (4,27): error CS0501: 'I2.I2()' must declare a body because it is not marked abstract, extern, or partial // sealed static partial I2(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I2").WithArguments("I2.I2()").WithLocation(4, 27), // (4,27): error CS0542: 'I2': member names cannot be the same as their enclosing type // sealed static partial I2(); Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I2").WithArguments("I2").WithLocation(4, 27), // (9,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I2() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(9, 12), // (9,20): error CS0542: 'I2': member names cannot be the same as their enclosing type // static partial I2() {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I2").WithArguments("I2").WithLocation(9, 20), // (9,20): error CS0111: Type 'I2' already defines a member called 'I2' with the same parameter types // static partial I2() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I2").WithArguments("I2", "I2").WithLocation(9, 20), // (9,20): error CS0161: 'I2.I2()': not all code paths return a value // static partial I2() {} Diagnostic(ErrorCode.ERR_ReturnExpected, "I2").WithArguments("I2.I2()").WithLocation(9, 20), // (14,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I3(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(14, 12), // (14,20): error CS0501: 'I3.I3()' must declare a body because it is not marked abstract, extern, or partial // static partial I3(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I3").WithArguments("I3.I3()").WithLocation(14, 20), // (14,20): error CS0542: 'I3': member names cannot be the same as their enclosing type // static partial I3(); Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I3").WithArguments("I3").WithLocation(14, 20), // (19,19): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(19, 19), // (19,27): error CS0542: 'I3': member names cannot be the same as their enclosing type // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I3").WithArguments("I3").WithLocation(19, 27), // (19,27): error CS0111: Type 'I3' already defines a member called 'I3' with the same parameter types // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I3").WithArguments("I3", "I3").WithLocation(19, 27), // (19,27): error CS0161: 'I3.I3()': not all code paths return a value // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_ReturnExpected, "I3").WithArguments("I3.I3()").WithLocation(19, 27) ); } [Fact] public void AbstractStaticConstructor_01() { var source1 = @" interface I1 { abstract static I1(); } interface I2 { abstract static I2() {} } interface I3 { static I3(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I1").WithArguments("abstract").WithLocation(4, 21), // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I2() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("abstract").WithLocation(9, 21), // (14,12): error CS0501: 'I3.I3()' must declare a body because it is not marked abstract, extern, or partial // static I3(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I3").WithArguments("I3.I3()").WithLocation(14, 12) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); } [Fact] public void PartialSealedStatic_01() { var source1 = @" partial interface I1 { sealed static partial void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Null(m01.PartialImplementationPart); } [Fact] public void PartialSealedStatic_02() { var source1 = @" partial interface I1 { sealed static partial void M01(); } partial interface I1 { sealed static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); ValidatePartialSealedStatic_02(compilation1); } private static void ValidatePartialSealedStatic_02(CSharpCompilation compilation1) { compilation1.VerifyDiagnostics(); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialSealedStatic_03() { var source1 = @" partial interface I1 { static partial void M01(); } partial interface I1 { sealed static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); ValidatePartialSealedStatic_02(compilation1); } [Fact] public void PartialSealedStatic_04() { var source1 = @" partial interface I1 { sealed static partial void M01(); } partial interface I1 { static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); ValidatePartialSealedStatic_02(compilation1); } [Fact] public void PartialAbstractStatic_01() { var source1 = @" partial interface I1 { abstract static partial void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Null(m01.PartialImplementationPart); } [Fact] public void PartialAbstractStatic_02() { var source1 = @" partial interface I1 { abstract static partial void M01(); } partial interface I1 { abstract static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34), // (8,34): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(8, 34), // (8,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(8, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialAbstractStatic_03() { var source1 = @" partial interface I1 { abstract static partial void M01(); } partial interface I1 { static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialAbstractStatic_04() { var source1 = @" partial interface I1 { static partial void M01(); } partial interface I1 { abstract static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,34): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(8, 34), // (8,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(8, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PrivateAbstractStatic_01() { var source1 = @" interface I1 { private abstract static void M01(); private abstract static bool P01 { get; } private abstract static event System.Action E01; private abstract static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,34): error CS0621: 'I1.M01()': virtual or abstract members cannot be private // private abstract static void M01(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "M01").WithArguments("I1.M01()").WithLocation(4, 34), // (5,34): error CS0621: 'I1.P01': virtual or abstract members cannot be private // private abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "P01").WithArguments("I1.P01").WithLocation(5, 34), // (6,49): error CS0621: 'I1.E01': virtual or abstract members cannot be private // private abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_VirtualPrivate, "E01").WithArguments("I1.E01").WithLocation(6, 49), // (7,40): error CS0558: User-defined operator 'I1.operator +(I1)' must be declared static and public // private abstract static I1 operator+ (I1 x); Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 40) ); } [Fact] public void PropertyModifiers_01() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } private static void ValidatePropertyModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); { var m01 = i1.GetMember<PropertySymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<PropertySymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<PropertySymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<PropertySymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<PropertySymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<PropertySymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<PropertySymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<PropertySymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<PropertySymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<PropertySymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } { var m01 = i1.GetMember<PropertySymbol>("M01").GetMethod; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<PropertySymbol>("M02").GetMethod; Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<PropertySymbol>("M03").GetMethod; Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<PropertySymbol>("M04").GetMethod; Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<PropertySymbol>("M05").GetMethod; Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<PropertySymbol>("M06").GetMethod; Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<PropertySymbol>("M07").GetMethod; Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<PropertySymbol>("M08").GetMethod; Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<PropertySymbol>("M09").GetMethod; Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<PropertySymbol>("M10").GetMethod; Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } } [Fact] public void PropertyModifiers_02() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_03() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_04() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_05() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static bool M04 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_06() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static bool M04 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void EventModifiers_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event D M01 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 29), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static event D M03 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static event D M07 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static event D M10 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } private static void ValidateEventModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); { var m01 = i1.GetMember<EventSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<EventSymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<EventSymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<EventSymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<EventSymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<EventSymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<EventSymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<EventSymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<EventSymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<EventSymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } foreach (var addAccessor in new[] { true, false }) { var m01 = getAccessor(i1.GetMember<EventSymbol>("M01"), addAccessor); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = getAccessor(i1.GetMember<EventSymbol>("M02"), addAccessor); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = getAccessor(i1.GetMember<EventSymbol>("M03"), addAccessor); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = getAccessor(i1.GetMember<EventSymbol>("M04"), addAccessor); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = getAccessor(i1.GetMember<EventSymbol>("M05"), addAccessor); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = getAccessor(i1.GetMember<EventSymbol>("M06"), addAccessor); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = getAccessor(i1.GetMember<EventSymbol>("M07"), addAccessor); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = getAccessor(i1.GetMember<EventSymbol>("M08"), addAccessor); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = getAccessor(i1.GetMember<EventSymbol>("M09"), addAccessor); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = getAccessor(i1.GetMember<EventSymbol>("M10"), addAccessor); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } static MethodSymbol getAccessor(EventSymbol e, bool addAccessor) { return addAccessor ? e.AddMethod : e.RemoveMethod; } } [Fact] public void EventModifiers_02() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 29), // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static event D M03 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_03() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_04() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_05() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static event D M01 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 29), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (7,28): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static event D M02 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static event D M03 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (13,29): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static event D M04 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static event D M07 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (28,37): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static event D M09 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static event D M10 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_06() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 29), // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (7,28): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static event D M03 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (13,29): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (28,37): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void OperatorModifiers_01() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "9.0", "preview").WithLocation(10, 30), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "9.0", "preview").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "9.0", "preview").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "9.0", "preview").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "9.0", "preview").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } private static void ValidateOperatorModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("op_UnaryPlus"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<MethodSymbol>("op_UnaryNegation"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<MethodSymbol>("op_Increment"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<MethodSymbol>("op_Decrement"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<MethodSymbol>("op_LogicalNot"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<MethodSymbol>("op_OnesComplement"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<MethodSymbol>("op_Addition"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<MethodSymbol>("op_Subtraction"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<MethodSymbol>("op_Multiply"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<MethodSymbol>("op_Division"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } [Fact] public void OperatorModifiers_02() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(4, 32), // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "9.0", "preview").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "9.0", "preview").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "9.0", "preview").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "9.0", "preview").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "9.0", "preview").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_03() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_04() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_05() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "7.3", "preview").WithLocation(10, 30), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "--").WithArguments("default interface implementation", "8.0").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "7.3", "preview").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "7.3", "preview").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "7.3", "preview").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "*").WithArguments("default interface implementation", "8.0").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "7.3", "preview").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_06() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(4, 32), // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "7.3", "preview").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "--").WithArguments("default interface implementation", "8.0").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "7.3", "preview").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "7.3", "preview").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "7.3", "preview").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "*").WithArguments("default interface implementation", "8.0").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "7.3", "preview").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_07() { var source1 = @" public interface I1 { abstract static bool operator== (I1 x, I1 y); abstract static bool operator!= (I1 x, I1 y) {return false;} } public interface I2 { sealed static bool operator== (I2 x, I2 y); sealed static bool operator!= (I2 x, I2 y) {return false;} } public interface I3 { abstract sealed static bool operator== (I3 x, I3 y); abstract sealed static bool operator!= (I3 x, I3 y) {return false;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool operator== (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "7.3", "preview").WithLocation(4, 34), // (6,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "7.3", "preview").WithLocation(6, 34), // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (18,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "7.3", "preview").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "7.3", "preview").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator== (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(4, 34), // (6,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(6, 34), // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (18,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); void validate() { foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I1").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I2").GetMembers()) { Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I3").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } } } [Fact] public void OperatorModifiers_08() { var source1 = @" public interface I1 { abstract static implicit operator int(I1 x); abstract static explicit operator I1(bool x) {return null;} } public interface I2 { sealed static implicit operator int(I2 x); sealed static explicit operator I2(bool x) {return null;} } public interface I3 { abstract sealed static implicit operator int(I3 x); abstract sealed static explicit operator I3(bool x) {return null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "7.3", "preview").WithLocation(4, 39), // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I1").WithArguments("abstract", "7.3", "preview").WithLocation(6, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "7.3", "preview").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I3").WithArguments("abstract", "7.3", "preview").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(4, 39), // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I1").WithArguments("abstract", "9.0", "preview").WithLocation(6, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I3").WithArguments("abstract", "9.0", "preview").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); void validate() { foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I1").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I2").GetMembers()) { Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I3").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } } } [Fact] public void FieldModifiers_01() { var source1 = @" public interface I1 { abstract static int F1; sealed static int F2; abstract int F3; sealed int F4; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,25): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract static int F1; Diagnostic(ErrorCode.ERR_AbstractField, "F1").WithLocation(4, 25), // (5,23): error CS0106: The modifier 'sealed' is not valid for this item // sealed static int F2; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F2").WithArguments("sealed").WithLocation(5, 23), // (6,18): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract int F3; Diagnostic(ErrorCode.ERR_AbstractField, "F3").WithLocation(6, 18), // (6,18): error CS0525: Interfaces cannot contain instance fields // abstract int F3; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F3").WithLocation(6, 18), // (7,16): error CS0106: The modifier 'sealed' is not valid for this item // sealed int F4; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F4").WithArguments("sealed").WithLocation(7, 16), // (7,16): error CS0525: Interfaces cannot contain instance fields // sealed int F4; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F4").WithLocation(7, 16) ); } [Fact] public void ExternAbstractStatic_01() { var source1 = @" interface I1 { extern abstract static void M01(); extern abstract static bool P01 { get; } extern abstract static event System.Action E01; extern abstract static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,33): error CS0180: 'I1.M01()' cannot be both extern and abstract // extern abstract static void M01(); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M01").WithArguments("I1.M01()").WithLocation(4, 33), // (5,33): error CS0180: 'I1.P01' cannot be both extern and abstract // extern abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P01").WithArguments("I1.P01").WithLocation(5, 33), // (6,48): error CS0180: 'I1.E01' cannot be both extern and abstract // extern abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E01").WithArguments("I1.E01").WithLocation(6, 48), // (7,39): error CS0180: 'I1.operator +(I1)' cannot be both extern and abstract // extern abstract static I1 operator+ (I1 x); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 39) ); } [Fact] public void ExternAbstractStatic_02() { var source1 = @" interface I1 { extern abstract static void M01() {} extern abstract static bool P01 { get => false; } extern abstract static event System.Action E01 { add {} remove {} } extern abstract static I1 operator+ (I1 x) => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,33): error CS0180: 'I1.M01()' cannot be both extern and abstract // extern abstract static void M01() {} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M01").WithArguments("I1.M01()").WithLocation(4, 33), // (5,33): error CS0180: 'I1.P01' cannot be both extern and abstract // extern abstract static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P01").WithArguments("I1.P01").WithLocation(5, 33), // (6,48): error CS0180: 'I1.E01' cannot be both extern and abstract // extern abstract static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E01").WithArguments("I1.E01").WithLocation(6, 48), // (6,52): error CS8712: 'I1.E01': abstract event cannot use event accessor syntax // extern abstract static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.E01").WithLocation(6, 52), // (7,39): error CS0180: 'I1.operator +(I1)' cannot be both extern and abstract // extern abstract static I1 operator+ (I1 x) => null; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 39) ); } [Fact] public void ExternSealedStatic_01() { var source1 = @" #pragma warning disable CS0626 // Method, operator, or accessor is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. interface I1 { extern sealed static void M01(); extern sealed static bool P01 { get; } extern sealed static event System.Action E01; extern sealed static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); } [Fact] public void AbstractStaticInClass_01() { var source1 = @" abstract class C1 { public abstract static void M01(); public abstract static bool P01 { get; } public abstract static event System.Action E01; public abstract static C1 operator+ (C1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static void M01(); Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M01").WithArguments("abstract").WithLocation(4, 33), // (5,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P01").WithArguments("abstract").WithLocation(5, 33), // (6,48): error CS0112: A static member cannot be marked as 'abstract' // public abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "E01").WithArguments("abstract").WithLocation(6, 48), // (7,39): error CS0106: The modifier 'abstract' is not valid for this item // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("abstract").WithLocation(7, 39), // (7,39): error CS0501: 'C1.operator +(C1)' must declare a body because it is not marked abstract, extern, or partial // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("C1.operator +(C1)").WithLocation(7, 39) ); } [Fact] public void SealedStaticInClass_01() { var source1 = @" class C1 { sealed static void M01() {} sealed static bool P01 { get => false; } sealed static event System.Action E01 { add {} remove {} } public sealed static C1 operator+ (C1 x) => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,24): error CS0238: 'C1.M01()' cannot be sealed because it is not an override // sealed static void M01() {} Diagnostic(ErrorCode.ERR_SealedNonOverride, "M01").WithArguments("C1.M01()").WithLocation(4, 24), // (5,24): error CS0238: 'C1.P01' cannot be sealed because it is not an override // sealed static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_SealedNonOverride, "P01").WithArguments("C1.P01").WithLocation(5, 24), // (6,39): error CS0238: 'C1.E01' cannot be sealed because it is not an override // sealed static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_SealedNonOverride, "E01").WithArguments("C1.E01").WithLocation(6, 39), // (7,37): error CS0106: The modifier 'sealed' is not valid for this item // public sealed static C1 operator+ (C1 x) => null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("sealed").WithLocation(7, 37) ); } [Fact] public void AbstractStaticInStruct_01() { var source1 = @" struct C1 { public abstract static void M01(); public abstract static bool P01 { get; } public abstract static event System.Action E01; public abstract static C1 operator+ (C1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static void M01(); Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M01").WithArguments("abstract").WithLocation(4, 33), // (5,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P01").WithArguments("abstract").WithLocation(5, 33), // (6,48): error CS0112: A static member cannot be marked as 'abstract' // public abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "E01").WithArguments("abstract").WithLocation(6, 48), // (7,39): error CS0106: The modifier 'abstract' is not valid for this item // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("abstract").WithLocation(7, 39), // (7,39): error CS0501: 'C1.operator +(C1)' must declare a body because it is not marked abstract, extern, or partial // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("C1.operator +(C1)").WithLocation(7, 39) ); } [Fact] public void SealedStaticInStruct_01() { var source1 = @" struct C1 { sealed static void M01() {} sealed static bool P01 { get => false; } sealed static event System.Action E01 { add {} remove {} } public sealed static C1 operator+ (C1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,24): error CS0238: 'C1.M01()' cannot be sealed because it is not an override // sealed static void M01() {} Diagnostic(ErrorCode.ERR_SealedNonOverride, "M01").WithArguments("C1.M01()").WithLocation(4, 24), // (5,24): error CS0238: 'C1.P01' cannot be sealed because it is not an override // sealed static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_SealedNonOverride, "P01").WithArguments("C1.P01").WithLocation(5, 24), // (6,39): error CS0238: 'C1.E01' cannot be sealed because it is not an override // sealed static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_SealedNonOverride, "E01").WithArguments("C1.E01").WithLocation(6, 39), // (7,37): error CS0106: The modifier 'sealed' is not valid for this item // public sealed static C1 operator+ (C1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("sealed").WithLocation(7, 37) ); } [Fact] public void DefineAbstractStaticMethod_01() { var source1 = @" interface I1 { abstract static void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); Assert.True(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.True(compilation1.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); } } [Fact] public void DefineAbstractStaticMethod_02() { var source1 = @" interface I1 { abstract static void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 26) ); Assert.False(compilation1.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.False(compilation1.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.Net50); compilation2.VerifyDiagnostics( // (4,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 26) ); Assert.True(compilation2.Assembly.RuntimeSupportsDefaultInterfaceImplementation); Assert.False(compilation2.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces); } [Theory] [InlineData("I1", "+", "(I1 x)")] [InlineData("I1", "-", "(I1 x)")] [InlineData("I1", "!", "(I1 x)")] [InlineData("I1", "~", "(I1 x)")] [InlineData("I1", "++", "(I1 x)")] [InlineData("I1", "--", "(I1 x)")] [InlineData("I1", "+", "(I1 x, I1 y)")] [InlineData("I1", "-", "(I1 x, I1 y)")] [InlineData("I1", "*", "(I1 x, I1 y)")] [InlineData("I1", "/", "(I1 x, I1 y)")] [InlineData("I1", "%", "(I1 x, I1 y)")] [InlineData("I1", "&", "(I1 x, I1 y)")] [InlineData("I1", "|", "(I1 x, I1 y)")] [InlineData("I1", "^", "(I1 x, I1 y)")] [InlineData("I1", "<<", "(I1 x, int y)")] [InlineData("I1", ">>", "(I1 x, int y)")] public void DefineAbstractStaticOperator_01(string type, string op, string paramList) { var source1 = @" interface I1 { abstract static " + type + " operator " + op + " " + paramList + @"; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); } } [Fact] public void DefineAbstractStaticOperator_02() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); abstract static I1 operator > (I1 x, I1 y); abstract static I1 operator < (I1 x, I1 y); abstract static I1 operator >= (I1 x, I1 y); abstract static I1 operator <= (I1 x, I1 y); abstract static I1 operator == (I1 x, I1 y); abstract static I1 operator != (I1 x, I1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(8, count); } } [Theory] [InlineData("I1", "+", "(I1 x)")] [InlineData("I1", "-", "(I1 x)")] [InlineData("I1", "!", "(I1 x)")] [InlineData("I1", "~", "(I1 x)")] [InlineData("I1", "++", "(I1 x)")] [InlineData("I1", "--", "(I1 x)")] [InlineData("I1", "+", "(I1 x, I1 y)")] [InlineData("I1", "-", "(I1 x, I1 y)")] [InlineData("I1", "*", "(I1 x, I1 y)")] [InlineData("I1", "/", "(I1 x, I1 y)")] [InlineData("I1", "%", "(I1 x, I1 y)")] [InlineData("I1", "&", "(I1 x, I1 y)")] [InlineData("I1", "|", "(I1 x, I1 y)")] [InlineData("I1", "^", "(I1 x, I1 y)")] [InlineData("I1", "<<", "(I1 x, int y)")] [InlineData("I1", ">>", "(I1 x, int y)")] public void DefineAbstractStaticOperator_03(string type, string op, string paramList) { var source1 = @" interface I1 { abstract static " + type + " operator " + op + " " + paramList + @"; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator + (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 31 + type.Length) ); } [Fact] public void DefineAbstractStaticOperator_04() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); abstract static I1 operator > (I1 x, I1 y); abstract static I1 operator < (I1 x, I1 y); abstract static I1 operator >= (I1 x, I1 y); abstract static I1 operator <= (I1 x, I1 y); abstract static I1 operator == (I1 x, I1 y); abstract static I1 operator != (I1 x, I1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(4, 35), // (5,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(5, 35), // (6,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator > (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, ">").WithLocation(6, 33), // (7,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator < (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "<").WithLocation(7, 33), // (8,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator >= (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, ">=").WithLocation(8, 33), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator <= (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "<=").WithLocation(9, 33), // (10,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator == (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "==").WithLocation(10, 33), // (11,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator != (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "!=").WithLocation(11, 33) ); } [Fact] public void DefineAbstractStaticConversion_01() { var source1 = @" interface I1<T> where T : I1<T> { abstract static implicit operator int(T x); abstract static explicit operator T(int x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticConversion_03() { var source1 = @" interface I1<T> where T : I1<T> { abstract static implicit operator int(T x); abstract static explicit operator T(int x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 39), // (5,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator T(int x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T").WithLocation(5, 39) ); } [Fact] public void DefineAbstractStaticProperty_01() { var source1 = @" interface I1 { abstract static int P01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var p01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.True(p01.IsAbstract); Assert.False(p01.IsVirtual); Assert.False(p01.IsSealed); Assert.True(p01.IsStatic); Assert.False(p01.IsOverride); int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticProperty_02() { var source1 = @" interface I1 { abstract static int P01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(4, 31), // (4,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(4, 36) ); } [Fact] public void DefineAbstractStaticEvent_01() { var source1 = @" interface I1 { abstract static event System.Action E01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var e01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.True(e01.IsAbstract); Assert.False(e01.IsVirtual); Assert.False(e01.IsSealed); Assert.True(e01.IsStatic); Assert.False(e01.IsOverride); int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticEvent_02() { var source1 = @" interface I1 { abstract static event System.Action E01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "E01").WithLocation(4, 41) ); } [Fact] public void ConstraintChecks_01() { var source1 = @" public interface I1 { abstract static void M01(); } public interface I2 : I1 { } public interface I3 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var source2 = @" class C1<T1> where T1 : I1 { void Test(C1<I2> x) { } } class C2 { void M<T2>() where T2 : I1 {} void Test(C2 x) { x.M<I2>(); } } class C3<T3> where T3 : I2 { void Test(C3<I2> x, C3<I3> y) { } } class C4 { void M<T4>() where T4 : I2 {} void Test(C4 x) { x.M<I2>(); x.M<I3>(); } } class C5<T5> where T5 : I3 { void Test(C5<I3> y) { } } class C6 { void M<T6>() where T6 : I3 {} void Test(C6 x) { x.M<I3>(); } } class C7<T7> where T7 : I1 { void Test(C7<I1> y) { } } class C8 { void M<T8>() where T8 : I1 {} void Test(C8 x) { x.M<I1>(); } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); var expected = new[] { // (4,22): error CS8920: The interface 'I2' cannot be used as type parameter 'T1' in the generic type or method 'C1<T1>'. The constraint interface 'I1' or its base interface has static abstract members. // void Test(C1<I2> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "x").WithArguments("C1<T1>", "I1", "T1", "I2").WithLocation(4, 22), // (15,11): error CS8920: The interface 'I2' cannot be used as type parameter 'T2' in the generic type or method 'C2.M<T2>()'. The constraint interface 'I1' or its base interface has static abstract members. // x.M<I2>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I2>").WithArguments("C2.M<T2>()", "I1", "T2", "I2").WithLocation(15, 11), // (21,22): error CS8920: The interface 'I2' cannot be used as type parameter 'T3' in the generic type or method 'C3<T3>'. The constraint interface 'I2' or its base interface has static abstract members. // void Test(C3<I2> x, C3<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "x").WithArguments("C3<T3>", "I2", "T3", "I2").WithLocation(21, 22), // (21,32): error CS8920: The interface 'I3' cannot be used as type parameter 'T3' in the generic type or method 'C3<T3>'. The constraint interface 'I2' or its base interface has static abstract members. // void Test(C3<I2> x, C3<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C3<T3>", "I2", "T3", "I3").WithLocation(21, 32), // (32,11): error CS8920: The interface 'I2' cannot be used as type parameter 'T4' in the generic type or method 'C4.M<T4>()'. The constraint interface 'I2' or its base interface has static abstract members. // x.M<I2>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I2>").WithArguments("C4.M<T4>()", "I2", "T4", "I2").WithLocation(32, 11), // (33,11): error CS8920: The interface 'I3' cannot be used as type parameter 'T4' in the generic type or method 'C4.M<T4>()'. The constraint interface 'I2' or its base interface has static abstract members. // x.M<I3>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I3>").WithArguments("C4.M<T4>()", "I2", "T4", "I3").WithLocation(33, 11), // (39,22): error CS8920: The interface 'I3' cannot be used as type parameter 'T5' in the generic type or method 'C5<T5>'. The constraint interface 'I3' or its base interface has static abstract members. // void Test(C5<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C5<T5>", "I3", "T5", "I3").WithLocation(39, 22), // (50,11): error CS8920: The interface 'I3' cannot be used as type parameter 'T6' in the generic type or method 'C6.M<T6>()'. The constraint interface 'I3' or its base interface has static abstract members. // x.M<I3>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I3>").WithArguments("C6.M<T6>()", "I3", "T6", "I3").WithLocation(50, 11), // (56,22): error CS8920: The interface 'I1' cannot be used as type parameter 'T7' in the generic type or method 'C7<T7>'. The constraint interface 'I1' or its base interface has static abstract members. // void Test(C7<I1> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C7<T7>", "I1", "T7", "I1").WithLocation(56, 22), // (67,11): error CS8920: The interface 'I1' cannot be used as type parameter 'T8' in the generic type or method 'C8.M<T8>()'. The constraint interface 'I1' or its base interface has static abstract members. // x.M<I1>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I1>").WithArguments("C8.M<T8>()", "I1", "T8", "I1").WithLocation(67, 11) }; compilation2.VerifyDiagnostics(expected); compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { compilation1.EmitToImageReference() }); compilation2.VerifyDiagnostics(expected); } [Fact] public void ConstraintChecks_02() { var source1 = @" public interface I1 { abstract static void M01(); } public class C : I1 { public static void M01() {} } public struct S : I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var source2 = @" class C1<T1> where T1 : I1 { void Test(C1<C> x, C1<S> y, C1<T1> z) { } } class C2 { public void M<T2>(C2 x) where T2 : I1 { x.M<T2>(x); } void Test(C2 x) { x.M<C>(x); x.M<S>(x); } } class C3<T3> where T3 : I1 { void Test(C1<T3> z) { } } class C4 { void M<T4>(C2 x) where T4 : I1 { x.M<T4>(x); } } class C5<T5> { internal virtual void M<U5>() where U5 : T5 { } } class C6 : C5<I1> { internal override void M<U6>() { base.M<U6>(); } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyEmitDiagnostics(); compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { compilation1.EmitToImageReference() }); compilation2.VerifyEmitDiagnostics(); } [Fact] public void VarianceSafety_01() { var source1 = @" interface I2<out T1, in T2> { abstract static T1 P1 { get; } abstract static T2 P2 { get; } abstract static T1 P3 { set; } abstract static T2 P4 { set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (5,21): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.P2'. 'T2' is contravariant. // abstract static T2 P2 { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I2<T1, T2>.P2", "T2", "contravariant", "covariantly").WithLocation(5, 21), // (6,21): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.P3'. 'T1' is covariant. // abstract static T1 P3 { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I2<T1, T2>.P3", "T1", "covariant", "contravariantly").WithLocation(6, 21) ); } [Fact] public void VarianceSafety_02() { var source1 = @" interface I2<out T1, in T2> { abstract static T1 M1(); abstract static T2 M2(); abstract static void M3(T1 x); abstract static void M4(T2 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (5,21): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.M2()'. 'T2' is contravariant. // abstract static T2 M2(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I2<T1, T2>.M2()", "T2", "contravariant", "covariantly").WithLocation(5, 21), // (6,29): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.M3(T1)'. 'T1' is covariant. // abstract static void M3(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I2<T1, T2>.M3(T1)", "T1", "covariant", "contravariantly").WithLocation(6, 29) ); } [Fact] public void VarianceSafety_03() { var source1 = @" interface I2<out T1, in T2> { abstract static event System.Action<System.Func<T1>> E1; abstract static event System.Action<System.Func<T2>> E2; abstract static event System.Action<System.Action<T1>> E3; abstract static event System.Action<System.Action<T2>> E4; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (5,58): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.E2'. 'T2' is contravariant. // abstract static event System.Action<System.Func<T2>> E2; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E2").WithArguments("I2<T1, T2>.E2", "T2", "contravariant", "covariantly").WithLocation(5, 58), // (6,60): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.E3'. 'T1' is covariant. // abstract static event System.Action<System.Action<T1>> E3; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E3").WithArguments("I2<T1, T2>.E3", "T1", "covariant", "contravariantly").WithLocation(6, 60) ); } [Fact] public void VarianceSafety_04() { var source1 = @" interface I2<out T2> { abstract static int operator +(I2<T2> x); } interface I3<out T3> { abstract static int operator +(I3<T3> x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,36): error CS1961: Invalid variance: The type parameter 'T2' must be contravariantly valid on 'I2<T2>.operator +(I2<T2>)'. 'T2' is covariant. // abstract static int operator +(I2<T2> x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "I2<T2>").WithArguments("I2<T2>.operator +(I2<T2>)", "T2", "covariant", "contravariantly").WithLocation(4, 36), // (9,36): error CS1961: Invalid variance: The type parameter 'T3' must be contravariantly valid on 'I3<T3>.operator +(I3<T3>)'. 'T3' is covariant. // abstract static int operator +(I3<T3> x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "I3<T3>").WithArguments("I3<T3>.operator +(I3<T3>)", "T3", "covariant", "contravariantly").WithLocation(9, 36) ); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("!")] [InlineData("~")] [InlineData("true")] [InlineData("false")] public void OperatorSignature_01(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x); } interface I13 { static abstract bool operator " + op + @"(I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,26): error CS0562: The parameter of a unary operator must be the containing type // static bool operator +(T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0562: The parameter of a unary operator must be the containing type // static bool operator +(T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T5 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T71 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T8 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T10 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator false(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11)").WithLocation(47, 18), // (51,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator false(int x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [InlineData("++")] [InlineData("--")] public void OperatorSignature_02(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static T1 operator " + op + @"(T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static T2? operator " + op + @"(T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract T3 operator " + op + @"(T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract T4? operator " + op + @"(T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract T5 operator " + op + @"(T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract T71 operator " + op + @"(T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract T8 operator " + op + @"(T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract T10 operator " + op + @"(T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract int operator " + op + @"(int x); } interface I13 { static abstract I13 operator " + op + @"(I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,24): error CS0559: The parameter type for ++ or -- operator must be the containing type // static T1 operator ++(T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, op).WithLocation(4, 24), // (9,25): error CS0559: The parameter type for ++ or -- operator must be the containing type // static T2? operator ++(T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, op).WithLocation(9, 25), // (26,37): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T5 operator ++(T5 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(26, 37), // (32,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T71 operator ++(T71 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(32, 34), // (37,33): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T8 operator ++(T8 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(37, 33), // (44,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T10 operator ++(T10 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(44, 34), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator --(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11)").WithLocation(47, 18), // (51,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract int operator ++(int x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(51, 34) ); } [Theory] [InlineData("++")] [InlineData("--")] public void OperatorSignature_03(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static T1 operator " + op + @"(I1<T1> x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static T2? operator " + op + @"(I2<T2> x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract T3 operator " + op + @"(I3<T3> x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract T4? operator " + op + @"(I4<T4> x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract T5 operator " + op + @"(I6 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract T71 operator " + op + @"(I7<T71, T72> x); } interface I8<T8> where T8 : I9<T8> { static abstract T8 operator " + op + @"(I8<T8> x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract T10 operator " + op + @"(I10<T10> x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract int operator " + op + @"(I12 x); } interface I13<T13> where T13 : struct, I13<T13> { static abstract T13? operator " + op + @"(T13 x); } interface I14<T14> where T14 : struct, I14<T14> { static abstract T14 operator " + op + @"(T14? x); } interface I15<T151, T152> where T151 : I15<T151, T152> where T152 : I15<T151, T152> { static abstract T151 operator " + op + @"(T152 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,24): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // static T1 operator ++(I1<T1> x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecRetType, op).WithLocation(4, 24), // (9,25): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // static T2? operator ++(I2<T2> x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecRetType, op).WithLocation(9, 25), // (19,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T4? operator ++(I4<T4> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(19, 34), // (26,37): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T5 operator ++(I6 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(26, 37), // (32,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T71 operator ++(I7<T71, T72> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(32, 34), // (37,33): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T8 operator ++(I8<T8> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(37, 33), // (44,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T10 operator ++(I10<T10> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(44, 34), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator ++(I10<T11>)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(I10<T11>)").WithLocation(47, 18), // (51,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract int operator ++(I12 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(51, 34), // (56,35): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T13? operator ++(T13 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(56, 35), // (61,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T14 operator ++(T14? x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(61, 34), // (66,35): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T151 operator ++(T152 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(66, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x, bool y) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x, bool y) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x, bool y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x, bool y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x, bool y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x, bool y); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x, bool y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x, bool y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x, bool y); } interface I13 { static abstract bool operator " + op + @"(I13 x, bool y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators)).Verify( // (4,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(T1 x, bool y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(T2? x, bool y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T5 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T71 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T8 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T10 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator /(T11, bool)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11, bool)").WithLocation(47, 18), // (51,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(int x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_05([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(bool y, T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(bool y, T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(bool y, T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(bool y, T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(bool y, T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(bool y, T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(bool y, T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(bool y, T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(bool y, int x); } interface I13 { static abstract bool operator " + op + @"(bool y, I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators)).Verify( // (4,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(bool y, T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(bool y, T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T5 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T71 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T8 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T10 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator <=(bool, T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(bool, T11)").WithLocation(47, 18), // (51,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, int x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [InlineData("<<")] [InlineData(">>")] public void OperatorSignature_06(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x, int y) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x, int y) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x, int y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x, int y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x, int y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x, int y); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x, int y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x, int y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x, int y); } interface I13 { static abstract bool operator " + op + @"(I13 x, int y); } interface I14 { static abstract bool operator " + op + @"(I14 x, bool y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,26): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // static bool operator <<(T1 x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // static bool operator <<(T2? x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T5 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T71 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T8 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T10 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator >>(T11, int)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11, int)").WithLocation(47, 18), // (51,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(int x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(51, 35), // (61,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(I14 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(61, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_07([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { abstract static " + op + @" operator T1(T1 y); } interface I2<T2> where T2 : I2<T2> { abstract static " + op + @" operator dynamic(T2 y); } interface I3<T3> where T3 : I3<T3> { static abstract " + op + @" operator T3(bool y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract " + op + @" operator T4?(bool y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract " + op + @" operator T5 (bool y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract " + op + @" operator T71 (bool y); } interface I8<T8> where T8 : I9<T8> { static abstract " + op + @" operator T8(bool y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract " + op + @" operator T10(bool y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract " + op + @" operator int(bool y); } interface I13 { static abstract " + op + @" operator I13(bool y); } interface I14<T14> where T14 : I14<T14> { abstract static " + op + @" operator object(T14 y); } class C15 {} class C16 : C15 {} interface I17<T17> where T17 : C15, I17<T17> { abstract static " + op + @" operator C16(T17 y); } interface I18<T18> where T18 : C16, I18<T18> { abstract static " + op + @" operator C15(T18 y); } interface I19<T19_1, T19_2> where T19_1 : I19<T19_1, T19_2>, T19_2 { abstract static " + op + @" operator T19_1(T19_2 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,39): error CS0555: User-defined operator cannot convert a type to itself // abstract static explicit operator T1(T1 y); Diagnostic(ErrorCode.ERR_IdentityConversion, "T1").WithLocation(4, 39), // (9,39): error CS1964: 'I2<T2>.explicit operator dynamic(T2)': user-defined conversions to or from the dynamic type are not allowed // abstract static explicit operator dynamic(T2 y); Diagnostic(ErrorCode.ERR_BadDynamicConversion, "dynamic").WithArguments("I2<T2>." + op + " operator dynamic(T2)").WithLocation(9, 39), // (26,43): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T5 (bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T5").WithLocation(26, 43), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T71 (bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T71").WithLocation(32, 39), // (37,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T8(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T8").WithLocation(37, 39), // (44,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T10(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T10").WithLocation(44, 39), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.explicit operator T11(bool)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>." + op + " operator T11(bool)").WithLocation(47, 18), // (51,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator int(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "int").WithLocation(51, 39), // (56,39): error CS0552: 'I13.explicit operator I13(bool)': user-defined conversions to or from an interface are not allowed // static abstract explicit operator I13(bool y); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I13").WithArguments("I13." + op + " operator I13(bool)").WithLocation(56, 39) ); } [Theory] [CombinatorialData] public void OperatorSignature_08([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { abstract static " + op + @" operator T1(T1 y); } interface I2<T2> where T2 : I2<T2> { abstract static " + op + @" operator T2(dynamic y); } interface I3<T3> where T3 : I3<T3> { static abstract " + op + @" operator bool(T3 y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract " + op + @" operator bool(T4? y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract " + op + @" operator bool(T5 y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract " + op + @" operator bool(T71 y); } interface I8<T8> where T8 : I9<T8> { static abstract " + op + @" operator bool(T8 y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract " + op + @" operator bool(T10 y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract " + op + @" operator bool(int y); } interface I13 { static abstract " + op + @" operator bool(I13 y); } interface I14<T14> where T14 : I14<T14> { abstract static " + op + @" operator T14(object y); } class C15 {} class C16 : C15 {} interface I17<T17> where T17 : C15, I17<T17> { abstract static " + op + @" operator T17(C16 y); } interface I18<T18> where T18 : C16, I18<T18> { abstract static " + op + @" operator T18(C15 y); } interface I19<T19_1, T19_2> where T19_1 : I19<T19_1, T19_2>, T19_2 { abstract static " + op + @" operator T19_2(T19_1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,39): error CS0555: User-defined operator cannot convert a type to itself // abstract static explicit operator T1(T1 y); Diagnostic(ErrorCode.ERR_IdentityConversion, "T1").WithLocation(4, 39), // (9,39): error CS1964: 'I2<T2>.explicit operator T2(dynamic)': user-defined conversions to or from the dynamic type are not allowed // abstract static explicit operator T2(dynamic y); Diagnostic(ErrorCode.ERR_BadDynamicConversion, "T2").WithArguments("I2<T2>." + op + " operator T2(dynamic)").WithLocation(9, 39), // (26,43): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T5 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(26, 43), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T71 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(32, 39), // (37,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T8 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(37, 39), // (44,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T10 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(44, 39), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.explicit operator bool(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>." + op + " operator bool(T11)").WithLocation(47, 18), // (51,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(int y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(51, 39), // (56,39): error CS0552: 'I13.explicit operator bool(I13)': user-defined conversions to or from an interface are not allowed // static abstract explicit operator bool(I13 y); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "bool").WithArguments("I13." + op + " operator bool(I13)").WithLocation(56, 39) ); } [Fact] public void ConsumeAbstractStaticMethod_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { M01(); M04(); } void M03() { this.M01(); this.M04(); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { I1.M01(); x.M01(); I1.M04(); x.M04(); } static void MT2<T>() where T : I1 { T.M03(); T.M04(); T.M00(); T.M05(); _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.M01()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // M01(); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "M01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // this.M01(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // this.M04(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.M01(); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.M01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // x.M01(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // x.M04(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M03(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M04(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M00(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.M05()' is inaccessible due to its protection level // T.M05(); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 11), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.M01()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01()").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticMethod_02() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = nameof(M01); _ = nameof(M04); } void M03() { _ = nameof(this.M01); _ = nameof(this.M04); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = nameof(I1.M01); _ = nameof(x.M01); _ = nameof(I1.M04); _ = nameof(x.M04); } static void MT2<T>() where T : I1 { _ = nameof(T.M03); _ = nameof(T.M04); _ = nameof(T.M00); _ = nameof(T.M05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = nameof(T.M05); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticMethod_03() { var source1 = @" public interface I1 { abstract static void M01(); abstract static void M04(int x); } class Test { static void M02<T, U>() where T : U where U : I1 { T.M01(); } static string M03<T, U>() where T : U where U : I1 { return nameof(T.M01); } static async void M05<T, U>() where T : U where U : I1 { T.M04(await System.Threading.Tasks.Task.FromResult(1)); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 14 (0xe) .maxstack 0 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""void I1.M01()"" IL_000c: nop IL_000d: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""M01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 12 (0xc) .maxstack 0 IL_0000: constrained. ""T"" IL_0006: call ""void I1.M01()"" IL_000b: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""M01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("T.M01()", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IInvocationOperation (virtual void I1.M01()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'T.M01()') Instance Receiver: null Arguments(0) "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("void I1.M01()", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("M01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticMethod_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.M01(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.M01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_05() { var source1 = @" public interface I1 { abstract static I1 Select(System.Func<int, int> p); } class Test { static void M02<T>() where T : I1 { _ = from t in T select t + 1; _ = from t in I1 select t + 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); // https://github.com/dotnet/roslyn/issues/53796: Confirm whether we want to enable the 'from t in T' scenario. compilation1.VerifyDiagnostics( // (11,23): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = from t in T select t + 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(11, 23), // (12,26): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = from t in I1 select t + 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "select t + 1").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.M01(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.M01(); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.M01(); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_01(string prefixOp, string postfixOp) { var source1 = @" interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); abstract static I1<T> operator" + prefixOp + postfixOp + @" (I1<T> x); static void M02(I1<T> x) { _ = " + prefixOp + "x" + postfixOp + @"; } void M03(I1<T> y) { _ = " + prefixOp + "y" + postfixOp + @"; } } class Test<T> where T : I1<T> { static void MT1(I1<T> a) { _ = " + prefixOp + "a" + postfixOp + @"; } static void MT2() { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (" + prefixOp + "b" + postfixOp + @").ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "x" + postfixOp).WithLocation(8, 13), // (13,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "y" + postfixOp).WithLocation(13, 13), // (21,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "a" + postfixOp).WithLocation(21, 13), (prefixOp + postfixOp).Length == 1 ? // (26,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (-b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, prefixOp + "b" + postfixOp).WithLocation(26, 78) : // (26,78): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b--).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, prefixOp + "b" + postfixOp).WithLocation(26, 78) ); } [Theory] [InlineData("+", "", "op_UnaryPlus", "Plus")] [InlineData("-", "", "op_UnaryNegation", "Minus")] [InlineData("!", "", "op_LogicalNot", "Not")] [InlineData("~", "", "op_OnesComplement", "BitwiseNegation")] [InlineData("++", "", "op_Increment", "Increment")] [InlineData("--", "", "op_Decrement", "Decrement")] [InlineData("", "++", "op_Increment", "Increment")] [InlineData("", "--", "op_Decrement", "Decrement")] public void ConsumeAbstractUnaryOperator_03(string prefixOp, string postfixOp, string metadataName, string opKind) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } class Test { static T M02<T, U>(T x) where T : U where U : I1<T> { return " + prefixOp + "x" + postfixOp + @"; } static T? M03<T, U>(T? y) where T : struct, U where U : I1<T> { return " + prefixOp + "y" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 21 (0x15) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: dup IL_000e: starg.s V_0 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: dup IL_002f: starg.s V_0 IL_0031: stloc.2 IL_0032: br.s IL_0034 IL_0034: ldloc.2 IL_0035: ret } "); break; case ("", "++"): case ("", "--"): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 21 (0x15) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: dup IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T)"" IL_000e: starg.s V_0 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: dup IL_0003: stloc.0 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: brtrue.s IL_0018 IL_000d: ldloca.s V_1 IL_000f: initobj ""T?"" IL_0015: ldloc.1 IL_0016: br.s IL_002f IL_0018: ldloca.s V_0 IL_001a: call ""readonly T T?.GetValueOrDefault()"" IL_001f: constrained. ""T"" IL_0025: call ""T I1<T>." + metadataName + @"(T)"" IL_002a: newobj ""T?..ctor(T)"" IL_002f: starg.s V_0 IL_0031: stloc.2 IL_0032: br.s IL_0034 IL_0034: ldloc.2 IL_0035: ret } "); break; default: verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); break; } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(T)"" IL_000c: dup IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0016 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: br.s IL_002d IL_0016: ldloca.s V_0 IL_0018: call ""readonly T T?.GetValueOrDefault()"" IL_001d: constrained. ""T"" IL_0023: call ""T I1<T>." + metadataName + @"(T)"" IL_0028: newobj ""T?..ctor(T)"" IL_002d: dup IL_002e: starg.s V_0 IL_0030: ret } "); break; case ("", "++"): case ("", "--"): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: dup IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: starg.s V_0 IL_0030: ret } "); break; default: verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(T)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""T I1<T>." + metadataName + @"(T)"" IL_0027: newobj ""T?..ctor(T)"" IL_002c: ret } "); break; } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = postfixOp != "" ? (ExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().First() : tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().First(); Assert.Equal(prefixOp + "x" + postfixOp, node.ToString()); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): case ("", "++"): case ("", "--"): VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IIncrementOrDecrementOperation (" + (prefixOp != "" ? "Prefix" : "Postfix") + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x)) (OperationKind." + opKind + @", Type: T) (Syntax: '" + prefixOp + "x" + postfixOp + @"') Target: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); break; default: VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IUnaryOperation (UnaryOperatorKind." + opKind + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x)) (OperationKind.Unary, Type: T) (Syntax: '" + prefixOp + "x" + postfixOp + @"') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); break; } } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_04(string prefixOp, string postfixOp) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1<T> { _ = " + prefixOp + "x" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = -x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, prefixOp + "x" + postfixOp).WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator- (T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, prefixOp + postfixOp).WithLocation(12, 31) ); } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_06(string prefixOp, string postfixOp) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1<T> { _ = " + prefixOp + "x" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = -x; Diagnostic(ErrorCode.ERR_FeatureInPreview, prefixOp + "x" + postfixOp).WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (12,31): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator- (T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, prefixOp + postfixOp).WithArguments("abstract", "9.0", "preview").WithLocation(12, 31) ); } [Fact] public void ConsumeAbstractTrueOperator_01() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); static void M02(I1 x) { _ = x ? true : false; } void M03(I1 y) { _ = y ? true : false; } } class Test { static void MT1(I1 a) { _ = a ? true : false; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b ? true : false).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (9,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x").WithLocation(9, 13), // (14,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y").WithLocation(14, 13), // (22,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a").WithLocation(22, 13), // (27,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b ? true : false).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b").WithLocation(27, 78) ); } [Fact] public void ConsumeAbstractTrueOperator_03() { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator true (T x); abstract static bool operator false (T x); } class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>.op_True(T)"" IL_000d: brtrue.s IL_0011 IL_000f: br.s IL_0011 IL_0011: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""bool I1<T>.op_True(T)"" IL_000c: pop IL_000d: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalExpressionSyntax>().First(); Assert.Equal("x ? true : false", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IConditionalOperation (OperationKind.Conditional, Type: System.Boolean) (Syntax: 'x ? true : false') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean I1<T>.op_True(T x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') WhenTrue: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') WhenFalse: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') "); } [Fact] public void ConsumeAbstractTrueOperator_04() { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1 { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(12, 35), // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(13, 35) ); } [Fact] public void ConsumeAbstractTrueOperator_06() { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1 { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (12,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(12, 35), // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); static void M02((int, C<I1>) x) { _ = x " + op + @" x; } void M03((int, C<I1>) y) { _ = y " + op + @" y; } } class Test { static void MT1((int, C<I1>) a) { _ = a " + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b " + op + @" b).ToString()); } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (9,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x == x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " x").WithLocation(9, 13), // (14,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y == y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " y").WithLocation(14, 13), // (22,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a == a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " a").WithLocation(22, 13), // (27,98): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(27, 98) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator true (T x); abstract static bool operator false (T x); } class Test { static void M02<T, U>((int, C<T>) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 55 (0x37) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0034 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_False(T)"" IL_002f: ldc.i4.0 IL_0030: ceq IL_0032: br.s IL_0035 IL_0034: ldc.i4.0 IL_0035: pop IL_0036: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_True(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.1 IL_0032: pop IL_0033: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0033 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_False(T)"" IL_002e: ldc.i4.0 IL_002f: ceq IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: pop IL_0035: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_True(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.1 IL_0031: pop IL_0032: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1 { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (21,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(21, 35), // (22,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(22, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1 { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (21,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(21, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" partial interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); static void M02(I1 x) { _ = x " + op + @" 1; } void M03(I1 y) { _ = y " + op + @" 2; } } class Test { static void MT1(I1 a) { _ = a " + op + @" 3; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + @" 4).ToString()); } } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator" + matchingOp + @" (I1 x, int y); } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x - 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " 1").WithLocation(8, 13), // (13,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y - 2; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " 2").WithLocation(13, 13), // (21,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a - 3; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " 3").WithLocation(21, 13), // (26,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b - 4).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b " + op + " 4").WithLocation(26, 78) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_01(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" static void M02(I1 x) { _ = x " + op + op + @" x; } void M03(I1 y) { _ = y " + op + op + @" y; } } class Test { static void MT1(I1 a) { _ = a " + op + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + op + @" b).ToString()); } static void MT3(I1 b, dynamic c) { _ = b " + op + op + @" c; } "; if (!success) { source1 += @" static void MT4<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T, dynamic>>)((T d, dynamic e) => (d " + op + op + @" e).ToString()); } "; } source1 += @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); if (success) { Assert.False(binaryIsAbstract); Assert.False(op == "&" ? falseIsAbstract : trueIsAbstract); var binaryMetadataName = op == "&" ? "op_BitwiseAnd" : "op_BitwiseOr"; var unaryMetadataName = op == "&" ? "op_False" : "op_True"; var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.MT1(I1)", @" { // Code size 22 (0x16) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0009: brtrue.s IL_0015 IL_000b: ldloc.0 IL_000c: ldarg.0 IL_000d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0012: pop IL_0013: br.s IL_0015 IL_0015: ret } "); if (op == "&") { verifier.VerifyIL("Test.MT3(I1, dynamic)", @" { // Code size 97 (0x61) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""bool I1.op_False(I1)"" IL_0007: brtrue.s IL_0060 IL_0009: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_000e: brfalse.s IL_0012 IL_0010: br.s IL_0047 IL_0012: ldc.i4.8 IL_0013: ldc.i4.2 IL_0014: ldtoken ""Test"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.2 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.1 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: dup IL_002f: ldc.i4.1 IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0037: stelem.ref IL_0038: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0042: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_004c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Target"" IL_0051: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0056: ldarg.0 IL_0057: ldarg.1 IL_0058: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, I1, dynamic)"" IL_005d: pop IL_005e: br.s IL_0060 IL_0060: ret } "); } else { verifier.VerifyIL("Test.MT3(I1, dynamic)", @" { // Code size 98 (0x62) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""bool I1.op_True(I1)"" IL_0007: brtrue.s IL_0061 IL_0009: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_000e: brfalse.s IL_0012 IL_0010: br.s IL_0048 IL_0012: ldc.i4.8 IL_0013: ldc.i4.s 36 IL_0015: ldtoken ""Test"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: ldc.i4.2 IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0025: dup IL_0026: ldc.i4.0 IL_0027: ldc.i4.1 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: dup IL_0030: ldc.i4.1 IL_0031: ldc.i4.0 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003e: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0043: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_004d: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Target"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0057: ldarg.0 IL_0058: ldarg.1 IL_0059: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, I1, dynamic)"" IL_005e: pop IL_005f: br.s IL_0061 IL_0061: ret } "); } } else { var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); builder.AddRange( // (10,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x && x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + op + " x").WithLocation(10, 13), // (15,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y && y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + op + " y").WithLocation(15, 13), // (23,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a && a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + op + " a").WithLocation(23, 13), // (28,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b && b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b " + op + op + " b").WithLocation(28, 78) ); if (op == "&" ? falseIsAbstract : trueIsAbstract) { builder.Add( // (33,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = b || c; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "b " + op + op + " c").WithLocation(33, 13) ); } builder.Add( // (38,98): error CS7083: Expression must be implicitly convertible to Boolean or its type 'T' must define operator 'true'. // _ = (System.Linq.Expressions.Expression<System.Action<T, dynamic>>)((T d, dynamic e) => (d || e).ToString()); Diagnostic(ErrorCode.ERR_InvalidDynamicCondition, "d").WithArguments("T", op == "&" ? "false" : "true").WithLocation(38, 98) ); compilation1.VerifyDiagnostics(builder.ToArrayAndFree()); } } [Theory] [CombinatorialData] public void ConsumeAbstractCompoundBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>")] string op) { var source1 = @" interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); static void M02(I1 x) { x " + op + @"= 1; } void M03(I1 y) { y " + op + @"= 2; } } interface I2<T> where T : I2<T> { abstract static T operator" + op + @" (T x, int y); } class Test { static void MT1(I1 a) { a " + op + @"= 3; } static void MT2<T>() where T : I2<T> { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + @"= 4).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x /= 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + "= 1").WithLocation(8, 9), // (13,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // y /= 2; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + "= 2").WithLocation(13, 9), // (26,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // a /= 3; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + "= 3").WithLocation(26, 9), // (31,78): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b /= 4).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b " + op + "= 4").WithLocation(31, 78) ); } private static string BinaryOperatorKind(string op) { switch (op) { case "+": return "Add"; case "-": return "Subtract"; case "*": return "Multiply"; case "/": return "Divide"; case "%": return "Remainder"; case "<<": return "LeftShift"; case ">>": return "RightShift"; case "&": return "And"; case "|": return "Or"; case "^": return "ExclusiveOr"; case "<": return "LessThan"; case "<=": return "LessThanOrEqual"; case "==": return "Equals"; case "!=": return "NotEquals"; case ">=": return "GreaterThanOrEqual"; case ">": return "GreaterThan"; } throw TestExceptionUtilities.UnexpectedValue(op); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); abstract static bool operator == (I1<T> x, I1<T> y); abstract static bool operator != (I1<T> x, I1<T> y); static void M02((int, I1<T>) x) { _ = x " + op + @" x; } void M03((int, I1<T>) y) { _ = y " + op + @" y; } } class Test { static void MT1<T>((int, I1<T>) a) where T : I1<T> { _ = a " + op + @" a; } static void MT2<T>() where T : I1<T> { _ = (System.Linq.Expressions.Expression<System.Action<(int, T)>>)(((int, T) b) => (b " + op + @" b).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (12,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x == x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " x").WithLocation(12, 13), // (17,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y == y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " y").WithLocation(17, 13), // (25,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a == a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " a").WithLocation(25, 13), // (30,92): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, T)>>)(((int, T) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(30, 92) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_03([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>")] string op) { string metadataName = BinaryOperatorName(op); bool isShiftOperator = op is "<<" or ">>"; var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static T0 operator" + op + @" (T0 x, int a); } partial class Test { static void M03<T, U>(T x) where T : U where U : I1<T> { _ = x " + op + @" 1; } static void M05<T, U>(T? y) where T : struct, U where U : I1<T> { _ = y " + op + @" 1; } } "; if (!isShiftOperator) { source1 += @" public partial interface I1<T0> { abstract static T0 operator" + op + @" (int a, T0 x); abstract static T0 operator" + op + @" (I1<T0> x, T0 a); abstract static T0 operator" + op + @" (T0 x, I1<T0> a); } partial class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = 1 " + op + @" x; } static void M04<T, U>(T? y) where T : struct, U where U : I1<T> { _ = 1 " + op + @" y; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { _ = x " + op + @" y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { _ = x " + op + @" y; } } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldarg.0 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(int, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_000e IL_000c: br.s IL_0022 IL_000e: ldc.i4.1 IL_000f: ldloca.s V_0 IL_0011: call ""readonly T T?.GetValueOrDefault()"" IL_0016: constrained. ""T"" IL_001c: call ""T I1<T>." + metadataName + @"(int, T)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: pop IL_000f: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_000e IL_000c: br.s IL_0022 IL_000e: ldloca.s V_0 IL_0010: call ""readonly T T?.GetValueOrDefault()"" IL_0015: ldc.i4.1 IL_0016: constrained. ""T"" IL_001c: call ""T I1<T>." + metadataName + @"(T, int)"" IL_0021: pop IL_0022: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 32 (0x20) .maxstack 2 .locals init (T? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brfalse.s IL_001f IL_000b: ldc.i4.1 IL_000c: ldloca.s V_0 IL_000e: call ""readonly T T?.GetValueOrDefault()"" IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + metadataName + @"(int, T)"" IL_001e: pop IL_001f: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: pop IL_000e: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 32 (0x20) .maxstack 2 .locals init (T? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brfalse.s IL_001f IL_000b: ldloca.s V_0 IL_000d: call ""readonly T T?.GetValueOrDefault()"" IL_0012: ldc.i4.1 IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + metadataName + @"(T, int)"" IL_001e: pop IL_001f: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " 1").Single(); Assert.Equal("x " + op + " 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.Binary, Type: T) (Syntax: 'x " + op + @" 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractComparisonBinaryOperator_03([CombinatorialValues("<", ">", "<=", ">=", "==", "!=")] string op) { string metadataName = BinaryOperatorName(op); var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static bool operator" + op + @" (T0 x, int a); abstract static bool operator" + op + @" (int a, T0 x); abstract static bool operator" + op + @" (I1<T0> x, T0 a); abstract static bool operator" + op + @" (T0 x, I1<T0> a); } partial class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = 1 " + op + @" x; } static void M03<T, U>(T x) where T : U where U : I1<T> { _ = x " + op + @" 1; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { _ = x " + op + @" y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { _ = x " + op + @" y; } } "; string matchingOp = MatchingBinaryOperator(op); source1 += @" public partial interface I1<T0> { abstract static bool operator" + matchingOp + @" (T0 x, int a); abstract static bool operator" + matchingOp + @" (int a, T0 x); abstract static bool operator" + matchingOp + @" (I1<T0> x, T0 a); abstract static bool operator" + matchingOp + @" (T0 x, I1<T0> a); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldarg.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(int, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(T, int)"" IL_000e: pop IL_000f: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(int, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(T, int)"" IL_000d: pop IL_000e: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " 1").Single(); Assert.Equal("x " + op + " 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @") (OperatorMethod: System.Boolean I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x " + op + @" 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractLiftedComparisonBinaryOperator_03([CombinatorialValues("<", ">", "<=", ">=", "==", "!=")] string op) { string metadataName = BinaryOperatorName(op); var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static bool operator" + op + @" (T0 x, T0 a); } partial class Test { static void M04<T, U>(T? x, T? y) where T : struct, U where U : I1<T> { _ = x " + op + @" y; } } "; string matchingOp = MatchingBinaryOperator(op); source1 += @" public partial interface I1<T0> { abstract static bool operator" + matchingOp + @" (T0 x, T0 a); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op is "==" or "!=") { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 61 (0x3d) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool T?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: beq.s IL_0017 IL_0015: br.s IL_003c IL_0017: ldloca.s V_0 IL_0019: call ""readonly bool T?.HasValue.get"" IL_001e: brtrue.s IL_0022 IL_0020: br.s IL_003c IL_0022: ldloca.s V_0 IL_0024: call ""readonly T T?.GetValueOrDefault()"" IL_0029: ldloca.s V_1 IL_002b: call ""readonly T T?.GetValueOrDefault()"" IL_0030: constrained. ""T"" IL_0036: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_003b: pop IL_003c: ret } "); } else { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool T?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: and IL_0014: brtrue.s IL_0018 IL_0016: br.s IL_0032 IL_0018: ldloca.s V_0 IL_001a: call ""readonly T T?.GetValueOrDefault()"" IL_001f: ldloca.s V_1 IL_0021: call ""readonly T T?.GetValueOrDefault()"" IL_0026: constrained. ""T"" IL_002c: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_0031: pop IL_0032: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op is "==" or "!=") { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 56 (0x38) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: bne.un.s IL_0037 IL_0014: ldloca.s V_0 IL_0016: call ""readonly bool T?.HasValue.get"" IL_001b: brfalse.s IL_0037 IL_001d: ldloca.s V_0 IL_001f: call ""readonly T T?.GetValueOrDefault()"" IL_0024: ldloca.s V_1 IL_0026: call ""readonly T T?.GetValueOrDefault()"" IL_002b: constrained. ""T"" IL_0031: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_0036: pop IL_0037: ret } "); } else { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 48 (0x30) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: and IL_0013: brfalse.s IL_002f IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: ldloca.s V_1 IL_001e: call ""readonly T T?.GetValueOrDefault()"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_002e: pop IL_002f: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " y").Single(); Assert.Equal("x " + op + " y", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @", IsLifted) (OperatorMethod: System.Boolean I1<T>." + metadataName + @"(T x, T a)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x " + op + @" y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T?) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T?) (Syntax: 'y') "); } [Theory] [InlineData("&", true, true)] [InlineData("|", true, true)] [InlineData("&", true, false)] [InlineData("|", true, false)] [InlineData("&", false, true)] [InlineData("|", false, true)] public void ConsumeAbstractLogicalBinaryOperator_03(string op, bool binaryIsAbstract, bool unaryIsAbstract) { var binaryMetadataName = op == "&" ? "op_BitwiseAnd" : "op_BitwiseOr"; var unaryMetadataName = op == "&" ? "op_False" : "op_True"; var opKind = op == "&" ? "ConditionalAnd" : "ConditionalOr"; if (binaryIsAbstract && unaryIsAbstract) { consumeAbstract(op); } else { consumeMixed(op, binaryIsAbstract, unaryIsAbstract); } void consumeAbstract(string op) { var source1 = @" public interface I1<T0> where T0 : I1<T0> { abstract static T0 operator" + op + @" (T0 a, T0 x); abstract static bool operator true (T0 x); abstract static bool operator false (T0 x); } public interface I2<T0> where T0 : struct, I2<T0> { abstract static T0 operator" + op + @" (T0 a, T0 x); abstract static bool operator true (T0? x); abstract static bool operator false (T0? x); } class Test { static void M03<T, U>(T x, T y) where T : U where U : I1<T> { _ = x " + op + op + @" y; } static void M04<T, U>(T? x, T? y) where T : struct, U where U : I2<T> { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 34 (0x22) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: constrained. ""T"" IL_000a: call ""bool I1<T>." + unaryMetadataName + @"(T)"" IL_000f: brtrue.s IL_0021 IL_0011: ldloc.0 IL_0012: ldarg.1 IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + binaryMetadataName + @"(T, T)"" IL_001e: pop IL_001f: br.s IL_0021 IL_0021: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 69 (0x45) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: constrained. ""T"" IL_000a: call ""bool I2<T>." + unaryMetadataName + @"(T?)"" IL_000f: brtrue.s IL_0044 IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldarg.1 IL_0014: stloc.2 IL_0015: ldloca.s V_1 IL_0017: call ""readonly bool T?.HasValue.get"" IL_001c: ldloca.s V_2 IL_001e: call ""readonly bool T?.HasValue.get"" IL_0023: and IL_0024: brtrue.s IL_0028 IL_0026: br.s IL_0042 IL_0028: ldloca.s V_1 IL_002a: call ""readonly T T?.GetValueOrDefault()"" IL_002f: ldloca.s V_2 IL_0031: call ""readonly T T?.GetValueOrDefault()"" IL_0036: constrained. ""T"" IL_003c: call ""T I2<T>." + binaryMetadataName + @"(T, T)"" IL_0041: pop IL_0042: br.s IL_0044 IL_0044: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + unaryMetadataName + @"(T)"" IL_000e: brtrue.s IL_001e IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: constrained. ""T"" IL_0018: call ""T I1<T>." + binaryMetadataName + @"(T, T)"" IL_001d: pop IL_001e: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 64 (0x40) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I2<T>." + unaryMetadataName + @"(T?)"" IL_000e: brtrue.s IL_003f IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: ldarg.1 IL_0013: stloc.2 IL_0014: ldloca.s V_1 IL_0016: call ""readonly bool T?.HasValue.get"" IL_001b: ldloca.s V_2 IL_001d: call ""readonly bool T?.HasValue.get"" IL_0022: and IL_0023: brfalse.s IL_003f IL_0025: ldloca.s V_1 IL_0027: call ""readonly T T?.GetValueOrDefault()"" IL_002c: ldloca.s V_2 IL_002e: call ""readonly T T?.GetValueOrDefault()"" IL_0033: constrained. ""T"" IL_0039: call ""T I2<T>." + binaryMetadataName + @"(T, T)"" IL_003e: pop IL_003f: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + op + " y").First(); Assert.Equal("x " + op + op + " y", node1.ToString()); VerifyOperationTreeForNode(compilation1, model, node1, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + opKind + @") (OperatorMethod: T I1<T>." + binaryMetadataName + @"(T a, T x)) (OperationKind.Binary, Type: T) (Syntax: 'x " + op + op + @" y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T) (Syntax: 'y') "); } void consumeMixed(string op, bool binaryIsAbstract, bool unaryIsAbstract) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 a, I1 x)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (unaryIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (unaryIsAbstract ? ";" : " => throw null;") + @" " + (unaryIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (unaryIsAbstract ? ";" : " => throw null;") + @" } class Test { static void M03<T, U>(T x, T y) where T : U where U : I1 { _ = x " + op + op + @" y; } static void M04<T, U>(T? x, T? y) where T : struct, U where U : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch (binaryIsAbstract, unaryIsAbstract) { case (true, false): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000e: brtrue.s IL_0025 IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: box ""T"" IL_0017: constrained. ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T?"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000e: brtrue.s IL_0025 IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: box ""T?"" IL_0017: constrained. ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); break; case (false, true): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: constrained. ""T"" IL_000f: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldarg.1 IL_0018: box ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T?"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: constrained. ""T"" IL_000f: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldarg.1 IL_0018: box ""T?"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); break; default: Assert.True(false); break; } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch (binaryIsAbstract, unaryIsAbstract) { case (true, false): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000d: brtrue.s IL_0022 IL_000f: ldloc.0 IL_0010: ldarg.1 IL_0011: box ""T"" IL_0016: constrained. ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000d: brtrue.s IL_0022 IL_000f: ldloc.0 IL_0010: ldarg.1 IL_0011: box ""T?"" IL_0016: constrained. ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); break; case (false, true): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: constrained. ""T"" IL_000e: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0013: brtrue.s IL_0022 IL_0015: ldloc.0 IL_0016: ldarg.1 IL_0017: box ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: constrained. ""T"" IL_000e: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0013: brtrue.s IL_0022 IL_0015: ldloc.0 IL_0016: ldarg.1 IL_0017: box ""T?"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); break; default: Assert.True(false); break; } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + op + " y").First(); Assert.Equal("x " + op + op + " y", node1.ToString()); VerifyOperationTreeForNode(compilation1, model, node1, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + opKind + @") (OperatorMethod: I1 I1." + binaryMetadataName + @"(I1 a, I1 x)) (OperationKind.Binary, Type: I1) (Syntax: 'x " + op + op + @" y') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: I1, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: I1, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T) (Syntax: 'y') "); } } [Theory] [InlineData("+", "op_Addition", "Add")] [InlineData("-", "op_Subtraction", "Subtract")] [InlineData("*", "op_Multiply", "Multiply")] [InlineData("/", "op_Division", "Divide")] [InlineData("%", "op_Modulus", "Remainder")] [InlineData("&", "op_BitwiseAnd", "And")] [InlineData("|", "op_BitwiseOr", "Or")] [InlineData("^", "op_ExclusiveOr", "ExclusiveOr")] [InlineData("<<", "op_LeftShift", "LeftShift")] [InlineData(">>", "op_RightShift", "RightShift")] public void ConsumeAbstractCompoundBinaryOperator_03(string op, string metadataName, string operatorKind) { bool isShiftOperator = op.Length == 2; var source1 = @" public interface I1<T0> where T0 : I1<T0> { "; if (!isShiftOperator) { source1 += @" abstract static int operator" + op + @" (int a, T0 x); abstract static I1<T0> operator" + op + @" (I1<T0> x, T0 a); abstract static T0 operator" + op + @" (T0 x, I1<T0> a); "; } source1 += @" abstract static T0 operator" + op + @" (T0 x, int a); } class Test { "; if (!isShiftOperator) { source1 += @" static void M02<T, U>(int a, T x) where T : U where U : I1<T> { a " + op + @"= x; } static void M04<T, U>(int? a, T? y) where T : struct, U where U : I1<T> { a " + op + @"= y; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { x " + op + @"= y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { x " + op + @"= y; } "; } source1 += @" static void M03<T, U>(T x) where T : U where U : I1<T> { x " + op + @"= 1; } static void M05<T, U>(T? y) where T : struct, U where U : I1<T> { y " + op + @"= 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(int, T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""int I1<T>." + metadataName + @"(int, T)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?, T?)", @" { // Code size 66 (0x42) .maxstack 2 .locals init (int? V_0, T? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool int?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: and IL_0014: brtrue.s IL_0021 IL_0016: ldloca.s V_2 IL_0018: initobj ""int?"" IL_001e: ldloc.2 IL_001f: br.s IL_003f IL_0021: ldloca.s V_0 IL_0023: call ""readonly int int?.GetValueOrDefault()"" IL_0028: ldloca.s V_1 IL_002a: call ""readonly T T?.GetValueOrDefault()"" IL_002f: constrained. ""T"" IL_0035: call ""int I1<T>." + metadataName + @"(int, T)"" IL_003a: newobj ""int?..ctor(int)"" IL_003f: starg.s V_0 IL_0041: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""I1<T> I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: starg.s V_0 IL_0010: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 50 (0x32) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002f IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: ldc.i4.1 IL_001f: constrained. ""T"" IL_0025: call ""T I1<T>." + metadataName + @"(T, int)"" IL_002a: newobj ""T?..ctor(T)"" IL_002f: starg.s V_0 IL_0031: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(int, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(int, T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?, T?)", @" { // Code size 65 (0x41) .maxstack 2 .locals init (int? V_0, T? V_1, int? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool int?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: and IL_0013: brtrue.s IL_0020 IL_0015: ldloca.s V_2 IL_0017: initobj ""int?"" IL_001d: ldloc.2 IL_001e: br.s IL_003e IL_0020: ldloca.s V_0 IL_0022: call ""readonly int int?.GetValueOrDefault()"" IL_0027: ldloca.s V_1 IL_0029: call ""readonly T T?.GetValueOrDefault()"" IL_002e: constrained. ""T"" IL_0034: call ""int I1<T>." + metadataName + @"(int, T)"" IL_0039: newobj ""int?..ctor(int)"" IL_003e: starg.s V_0 IL_0040: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""I1<T> I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: starg.s V_0 IL_000f: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0016 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: br.s IL_002e IL_0016: ldloca.s V_0 IL_0018: call ""readonly T T?.GetValueOrDefault()"" IL_001d: ldc.i4.1 IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T, int)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: starg.s V_0 IL_0030: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(n => n.ToString() == "x " + op + "= 1").Single(); Assert.Equal("x " + op + "= 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" ICompoundAssignmentOperation (BinaryOperatorKind." + operatorKind + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.CompoundAssignment, Type: T) (Syntax: 'x " + op + @"= 1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } class Test { static void M02<T, U>((int, T) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0011: bne.un.s IL_002c IL_0013: ldloc.0 IL_0014: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001f: constrained. ""T"" IL_0025: call ""bool I1<T>.op_Equality(T, T)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.0 IL_002d: pop IL_002e: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0011: bne.un.s IL_002c IL_0013: ldloc.0 IL_0014: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001f: constrained. ""T"" IL_0025: call ""bool I1<T>.op_Inequality(T, T)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.1 IL_002d: pop IL_002e: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0010: bne.un.s IL_002b IL_0012: ldloc.0 IL_0013: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001e: constrained. ""T"" IL_0024: call ""bool I1<T>.op_Equality(T, T)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0010: bne.un.s IL_002b IL_0012: ldloc.0 IL_0013: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001e: constrained. ""T"" IL_0024: call ""bool I1<T>.op_Inequality(T, T)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.1 IL_002c: pop IL_002d: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, T)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, T)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1 { _ = x " + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x - y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " y").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator- (I1 x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 32) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_04(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" } "; var source2 = @" class Test { static void M02<T>(T x, T y) where T : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); if (success) { compilation2.VerifyDiagnostics(); } else { compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x && y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + op + " y").WithLocation(6, 13) ); } var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); if (binaryIsAbstract) { builder.Add( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator& (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 32) ); } if (trueIsAbstract) { builder.Add( // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(13, 35) ); } if (falseIsAbstract) { builder.Add( // (14,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(14, 35) ); } compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation).Verify(builder.ToArrayAndFree()); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("*")] [InlineData("/")] [InlineData("%")] [InlineData("&")] [InlineData("|")] [InlineData("^")] [InlineData("<<")] [InlineData(">>")] public void ConsumeAbstractCompoundBinaryOperator_04(string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + op + @" (T x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1<T> { x " + op + @"= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // x *= y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + "= y").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator* (T x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 31) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } "; var source2 = @" class Test { static void M02<T>((int, T) x) where T : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator == (T x, T y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "==").WithLocation(12, 35), // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator != (T x, T y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "!=").WithLocation(13, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_06([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1 { _ = x " + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x - y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " y").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator- (I1 x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 32) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_06(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" } "; var source2 = @" class Test { static void M02<T>(T x, T y) where T : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); if (success) { compilation2.VerifyDiagnostics(); } else { compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x && y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + op + " y").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); } var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); if (binaryIsAbstract) { builder.Add( // (12,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator& (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 32) ); } if (trueIsAbstract) { builder.Add( // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } if (falseIsAbstract) { builder.Add( // (14,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(14, 35) ); } compilation3.VerifyDiagnostics(builder.ToArrayAndFree()); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("*")] [InlineData("/")] [InlineData("%")] [InlineData("&")] [InlineData("|")] [InlineData("^")] [InlineData("<<")] [InlineData(">>")] public void ConsumeAbstractCompoundBinaryOperator_06(string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + op + @" (T x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1<T> { x " + op + @"= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x <<= y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + "= y").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (12,31): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator<< (T x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 31) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } "; var source2 = @" class Test { static void M02<T>((int, T) x) where T : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (12,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator == (T x, T y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(12, 35), // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator != (T x, T y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { _ = P01; _ = P04; } void M03() { _ = this.P01; _ = this.P04; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { _ = I1.P01; _ = x.P01; _ = I1.P04; _ = x.P04; } static void MT2<T>() where T : I1 { _ = T.P03; _ = T.P04; _ = T.P00; _ = T.P05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01.ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = P01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 13), // (14,13): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = this.P01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 13), // (15,13): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = this.P04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 13), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = I1.P01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 13), // (28,13): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = x.P01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 13), // (30,13): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = x.P04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 13), // (35,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 13), // (36,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 13), // (37,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 13), // (38,15): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = T.P05; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 15), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01.ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticPropertySet_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { P01 = 1; P04 = 1; } void M03() { this.P01 = 1; this.P04 = 1; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { I1.P01 = 1; x.P01 = 1; I1.P04 = 1; x.P04 = 1; } static void MT2<T>() where T : I1 { T.P03 = 1; T.P04 = 1; T.P00 = 1; T.P05 = 1; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 = 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 = 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 = 1; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 = 1").WithLocation(40, 71), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { P01 += 1; P04 += 1; } void M03() { this.P01 += 1; this.P04 += 1; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { I1.P01 += 1; x.P01 += 1; I1.P04 += 1; x.P04 += 1; } static void MT2<T>() where T : I1 { T.P03 += 1; T.P04 += 1; T.P00 += 1; T.P05 += 1; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 += 1; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 += 1").WithLocation(40, 71), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticProperty_02() { var source1 = @" interface I1 { abstract static int P01 { get; set; } static void M02() { _ = nameof(P01); _ = nameof(P04); } void M03() { _ = nameof(this.P01); _ = nameof(this.P04); } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { _ = nameof(I1.P01); _ = nameof(x.P01); _ = nameof(I1.P04); _ = nameof(x.P04); } static void MT2<T>() where T : I1 { _ = nameof(T.P03); _ = nameof(T.P04); _ = nameof(T.P00); _ = nameof(T.P05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (14,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 20), // (15,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 20), // (28,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 20), // (30,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 20), // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = nameof(T.P05); Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""int I1.P01.get"" IL_000c: pop IL_000d: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: constrained. ""T"" IL_0006: call ""int I1.P01.get"" IL_000b: pop IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Right; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertySet_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 15 (0xf) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""void I1.P01.set"" IL_000d: nop IL_000e: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: constrained. ""T"" IL_0007: call ""void I1.P01.set"" IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertyCompound_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { T.P01 += 1; } static string M03<T, U>() where T : U where U : I1 { return nameof(T.P01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""int I1.P01.get"" IL_000c: ldc.i4.1 IL_000d: add IL_000e: constrained. ""T"" IL_0014: call ""void I1.P01.set"" IL_0019: nop IL_001a: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""P01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: constrained. ""T"" IL_0006: call ""int I1.P01.get"" IL_000b: ldc.i4.1 IL_000c: add IL_000d: constrained. ""T"" IL_0013: call ""void I1.P01.set"" IL_0018: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""P01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertyGet_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = T.P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertySet_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 = 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9), // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = T.P01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = T.P01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 13), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticPropertySet_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 = 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 = 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticEventAdd_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used interface I1 { abstract static event System.Action P01; static void M02() { P01 += null; P04 += null; } void M03() { this.P01 += null; this.P04 += null; } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { I1.P01 += null; x.P01 += null; I1.P04 += null; x.P04 += null; } static void MT2<T>() where T : I1 { T.P03 += null; T.P04 += null; T.P00 += null; T.P05 += null; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += null); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01 += null").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (14,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // this.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "this.P01 += null").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01 += null").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (28,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x.P01 += null").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += null); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 += null").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticEventRemove_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used interface I1 { abstract static event System.Action P01; static void M02() { P01 -= null; P04 -= null; } void M03() { this.P01 -= null; this.P04 -= null; } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { I1.P01 -= null; x.P01 -= null; I1.P04 -= null; x.P04 -= null; } static void MT2<T>() where T : I1 { T.P03 -= null; T.P04 -= null; T.P00 -= null; T.P05 -= null; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 -= null); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01 -= null").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (14,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // this.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "this.P01 -= null").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01 -= null").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (28,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x.P01 -= null").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 -= null); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 -= null").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticEvent_02() { var source1 = @" interface I1 { abstract static event System.Action P01; static void M02() { _ = nameof(P01); _ = nameof(P04); } void M03() { _ = nameof(this.P01); _ = nameof(this.P04); } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { _ = nameof(I1.P01); _ = nameof(x.P01); _ = nameof(I1.P04); _ = nameof(x.P04); } static void MT2<T>() where T : I1 { _ = nameof(T.P03); _ = nameof(T.P04); _ = nameof(T.P00); _ = nameof(T.P05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (14,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 20), // (15,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 20), // (28,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 20), // (30,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 20), // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = nameof(T.P05); Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticEvent_03() { var source1 = @" public interface I1 { abstract static event System.Action E01; } class Test { static void M02<T, U>() where T : U where U : I1 { T.E01 += null; T.E01 -= null; } static string M03<T, U>() where T : U where U : I1 { return nameof(T.E01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 28 (0x1c) .maxstack 1 IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: call ""void I1.E01.add"" IL_000d: nop IL_000e: ldnull IL_000f: constrained. ""T"" IL_0015: call ""void I1.E01.remove"" IL_001a: nop IL_001b: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""E01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 25 (0x19) .maxstack 1 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: call ""void I1.E01.add"" IL_000c: ldnull IL_000d: constrained. ""T"" IL_0013: call ""void I1.E01.remove"" IL_0018: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""E01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.E01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IEventReferenceOperation: event System.Action I1.E01 (Static) (OperationKind.EventReference, Type: System.Action) (Syntax: 'T.E01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "E01").Single().ToTestDisplayString()); Assert.Equal("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "E01").Single().ToTestDisplayString()); Assert.Contains("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("event System.Action I1.E01", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "E01").Single().ToTestDisplayString()); Assert.Equal("event System.Action I1.E01", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "E01").Single().ToTestDisplayString()); Assert.Contains("event System.Action I1.E01", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("event System.Action I1.E01", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("E01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticEventAdd_04() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01 += null").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "P01").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventRemove_04() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 -= null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01 -= null").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "P01").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventAdd_06() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventRemove_06() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 -= null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 -= null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticIndexedProperty_03() { var ilSource = @" .class interface public auto ansi abstract I1 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) // Methods .method public hidebysig specialname newslot abstract virtual static int32 get_Item ( int32 x ) cil managed { } // end of method I1::get_Item .method public hidebysig specialname newslot abstract virtual static void set_Item ( int32 x, int32 'value' ) cil managed { } // end of method I1::set_Item // Properties .property int32 Item( int32 x ) { .get int32 I1::get_Item(int32) .set void I1::set_Item(int32, int32) } } // end of class I1 "; var source1 = @" class Test { static void M02<T>() where T : I1 { T.Item[0] += 1; } static string M03<T>() where T : I1 { return nameof(T.Item); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (6,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.Item[0] += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(6, 9), // (11,23): error CS0119: 'T' is a type parameter, which is not valid in the given context // return nameof(T.Item); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(11, 23) ); var source2 = @" class Test { static void M02<T>() where T : I1 { T[0] += 1; } static void M03<T>() where T : I1 { T.set_Item(0, T.get_Item(0) + 1); } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation2.VerifyDiagnostics( // (6,9): error CS0119: 'T' is a type, which is not valid in the given context // T[0] += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(6, 9), // (11,11): error CS0571: 'I1.this[int].set': cannot explicitly call operator or accessor // T.set_Item(0, T.get_Item(0) + 1); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Item").WithArguments("I1.this[int].set").WithLocation(11, 11), // (11,25): error CS0571: 'I1.this[int].get': cannot explicitly call operator or accessor // T.set_Item(0, T.get_Item(0) + 1); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("I1.this[int].get").WithLocation(11, 25) ); } [Fact] public void ConsumeAbstractStaticIndexedProperty_04() { var ilSource = @" .class interface public auto ansi abstract I1 { // Methods .method public hidebysig specialname newslot abstract virtual static int32 get_Item ( int32 x ) cil managed { } // end of method I1::get_Item .method public hidebysig specialname newslot abstract virtual static void set_Item ( int32 x, int32 'value' ) cil managed { } // end of method I1::set_Item // Properties .property int32 Item( int32 x ) { .get int32 I1::get_Item(int32) .set void I1::set_Item(int32, int32) } } // end of class I1 "; var source1 = @" class Test { static void M02<T>() where T : I1 { T.Item[0] += 1; } static string M03<T>() where T : I1 { return nameof(T.Item); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (6,11): error CS1545: Property, indexer, or event 'I1.Item[int]' is not supported by the language; try directly calling accessor methods 'I1.get_Item(int)' or 'I1.set_Item(int, int)' // T.Item[0] += 1; Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Item").WithArguments("I1.Item[int]", "I1.get_Item(int)", "I1.set_Item(int, int)").WithLocation(6, 11), // (11,25): error CS1545: Property, indexer, or event 'I1.Item[int]' is not supported by the language; try directly calling accessor methods 'I1.get_Item(int)' or 'I1.set_Item(int, int)' // return nameof(T.Item); Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Item").WithArguments("I1.Item[int]", "I1.get_Item(int)", "I1.set_Item(int, int)").WithLocation(11, 25) ); var source2 = @" class Test { static void M02<T>() where T : I1 { T.set_Item(0, T.get_Item(0) + 1); } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation2, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T>()", @" { // Code size 29 (0x1d) .maxstack 3 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: ldc.i4.0 IL_0003: constrained. ""T"" IL_0009: call ""int I1.get_Item(int)"" IL_000e: ldc.i4.1 IL_000f: add IL_0010: constrained. ""T"" IL_0016: call ""void I1.set_Item(int, int)"" IL_001b: nop IL_001c: ret } "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = (System.Action)M01; _ = (System.Action)M04; } void M03() { _ = (System.Action)this.M01; _ = (System.Action)this.M04; } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = (System.Action)I1.M01; _ = (System.Action)x.M01; _ = (System.Action)I1.M04; _ = (System.Action)x.M04; } static void MT2<T>() where T : I1 { _ = (System.Action)T.M03; _ = (System.Action)T.M04; _ = (System.Action)T.M00; _ = (System.Action)T.M05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.Action)T.M01).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (System.Action)M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(System.Action)M01").WithLocation(8, 13), // (14,28): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)this.M01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 28), // (15,28): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)this.M04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 28), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (System.Action)I1.M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(System.Action)I1.M01").WithLocation(27, 13), // (28,28): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)x.M01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 28), // (30,28): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)x.M04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 28), // (35,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 28), // (36,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 28), // (37,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 28), // (38,30): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = (System.Action)T.M05; Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 30), // (40,87): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.Action)T.M01).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01").WithLocation(40, 87) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_03() { var source1 = @" public interface I1 { abstract static void M01(); } class Test { static System.Action M02<T, U>() where T : U where U : I1 { return T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 24 (0x18) .maxstack 2 .locals init (System.Action V_0) IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: ldftn ""void I1.M01()"" IL_000e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0012: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = (System.Action)T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "(System.Action)T.M01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = (System.Action)T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,28): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 28) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (6,28): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 28), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = new System.Action(M01); _ = new System.Action(M04); } void M03() { _ = new System.Action(this.M01); _ = new System.Action(this.M04); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = new System.Action(I1.M01); _ = new System.Action(x.M01); _ = new System.Action(I1.M04); _ = new System.Action(x.M04); } static void MT2<T>() where T : I1 { _ = new System.Action(T.M03); _ = new System.Action(T.M04); _ = new System.Action(T.M00); _ = new System.Action(T.M05); _ = (System.Linq.Expressions.Expression<System.Action>)(() => new System.Action(T.M01).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,31): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = new System.Action(M01); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "M01").WithLocation(8, 31), // (14,31): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(this.M01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 31), // (15,31): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(this.M04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 31), // (27,31): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = new System.Action(I1.M01); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.M01").WithLocation(27, 31), // (28,31): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(x.M01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 31), // (30,31): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(x.M04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 31), // (35,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 31), // (36,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 31), // (37,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 31), // (38,33): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = new System.Action(T.M05); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 33), // (40,89): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => new System.Action(T.M01).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01").WithLocation(40, 89) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_03() { var source1 = @" public interface I1 { abstract static void M01(); } class Test { static System.Action M02<T, U>() where T : U where U : I1 { return new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 24 (0x18) .maxstack 2 .locals init (System.Action V_0) IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: ldftn ""void I1.M01()"" IL_000e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0012: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.M01").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_01() { var source1 = @" unsafe interface I1 { abstract static void M01(); static void M02() { _ = (delegate*<void>)&M01; _ = (delegate*<void>)&M04; } void M03() { _ = (delegate*<void>)&this.M01; _ = (delegate*<void>)&this.M04; } static void M04() {} protected abstract static void M05(); } unsafe class Test { static void MT1(I1 x) { _ = (delegate*<void>)&I1.M01; _ = (delegate*<void>)&x.M01; _ = (delegate*<void>)&I1.M04; _ = (delegate*<void>)&x.M04; } static void MT2<T>() where T : I1 { _ = (delegate*<void>)&T.M03; _ = (delegate*<void>)&T.M04; _ = (delegate*<void>)&T.M00; _ = (delegate*<void>)&T.M05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (delegate*<void>)&M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(delegate*<void>)&M01").WithLocation(8, 13), // (14,13): error CS8757: No overload for 'M01' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&this.M01; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&this.M01").WithArguments("M01", "delegate*<void>").WithLocation(14, 13), // (15,13): error CS8757: No overload for 'M04' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&this.M04; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&this.M04").WithArguments("M04", "delegate*<void>").WithLocation(15, 13), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (delegate*<void>)&I1.M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(delegate*<void>)&I1.M01").WithLocation(27, 13), // (28,13): error CS8757: No overload for 'M01' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&x.M01; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&x.M01").WithArguments("M01", "delegate*<void>").WithLocation(28, 13), // (30,13): error CS8757: No overload for 'M04' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&x.M04; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&x.M04").WithArguments("M04", "delegate*<void>").WithLocation(30, 13), // (35,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 31), // (36,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 31), // (37,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 31), // (38,33): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = (delegate*<void>)&T.M05; Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 33), // (40,88): error CS1944: An expression tree may not contain an unsafe pointer operation // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "(delegate*<void>)&T.M01").WithLocation(40, 88), // (40,106): error CS8810: '&' on method groups cannot be used in expression trees // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); Diagnostic(ErrorCode.ERR_AddressOfMethodGroupInExpressionTree, "T.M01").WithLocation(40, 106) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_03() { var source1 = @" public interface I1 { abstract static void M01(); } unsafe class Test { static delegate*<void> M02<T, U>() where T : U where U : I1 { return &T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 18 (0x12) .maxstack 1 .locals init (delegate*<void> V_0) IL_0000: nop IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: constrained. ""T"" IL_0006: ldftn ""void I1.M01()"" IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionFunctionPointer_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" unsafe class Test { static void M02<T>() where T : I1 { _ = (delegate*<void>)&T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "(delegate*<void>)&T.M01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" unsafe class Test { static void M02<T>() where T : I1 { _ = (delegate*<void>)&T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public void M01() {} } " + typeKeyword + @" C3 : I1 { static void M01() {} } " + typeKeyword + @" C4 : I1 { void I1.M01() {} } " + typeKeyword + @" C5 : I1 { public static int M01() => throw null; } " + typeKeyword + @" C6 : I1 { static int I1.M01() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01()' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01()").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01()'. 'C2.M01()' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01()", "C2.M01()").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01()'. 'C3.M01()' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01()", "C3.M01()").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01()' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01()").WithLocation(24, 10), // (26,13): error CS0539: 'C4.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01()").WithLocation(26, 13), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01()'. 'C5.M01()' cannot implement 'I1.M01()' because it does not have the matching return type of 'void'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01()", "C5.M01()", "void").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01()' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01()").WithLocation(36, 10), // (38,19): error CS0539: 'C6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01()").WithLocation(38, 19) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract void M01(); } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static void M01() {} } " + typeKeyword + @" C3 : I1 { void M01() {} } " + typeKeyword + @" C4 : I1 { static void I1.M01() {} } " + typeKeyword + @" C5 : I1 { public int M01() => throw null; } " + typeKeyword + @" C6 : I1 { int I1.M01() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01()' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01()").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01()'. 'C2.M01()' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01()", "C2.M01()").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01()'. 'C3.M01()' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01()", "C3.M01()").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01()' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01()").WithLocation(24, 10), // (26,20): error CS0539: 'C4.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01()").WithLocation(26, 20), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01()'. 'C5.M01()' cannot implement 'I1.M01()' because it does not have the matching return type of 'void'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01()", "C5.M01()", "void").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01()' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01()").WithLocation(36, 10), // (38,12): error CS0539: 'C6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01()").WithLocation(38, 12) ); } [Fact] public void ImplementAbstractStaticMethod_03() { var source1 = @" public interface I1 { abstract static void M01(); } interface I2 : I1 {} interface I3 : I1 { public virtual void M01() {} } interface I4 : I1 { static void M01() {} } interface I5 : I1 { void I1.M01() {} } interface I6 : I1 { static void I1.M01() {} } interface I7 : I1 { abstract static void M01(); } interface I8 : I1 { abstract static void I1.M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (12,25): warning CS0108: 'I3.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // public virtual void M01() {} Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01()", "I1.M01()").WithLocation(12, 25), // (17,17): warning CS0108: 'I4.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // static void M01() {} Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01()", "I1.M01()").WithLocation(17, 17), // (22,13): error CS0539: 'I5.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01()").WithLocation(22, 13), // (27,20): error CS0106: The modifier 'static' is not valid for this item // static void I1.M01() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 20), // (27,20): error CS0539: 'I6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01()").WithLocation(27, 20), // (32,26): warning CS0108: 'I7.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // abstract static void M01(); Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01()", "I1.M01()").WithLocation(32, 26), // (37,29): error CS0106: The modifier 'static' is not valid for this item // abstract static void I1.M01(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 29), // (37,29): error CS0539: 'I8.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static void I1.M01(); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01()").WithLocation(37, 29) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); abstract static void M02(); } "; var source2 = typeKeyword + @" Test: I1 { static void I1.M01() {} public static void M02() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,20): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 20) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (4,20): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 20), // (10,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 26), // (11,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M02(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = typeKeyword + @" Test1: I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01()' cannot implement interface member 'I1.M01()' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01()", "I1.M01()", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01()' cannot implement interface member 'I1.M01()' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01()", "I1.M01()", "Test1").WithLocation(2, 12), // (9,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = typeKeyword + @" Test1: I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,20): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 20) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,20): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 20), // (9,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C : I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, cM01.MethodKind); Assert.Equal("void C.M01()", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C : I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.Equal("void C.I1.M01()", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticMethod_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static void M01(); } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C2.I1.M01()", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticMethod_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig static abstract virtual void M01 () cil managed { } // end of method I1::M01 } // end of class I1 .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static void I1.M01 () cil managed { .override method void I1::M01() .maxstack 8 IL_0000: ret } // end of method C1::I1.M01 .method public hidebysig static void M01 () cil managed { IL_0000: ret } // end of method C1::M01 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } // end of method C1::.ctor } // end of class C1 .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static void M01 () cil managed { IL_0000: ret } // end of method C2::M01 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1.I1.M01()", c1M01.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); Assert.Equal("void C2.M01()", c5.FindImplementationForInterfaceMember(m01).ToTestDisplayString()); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticMethod_11() { // Ignore invalid metadata (non-abstract static virtual method). var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig virtual static void M01 () cil managed { IL_0000: ret } // end of method I1::M01 } // end of class I1 "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static void I1.M01() {} } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation2.VerifyEmitDiagnostics( // (4,19): error CS0539: 'C1.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01()").WithLocation(4, 19) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Fact] public void ImplementAbstractStaticMethod_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void M01 () cil managed { } // end of method I1::M01 } // end of class I1 .class interface public auto ansi abstract I2 implements I1 { // Methods .method private hidebysig static void I1.M01 () cil managed { .override method void I1::M01() IL_0000: ret } // end of method I2::I1.M01 } // end of class I2 "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01()' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01()").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticMethod_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static void M01(); } class C1 { public static void M01() {} } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("void C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1.M01"); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Ordinary, c2M01.MethodKind); Assert.Equal("void C1.M01()", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C1.M01()"" IL_0005: ret } "); } [Fact] public void ImplementAbstractStaticMethod_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void modopt(I1) M01 () cil managed { } // end of method I1::M01 } // end of class I1 "; var source1 = @" class C1 : I1 { public static void M01() {} } class C2 : I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("void modopt(I1) C1.I1.M01()", c1M01.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1.M01"); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("void modopt(I1) C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C1.M01()"" IL_0005: ret } "); } [Fact] public void ImplementAbstractStaticMethod_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static void M01(); abstract static void M02(); } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static void I1.M02() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<MethodSymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>("M01"); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<MethodSymbol>().Single(); var c2M02 = c3.BaseType().GetMember<MethodSymbol>("I1.M02"); Assert.Equal("void C2.I1.M02()", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Fact] public void ImplementAbstractStaticMethod_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static void M01(); } public class C1 : I1 { public static void M01() {} } public class C2 : C1 { new public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C2.M01()"" IL_0005: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<MethodSymbol>("M01"); Assert.Equal("void C2.M01()", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C3.I1.M01()", c3M01.ToTestDisplayString()); Assert.Same(m01, c3M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_17(bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(System.Int32 x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(System.Int32 x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_18(bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(T x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(T x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_19(bool genericFirst) { // Same as ImplementAbstractStaticMethod_17 only implementation is explicit in source. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" static void I1.M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.I1.M01(System.Int32 x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_20(bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implementation is explicit in source. var generic = @" static void I1<T>.M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.I1<T>.M01(T x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_21(bool genericFirst) { // Same as ImplementAbstractStaticMethod_17 only implicit implementation is in an intermediate base. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T> : C1<T>, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C11<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "void C11<T>.I1.M01(System.Int32 x)" : "void C1<T>.M01(System.Int32 x)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_22(bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implicit implementation is in an intermediate base. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T> : C1<T>, I1<T> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C11<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "void C11<T>.I1<T>.M01(T x)" : "void C1<T>.M01(T x)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } private static string UnaryOperatorName(string op) => OperatorFacts.UnaryOperatorNameFromSyntaxKindIfAny(SyntaxFactory.ParseToken(op).Kind()); private static string BinaryOperatorName(string op) => op switch { ">>" => WellKnownMemberNames.RightShiftOperatorName, _ => OperatorFacts.BinaryOperatorNameFromSyntaxKindIfAny(SyntaxFactory.ParseToken(op).Kind()) }; [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = UnaryOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public C2 operator " + op + @"(C2 x) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static C3 operator " + op + @"(C3 x) => throw null; } " + typeKeyword + @" C4 : I1<C4> { C4 I1<C4>.operator " + op + @"(C4 x) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static int operator " + op + @" (C5 x) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static int I1<C6>.operator " + op + @" (C6 x) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static C7 " + opName + @"(C7 x) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static C8 I1<C8>." + opName + @"(C8 x) => throw null; } public interface I2<T> where T : I2<T> { abstract static T " + opName + @"(T x); } " + typeKeyword + @" C9 : I2<C9> { public static C9 operator " + op + @"(C9 x) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static C10 I2<C10>.operator " + op + @"(C10 x) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_BadIncDecRetType or (int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.operator +(C1)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>.operator " + op + "(C1)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.operator +(C2)'. 'C2.operator +(C2)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>.operator " + op + "(C2)", "C2.operator " + op + "(C2)").WithLocation(12, 10), // (14,24): error CS0558: User-defined operator 'C2.operator +(C2)' must be declared static and public // public C2 operator +(C2 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C2.operator " + op + "(C2)").WithLocation(14, 24), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.operator +(C3)'. 'C3.operator +(C3)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>.operator " + op + "(C3)", "C3.operator " + op + "(C3)").WithLocation(18, 10), // (20,24): error CS0558: User-defined operator 'C3.operator +(C3)' must be declared static and public // static C3 operator +(C3 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C3.operator " + op + "(C3)").WithLocation(20, 24), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.operator +(C4)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>.operator " + op + "(C4)").WithLocation(24, 10), // (26,24): error CS8930: Explicit implementation of a user-defined operator 'C4.operator +(C4)' must be declared static // C4 I1<C4>.operator +(C4 x) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("C4.operator " + op + "(C4)").WithLocation(26, 24), // (26,24): error CS0539: 'C4.operator +(C4)' in explicit interface declaration is not found among members of the interface that can be implemented // C4 I1<C4>.operator +(C4 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C4.operator " + op + "(C4)").WithLocation(26, 24), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.operator +(C5)'. 'C5.operator +(C5)' cannot implement 'I1<C5>.operator +(C5)' because it does not have the matching return type of 'C5'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>.operator " + op + "(C5)", "C5.operator " + op + "(C5)", "C5").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.operator +(C6)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>.operator " + op + "(C6)").WithLocation(36, 10), // (38,32): error CS0539: 'C6.operator +(C6)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C6>.operator + (C6 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C6.operator " + op + "(C6)").WithLocation(38, 32), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.operator +(C7)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>.operator " + op + "(C7)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.operator +(C8)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>.operator " + op + "(C8)").WithLocation(48, 10), // (50,22): error CS0539: 'C8.op_UnaryPlus(C8)' in explicit interface declaration is not found among members of the interface that can be implemented // static C8 I1<C8>.op_UnaryPlus(C8 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8)").WithLocation(50, 22), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_UnaryPlus(C9)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_UnaryPlus(C10)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10)").WithLocation(65, 11), // (67,33): error CS0539: 'C10.operator +(C10)' in explicit interface declaration is not found among members of the interface that can be implemented // static C10 I2<C10>.operator +(C10 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C10.operator " + op + "(C10)").WithLocation(67, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = BinaryOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public C2 operator " + op + @"(C2 x, int y) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static C3 operator " + op + @"(C3 x, int y) => throw null; } " + typeKeyword + @" C4 : I1<C4> { C4 I1<C4>.operator " + op + @"(C4 x, int y) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static int operator " + op + @" (C5 x, int y) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static int I1<C6>.operator " + op + @" (C6 x, int y) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static C7 " + opName + @"(C7 x, int y) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static C8 I1<C8>." + opName + @"(C8 x, int y) => throw null; } public interface I2<T> where T : I2<T> { abstract static T " + opName + @"(T x, int y); } " + typeKeyword + @" C9 : I2<C9> { public static C9 operator " + op + @"(C9 x, int y) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static C10 I2<C10>.operator " + op + @"(C10 x, int y) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.operator >>(C1, int)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>.operator " + op + "(C1, int)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.operator >>(C2, int)'. 'C2.operator >>(C2, int)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>.operator " + op + "(C2, int)", "C2.operator " + op + "(C2, int)").WithLocation(12, 10), // (14,24): error CS0558: User-defined operator 'C2.operator >>(C2, int)' must be declared static and public // public C2 operator >>(C2 x, int y) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C2.operator " + op + "(C2, int)").WithLocation(14, 24), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.operator >>(C3, int)'. 'C3.operator >>(C3, int)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>.operator " + op + "(C3, int)", "C3.operator " + op + "(C3, int)").WithLocation(18, 10), // (20,24): error CS0558: User-defined operator 'C3.operator >>(C3, int)' must be declared static and public // static C3 operator >>(C3 x, int y) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C3.operator " + op + "(C3, int)").WithLocation(20, 24), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.operator >>(C4, int)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>.operator " + op + "(C4, int)").WithLocation(24, 10), // (26,24): error CS8930: Explicit implementation of a user-defined operator 'C4.operator >>(C4, int)' must be declared static // C4 I1<C4>.operator >>(C4 x, int y) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("C4.operator " + op + "(C4, int)").WithLocation(26, 24), // (26,24): error CS0539: 'C4.operator >>(C4, int)' in explicit interface declaration is not found among members of the interface that can be implemented // C4 I1<C4>.operator >>(C4 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C4.operator " + op + "(C4, int)").WithLocation(26, 24), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.operator >>(C5, int)'. 'C5.operator >>(C5, int)' cannot implement 'I1<C5>.operator >>(C5, int)' because it does not have the matching return type of 'C5'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>.operator " + op + "(C5, int)", "C5.operator " + op + "(C5, int)", "C5").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.operator >>(C6, int)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>.operator " + op + "(C6, int)").WithLocation(36, 10), // (38,32): error CS0539: 'C6.operator >>(C6, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C6>.operator >> (C6 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C6.operator " + op + "(C6, int)").WithLocation(38, 32), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.operator >>(C7, int)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>.operator " + op + "(C7, int)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.operator >>(C8, int)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>.operator " + op + "(C8, int)").WithLocation(48, 10), // (50,22): error CS0539: 'C8.op_RightShift(C8, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static C8 I1<C8>.op_RightShift(C8 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8, int)").WithLocation(50, 22), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_RightShift(C9, int)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9, int)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_RightShift(C10, int)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10, int)").WithLocation(65, 11), // (67,33): error CS0539: 'C10.operator >>(C10, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static C10 I2<C10>.operator >>(C10 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C10.operator " + op + "(C10, int)").WithLocation(67, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_03([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } interface I2 : I1 {} interface I3 : I1 { I1 operator " + op + @"(I1 x) => default; } interface I4 : I1 { static I1 operator " + op + @"(I1 x) => default; } interface I5 : I1 { I1 I1.operator " + op + @"(I1 x) => default; } interface I6 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } interface I7 : I1 { abstract static I1 operator " + op + @"(I1 x); } public interface I11<T> where T : I11<T> { abstract static T operator " + op + @"(T x); } interface I8<T> : I11<T> where T : I8<T> { T operator " + op + @"(T x) => default; } interface I9<T> : I11<T> where T : I9<T> { static T operator " + op + @"(T x) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static T operator " + op + @"(T x); } interface I12<T> : I11<T> where T : I12<T> { static T I11<T>.operator " + op + @"(T x) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static T I11<T>.operator " + op + @"(T x); } interface I14 : I1 { abstract static I1 I1.operator " + op + @"(I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); ErrorCode badSignatureError = op.Length != 2 ? ErrorCode.ERR_BadUnaryOperatorSignature : ErrorCode.ERR_BadIncDecSignature; ErrorCode badAbstractSignatureError = op.Length != 2 ? ErrorCode.ERR_BadAbstractUnaryOperatorSignature : ErrorCode.ERR_BadAbstractIncDecSignature; compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (12,17): error CS0558: User-defined operator 'I3.operator +(I1)' must be declared static and public // I1 operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I3.operator " + op + "(I1)").WithLocation(12, 17), // (12,17): error CS0562: The parameter of a unary operator must be the containing type // I1 operator +(I1 x) => default; Diagnostic(badSignatureError, op).WithLocation(12, 17), // (17,24): error CS0562: The parameter of a unary operator must be the containing type // static I1 operator +(I1 x) => default; Diagnostic(badSignatureError, op).WithLocation(17, 24), // (22,20): error CS8930: Explicit implementation of a user-defined operator 'I5.operator +(I1)' must be declared static // I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("I5.operator " + op + "(I1)").WithLocation(22, 20), // (22,20): error CS0539: 'I5.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I5.operator " + op + "(I1)").WithLocation(22, 20), // (27,27): error CS0539: 'I6.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I6.operator " + op + "(I1)").WithLocation(27, 27), // (32,33): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // abstract static I1 operator +(I1 x); Diagnostic(badAbstractSignatureError, op).WithLocation(32, 33), // (42,16): error CS0558: User-defined operator 'I8<T>.operator +(T)' must be declared static and public // T operator +(T x) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I8<T>.operator " + op + "(T)").WithLocation(42, 16), // (42,16): error CS0562: The parameter of a unary operator must be the containing type // T operator +(T x) => default; Diagnostic(badSignatureError, op).WithLocation(42, 16), // (47,23): error CS0562: The parameter of a unary operator must be the containing type // static T operator +(T x) => default; Diagnostic(badSignatureError, op).WithLocation(47, 23), // (57,30): error CS0539: 'I12<T>.operator +(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static T I11<T>.operator +(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I12<T>.operator " + op + "(T)").WithLocation(57, 30), // (62,39): error CS0106: The modifier 'abstract' is not valid for this item // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(62, 39), // (62,39): error CS0501: 'I13<T>.operator +(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I13<T>.operator " + op + "(T)").WithLocation(62, 39), // (62,39): error CS0539: 'I13<T>.operator +(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I13<T>.operator " + op + "(T)").WithLocation(62, 39), // (67,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(67, 36), // (67,36): error CS0501: 'I14.operator +(I1)' must declare a body because it is not marked abstract, extern, or partial // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I14.operator " + op + "(I1)").WithLocation(67, 36), // (67,36): error CS0539: 'I14.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I14.operator " + op + "(I1)").WithLocation(67, 36) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_03([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } interface I2 : I1 {} interface I3 : I1 { I1 operator " + op + @"(I1 x, int y) => default; } interface I4 : I1 { static I1 operator " + op + @"(I1 x, int y) => default; } interface I5 : I1 { I1 I1.operator " + op + @"(I1 x, int y) => default; } interface I6 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } interface I7 : I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public interface I11<T> where T : I11<T> { abstract static T operator " + op + @"(T x, int y); } interface I8<T> : I11<T> where T : I8<T> { T operator " + op + @"(T x, int y) => default; } interface I9<T> : I11<T> where T : I9<T> { static T operator " + op + @"(T x, int y) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static T operator " + op + @"(T x, int y); } interface I12<T> : I11<T> where T : I12<T> { static T I11<T>.operator " + op + @"(T x, int y) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static T I11<T>.operator " + op + @"(T x, int y); } interface I14 : I1 { abstract static I1 I1.operator " + op + @"(I1 x, int y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); bool isShift = op == "<<" || op == ">>"; ErrorCode badSignatureError = isShift ? ErrorCode.ERR_BadShiftOperatorSignature : ErrorCode.ERR_BadBinaryOperatorSignature; ErrorCode badAbstractSignatureError = isShift ? ErrorCode.ERR_BadAbstractShiftOperatorSignature : ErrorCode.ERR_BadAbstractBinaryOperatorSignature; var expected = new[] { // (12,17): error CS0563: One of the parameters of a binary operator must be the containing type // I1 operator |(I1 x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(12, 17), // (17,24): error CS0563: One of the parameters of a binary operator must be the containing type // static I1 operator |(I1 x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(17, 24), // (22,20): error CS8930: Explicit implementation of a user-defined operator 'I5.operator |(I1, int)' must be declared static // I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("I5.operator " + op + "(I1, int)").WithLocation(22, 20), // (22,20): error CS0539: 'I5.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I5.operator " + op + "(I1, int)").WithLocation(22, 20), // (27,27): error CS0539: 'I6.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I6.operator " + op + "(I1, int)").WithLocation(27, 27), // (32,33): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // abstract static I1 operator |(I1 x, int y); Diagnostic(badAbstractSignatureError, op).WithLocation(32, 33), // (42,16): error CS0563: One of the parameters of a binary operator must be the containing type // T operator |(T x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(42, 16), // (47,23): error CS0563: One of the parameters of a binary operator must be the containing type // static T operator |(T x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(47, 23), // (57,30): error CS0539: 'I12<T>.operator |(T, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static T I11<T>.operator |(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I12<T>.operator " + op + "(T, int)").WithLocation(57, 30), // (62,39): error CS0106: The modifier 'abstract' is not valid for this item // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(62, 39), // (62,39): error CS0501: 'I13<T>.operator |(T, int)' must declare a body because it is not marked abstract, extern, or partial // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I13<T>.operator " + op + "(T, int)").WithLocation(62, 39), // (62,39): error CS0539: 'I13<T>.operator |(T, int)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I13<T>.operator " + op + "(T, int)").WithLocation(62, 39), // (67,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(67, 36), // (67,36): error CS0501: 'I14.operator |(I1, int)' must declare a body because it is not marked abstract, extern, or partial // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I14.operator " + op + "(I1, int)").WithLocation(67, 36), // (67,36): error CS0539: 'I14.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I14.operator " + op + "(I1, int)").WithLocation(67, 36) }; if (op is "==" or "!=") { expected = expected.Concat( new[] { // (12,17): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // I1 operator ==(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(12, 17), // (17,24): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static I1 operator ==(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(17, 24), // (42,16): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // T operator ==(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(42, 16), // (47,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static T operator ==(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(47, 23), } ).ToArray(); } else { expected = expected.Concat( new[] { // (12,17): error CS0558: User-defined operator 'I3.operator |(I1, int)' must be declared static and public // I1 operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I3.operator " + op + "(I1, int)").WithLocation(12, 17), // (42,16): error CS0558: User-defined operator 'I8<T>.operator |(T, int)' must be declared static and public // T operator |(T x, int y) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I8<T>.operator " + op + "(T, int)").WithLocation(42, 16) } ).ToArray(); } compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify(expected); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_04([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public interface I2<T> where T : I2<T> { abstract static T operator " + op + @"(T x); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static Test2 operator " + op + @"(Test2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15), // (14,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator +(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(14, 33), // (19,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator +(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(19, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public interface I2<T> where T : I2<T> { abstract static T operator " + op + @"(T x, int y); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static Test2 operator " + op + @"(Test2 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15), // (14,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator +(I1 x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(14, 33), // (19,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator +(T x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(19, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_05([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static Test1 operator " + op + @"(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (2,12): error CS8929: 'Test1.operator +(Test1)' cannot implement interface member 'I1<Test1>.operator +(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1)", "I1<Test1>.operator " + op + "(Test1)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (2,12): error CS8929: 'Test1.operator +(Test1)' cannot implement interface member 'I1<Test1>.operator +(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1)", "I1<Test1>.operator " + op + "(Test1)", "Test1").WithLocation(2, 12), // (9,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator +(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_05([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static Test1 operator " + op + @"(Test1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (2,12): error CS8929: 'Test1.operator >>(Test1, int)' cannot implement interface member 'I1<Test1>.operator >>(Test1, int)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1, int)", "I1<Test1>.operator " + op + "(Test1, int)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (2,12): error CS8929: 'Test1.operator >>(Test1, int)' cannot implement interface member 'I1<Test1>.operator >>(Test1, int)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1, int)", "I1<Test1>.operator " + op + "(Test1, int)", "Test1").WithLocation(2, 12), // (9,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator >>(T x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_06([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator +(I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_06([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator +(I1 x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_07([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } " + typeKeyword + @" C : I1<C> { public static C operator " + op + @"(C x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("C C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_07([CombinatorialValues("true", "false")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static bool operator " + op + @"(T x); } partial " + typeKeyword + @" C : I1<C> { public static bool operator " + op + @"(C x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1<T> where T : I1<T> { abstract static bool operator " + matchingOp + @"(T x); } partial " + typeKeyword + @" C { public static bool operator " + matchingOp + @"(C x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("System.Boolean C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_07([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() partial " + typeKeyword + @" C : I1<C> { public static C operator " + op + @"(C x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + matchingOp + @"(T x, int y); } partial " + typeKeyword + @" C { public static C operator " + matchingOp + @"(C x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.Equal(matchingOp is null ? 1 : 2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("C C." + opName + "(C x, System.Int32 y)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_08([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } " + typeKeyword + @" C : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal("default", node.ToString()); Assert.Equal("I1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("I1 C.I1." + opName + "(I1 x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("I1 C.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_08([CombinatorialValues("true", "false")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1 { abstract static bool operator " + op + @"(I1 x); } partial " + typeKeyword + @" C : I1 { static bool I1.operator " + op + @"(I1 x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1 { abstract static bool operator " + matchingOp + @"(I1 x); } partial " + typeKeyword + @" C { static bool I1.operator " + matchingOp + @"(I1 x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", node.ToString()); Assert.Equal("System.Boolean", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("System.Boolean C.I1." + opName + "(I1 x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers(opName).OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("System.Boolean C.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_08([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } partial " + typeKeyword + @" C : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator " + matchingOp + @"(I1 x, int y); } partial " + typeKeyword + @" C { static I1 I1.operator " + matchingOp + @"(I1 x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", node.ToString()); Assert.Equal("I1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("I1 C.I1." + opName + "(I1 x, System.Int32 y)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers(opName).OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(matchingOp is null ? 1 : 2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("I1 C.I1." + opName + "(I1 x, System.Int32 y)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_09([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public class C2 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_09([CombinatorialValues("true", "false")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public partial interface I1 { abstract static bool operator " + op + @"(I1 x); } public partial class C2 : I1 { static bool I1.operator " + op + @"(I1 x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1 { abstract static bool operator " + matchingOp + @"(I1 x); } public partial class C2 { static bool I1.operator " + matchingOp + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Boolean C2.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_09([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public partial interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public partial class C2 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator " + matchingOp + @"(I1 x, int y); } public partial class C2 { static I1 I1.operator " + matchingOp + @"(I1 x, int y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2.I1." + opName + "(I1 x, System.Int32 y)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_10([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x) cil managed { .override method class I1 I1::" + opName + @"(class I1) IL_0000: ldnull IL_0001: ret } .method public hidebysig static specialname class I1 " + opName + @" (class I1 x) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static specialname class I1 " + opName + @" (class I1 x) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Equal(MethodKind.UserDefinedOperator, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C1.I1." + opName + "(I1 x)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2." + opName + "(I1 x)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_10([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x, int32 y) cil managed { .override method class I1 I1::" + opName + @"(class I1, int32) IL_0000: ldnull IL_0001: ret } .method public hidebysig static specialname class I1 " + opName + @" (class I1 x, int32 y) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static specialname class I1 " + opName + @" (class I1 x, int32 y) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Equal(MethodKind.UserDefinedOperator, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C1.I1." + opName + "(I1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2." + opName + "(I1 x, System.Int32 y)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_11([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname virtual static class I1 " + opName + @" ( class I1 x ) cil managed { IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation2.VerifyEmitDiagnostics( // (4,27): error CS0539: 'C1.operator ~(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator ~(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C1.operator " + op + "(I1)").WithLocation(4, 27) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("I1 I1." + opName + "(I1 x)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_11([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation2.VerifyEmitDiagnostics( // (4,27): error CS0539: 'C1.operator <(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator <(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C1.operator " + op + "(I1, int)").WithLocation(4, 27) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("I1 I1." + opName + "(I1 x, System.Int32 y)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_12([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x ) cil managed { } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x) cil managed { .override method class I1 I1::" + opName + @"(class I1) IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.operator ~(I1)' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.operator " + op + "(I1)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_12([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x, int32 y) cil managed { .override method class I1 I1::" + opName + @"(class I1, int32) IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.operator /(I1, int)' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.operator " + op + "(I1, int)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_13([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public class C2 : C1, I1<C2> { } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); } public partial class C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var i1 = c2.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.False(c2M01.HasSpecialName); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.False(c1M01.HasRuntimeSpecialName); Assert.True(c1M01.HasSpecialName); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.True(c2M01.HasSpecialName); Assert.Equal("C2 C1." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1<C2>." + opName + "(C2, C1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C2 C1." + opName + @"(C2, C1)"" IL_0007: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_14([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static !T modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static C1 operator " + op + @"(C1 x) => default; } class C2 : I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("C1 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("C1 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("C1 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("C2 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""C1 C1." + opName + @"(C1)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_14([CombinatorialValues("true", "false")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static bool modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static bool operator " + op + @"(C1 x) => default; public static bool operator " + (op == "true" ? "false" : "true") + @"(C1 x) => default; } class C2 : I1<C2> { static bool I1<C2>.operator " + op + @"(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("System.Boolean modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("System.Boolean C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("System.Boolean C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("System.Boolean modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""bool C1." + opName + @"(C1)"" IL_0006: ret } "); } private static string MatchingBinaryOperator(string op) { return op switch { "<" => ">", ">" => "<", "<=" => ">=", ">=" => "<=", "==" => "!=", "!=" => "==", _ => null }; } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_14([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static !T modopt(I1`1) " + opName + @" ( !T x, int32 y ) cil managed { } } "; string matchingOp = MatchingBinaryOperator(op); string additionalMethods = ""; if (matchingOp is object) { additionalMethods = @" public static C1 operator " + matchingOp + @"(C1 x, int y) => default; "; } var source1 = @" #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() class C1 : I1<C1> { public static C1 operator " + op + @"(C1 x, int y) => default; " + additionalMethods + @" } class C2 : I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x, int y) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("C1 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("C1 C1." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("C1 C1." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("C2 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x, System.Int32 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1, int)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C1 C1." + opName + @"(C1, int)"" IL_0007: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_15([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public partial class C2 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M02 = c3.BaseType().GetMembers("I1." + opName).OfType<MethodSymbol>().Single(); Assert.Equal("I1 C2.I1." + opName + "(I1 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Fact] public void ImplementAbstractStaticUnaryTrueFalseOperator_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static bool operator true(I1 x); abstract static bool operator false(I1 x); } public partial class C2 : I1 { static bool I1.operator true(I1 x) => default; static bool I1.operator false(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("op_True").OfType<MethodSymbol>().Single(); var m02 = c3.Interfaces().Single().GetMembers("op_False").OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMembers("I1.op_True").OfType<MethodSymbol>().Single(); Assert.Equal("System.Boolean C2.I1.op_True(I1 x)", c2M01.ToTestDisplayString()); Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); var c2M02 = c3.BaseType().GetMembers("I1.op_False").OfType<MethodSymbol>().Single(); Assert.Equal("System.Boolean C2.I1.op_False(I1 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_15([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); abstract static T operator " + op + @"(T x, C2 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public partial class C2 : C1, I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x, C2 y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); abstract static T operator " + matchingOp + @"(T x, C2 y); } public partial class C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } public partial class C2 { static C2 I1<C2>.operator " + matchingOp + @"(C2 x, C2 y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().First(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C2 C1." + opName + "(C2 x, C1 y)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().ElementAt(1); var c2M02 = c3.BaseType().GetMembers("I1<C2>." + opName).OfType<MethodSymbol>().First(); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C2 y)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_16([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A new implicit implementation is properly considered. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 : I1<C2> { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public partial class C2 : C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); } public partial class C1 : I1<C2> { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } public partial class C2 : C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1<C2>." + opName + "(C2, C1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C2 C2." + opName + @"(C2, C1)"" IL_0007: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C2 C2." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C2 C3.I1<C2>." + opName + "(C2 x, C1 y)", c3M01.ToTestDisplayString()); Assert.Equal(m01, c3M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_18([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, U y) => default; "; var nonGeneric = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, int y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> { public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, U y) => default; public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>." + opName + "(C1<T, U> x, U y)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>." + opName + "(C1<T, U> x, U y)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_20([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // Same as ImplementAbstractStaticBinaryOperator_18 only implementation is explicit in source. var generic = @" static C1<T, U> I1<C1<T, U>, U>.operator " + op + @"(C1<T, U> x, U y) => default; "; var nonGeneric = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, int y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> : I1<C1<T, U>, U> { public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, int y) => default; static C1<T, U> I1<C1<T, U>, U>.operator " + matchingOp + @"(C1<T, U> x, U y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>.I1<C1<T, U>, U>." + opName + "(C1<T, U> x, U y)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_22([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implicit implementation is in an intermediate base. var generic = @" public static C11<T, U> operator " + op + @"(C11<T, U> x, C1<T, U> y) => default; "; var nonGeneric = @" public static C11<T, U> operator " + op + @"(C11<T, int> x, C1<T, U> y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T, U> : C1<T, U>, I1<C11<T, U>, C1<T, U>> { } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> { public static C11<T, U> operator " + matchingOp + @"(C11<T, U> x, C1<T, U> y) => default; public static C11<T, U> operator " + matchingOp + @"(C11<T, int> x, C1<T, U> y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C11<int, int>, I1<C11<int, int>, C1<int, int>> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "C11<T, U> C11<T, U>.I1<C11<T, U>, C1<T, U>>." + opName + "(C11<T, U> x, C1<T, U> y)" : "C11<T, U> C1<T, U>." + opName + "(C11<T, U> x, C1<T, U> y)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } class C1 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } class C2 : I1 { private static I1 I1.operator " + op + @"(I1 x) => default; } class C3 : I1 { protected static I1 I1.operator " + op + @"(I1 x) => default; } class C4 : I1 { internal static I1 I1.operator " + op + @"(I1 x) => default; } class C5 : I1 { protected internal static I1 I1.operator " + op + @"(I1 x) => default; } class C6 : I1 { private protected static I1 I1.operator " + op + @"(I1 x) => default; } class C7 : I1 { public static I1 I1.operator " + op + @"(I1 x) => default; } class C8 : I1 { static partial I1 I1.operator " + op + @"(I1 x) => default; } class C9 : I1 { async static I1 I1.operator " + op + @"(I1 x) => default; } class C10 : I1 { unsafe static I1 I1.operator " + op + @"(I1 x) => default; } class C11 : I1 { static readonly I1 I1.operator " + op + @"(I1 x) => default; } class C12 : I1 { extern static I1 I1.operator " + op + @"(I1 x); } class C13 : I1 { abstract static I1 I1.operator " + op + @"(I1 x) => default; } class C14 : I1 { virtual static I1 I1.operator " + op + @"(I1 x) => default; } class C15 : I1 { sealed static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.WRN_ExternMethodNoImplementation or (int)ErrorCode.ERR_OpTFRetType or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (16,35): error CS0106: The modifier 'private' is not valid for this item // private static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private").WithLocation(16, 35), // (22,37): error CS0106: The modifier 'protected' is not valid for this item // protected static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected").WithLocation(22, 37), // (28,36): error CS0106: The modifier 'internal' is not valid for this item // internal static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("internal").WithLocation(28, 36), // (34,46): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected internal").WithLocation(34, 46), // (40,45): error CS0106: The modifier 'private protected' is not valid for this item // private protected static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private protected").WithLocation(40, 45), // (46,34): error CS0106: The modifier 'public' is not valid for this item // public static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("public").WithLocation(46, 34), // (52,12): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // static partial I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(52, 12), // (58,33): error CS0106: The modifier 'async' is not valid for this item // async static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("async").WithLocation(58, 33), // (70,36): error CS0106: The modifier 'readonly' is not valid for this item // static readonly I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("readonly").WithLocation(70, 36), // (82,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(82, 36), // (88,35): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("virtual").WithLocation(88, 35), // (94,34): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("sealed").WithLocation(94, 34) ); } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } struct C1 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C2 : I1 { private static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C3 : I1 { protected static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C4 : I1 { internal static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C5 : I1 { protected internal static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C6 : I1 { private protected static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C7 : I1 { public static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C8 : I1 { static partial I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C9 : I1 { async static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C10 : I1 { unsafe static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C11 : I1 { static readonly I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C12 : I1 { extern static I1 I1.operator " + op + @"(I1 x, int y); } struct C13 : I1 { abstract static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C14 : I1 { virtual static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C15 : I1 { sealed static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.WRN_ExternMethodNoImplementation or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (16,35): error CS0106: The modifier 'private' is not valid for this item // private static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private").WithLocation(16, 35), // (22,37): error CS0106: The modifier 'protected' is not valid for this item // protected static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected").WithLocation(22, 37), // (28,36): error CS0106: The modifier 'internal' is not valid for this item // internal static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("internal").WithLocation(28, 36), // (34,46): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected internal").WithLocation(34, 46), // (40,45): error CS0106: The modifier 'private protected' is not valid for this item // private protected static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private protected").WithLocation(40, 45), // (46,34): error CS0106: The modifier 'public' is not valid for this item // public static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("public").WithLocation(46, 34), // (52,12): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // static partial I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(52, 12), // (58,33): error CS0106: The modifier 'async' is not valid for this item // async static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("async").WithLocation(58, 33), // (70,36): error CS0106: The modifier 'readonly' is not valid for this item // static readonly I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("readonly").WithLocation(70, 36), // (82,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(82, 36), // (88,35): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("virtual").WithLocation(88, 35), // (94,34): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("sealed").WithLocation(94, 34) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1<T> where T : struct { abstract static I1<T> operator " + op + @"(I1<T> x); } class C1 { static I1<int> I1<int>.operator " + op + @"(I1<int> x) => default; } class C2 : I1<C2> { static I1<C2> I1<C2>.operator " + op + @"(I1<C2> x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OpTFRetType or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (9,20): error CS0540: 'C1.I1<int>.operator -(I1<int>)': containing type does not implement interface 'I1<int>' // static I1<int> I1<int>.operator -(I1<int> x) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<int>").WithArguments("C1.I1<int>.operator " + op + "(I1<int>)", "I1<int>").WithLocation(9, 20), // (12,7): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // class C2 : I1<C2> Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 7), // (14,19): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 19), // (14,35): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, op).WithArguments("I1<T>", "T", "C2").WithLocation(14, 35), // (14,44): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("I1<T>", "T", "C2").WithLocation(14, 44 + op.Length - 1) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1<T> where T : class { abstract static I1<T> operator " + op + @"(I1<T> x, int y); } struct C1 { static I1<string> I1<string>.operator " + op + @"(I1<string> x, int y) => default; } struct C2 : I1<C2> { static I1<C2> I1<C2>.operator " + op + @"(I1<C2> x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (9,23): error CS0540: 'C1.I1<string>.operator %(I1<string>, int)': containing type does not implement interface 'I1<string>' // static I1<string> I1<string>.operator %(I1<string> x, int y) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<string>").WithArguments("C1.I1<string>.operator " + op + "(I1<string>, int)", "I1<string>").WithLocation(9, 23), // (12,8): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // struct C2 : I1<C2> Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 8), // (14,19): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 19), // (14,35): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, op).WithArguments("I1<T>", "T", "C2").WithLocation(14, 35), // (14,44): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "x").WithArguments("I1<T>", "T", "C2").WithLocation(14, 44 + op.Length - 1) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public int M01 { get; set; } } " + typeKeyword + @" C3 : I1 { static int M01 { get; set; } } " + typeKeyword + @" C4 : I1 { int I1.M01 { get; set; } } " + typeKeyword + @" C5 : I1 { public static long M01 { get; set; } } " + typeKeyword + @" C6 : I1 { static long I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,12): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 12), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'int'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,20): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static long I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 20) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract int M01 { get; set; } } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static int M01 { get; set; } } " + typeKeyword + @" C3 : I1 { int M01 { get; set; } } " + typeKeyword + @" C4 : I1 { static int I1.M01 { get; set; } } " + typeKeyword + @" C5 : I1 { public long M01 { get; set; } } " + typeKeyword + @" C6 : I1 { long I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,19): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 19), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'int'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,13): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // long I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 13) ); } [Fact] public void ImplementAbstractStaticProperty_03() { var source1 = @" public interface I1 { abstract static int M01 { get; set; } } interface I2 : I1 {} interface I3 : I1 { public virtual int M01 { get => 0; set{} } } interface I4 : I1 { static int M01 { get; set; } } interface I5 : I1 { int I1.M01 { get => 0; set{} } } interface I6 : I1 { static int I1.M01 { get => 0; set{} } } interface I7 : I1 { abstract static int M01 { get; set; } } interface I8 : I1 { abstract static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (12,24): warning CS0108: 'I3.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // public virtual int M01 { get => 0; set{} } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01", "I1.M01").WithLocation(12, 24), // (17,16): warning CS0108: 'I4.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // static int M01 { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01", "I1.M01").WithLocation(17, 16), // (22,12): error CS0539: 'I5.M01' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01").WithLocation(22, 12), // (27,19): error CS0106: The modifier 'static' is not valid for this item // static int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 19), // (27,19): error CS0539: 'I6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01").WithLocation(27, 19), // (32,25): warning CS0108: 'I7.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01", "I1.M01").WithLocation(32, 25), // (37,28): error CS0106: The modifier 'static' is not valid for this item // abstract static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 28), // (37,28): error CS0539: 'I8.M01' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01").WithLocation(37, 28) ); foreach (var m01 in compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers()) { Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } abstract static int M02 { get; set; } } "; var source2 = typeKeyword + @" Test: I1 { static int I1.M01 { get; set; } public static int M02 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,19): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 19) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (4,19): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 19), // (10,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 25), // (11,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int M02 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 25) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } "; var source2 = typeKeyword + @" Test1: I1 { public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.set' cannot implement interface member 'I1.M01.set' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.set", "I1.M01.set", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.get' cannot implement interface member 'I1.M01.get' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.get", "I1.M01.get", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.set' cannot implement interface member 'I1.M01.set' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.set", "I1.M01.set", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.get' cannot implement interface member 'I1.M01.get' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.get", "I1.M01.get", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12), // (9,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(9, 31), // (9,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(9, 36) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } "; var source2 = typeKeyword + @" Test1: I1 { static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,19): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 19) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,19): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 19), // (9,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(9, 31), // (9,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(9, 36) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C : I1 { public static int M01 { get => 0; set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.False(cM01Get.HasRuntimeSpecialName); Assert.True(cM01Get.HasSpecialName); Assert.Equal("System.Int32 C.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.False(cM01Set.HasRuntimeSpecialName); Assert.True(cM01Set.HasSpecialName); Assert.Equal("void C.M01.set", cM01Set.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticReadonlyProperty_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; } } " + typeKeyword + @" C : I1 { public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Null(m01.SetMethod); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C.M01.set", cM01Set.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C : I1 { static int I1.M01 { get => 0; set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.I1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.False(cM01Get.HasRuntimeSpecialName); Assert.True(cM01Get.HasSpecialName); Assert.Equal("System.Int32 C.I1.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.False(cM01Set.HasRuntimeSpecialName); Assert.True(cM01Set.HasSpecialName); Assert.Equal("void C.I1.M01.set", cM01Set.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<PropertySymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var cM01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.I1.M01 { get; set; }", cM01.ToTestDisplayString()); Assert.Same(cM01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(cM01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, cM01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, cM01.SetMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig specialname static int32 I1.get_M01 () cil managed { .override method int32 I1::get_M01() IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static void I1.set_M01 ( int32 'value' ) cil managed { .override method void I1::set_M01(int32) IL_0000: ret } .property instance int32 I1.M01() { .get int32 C1::I1.get_M01() .set void C1::I1.set_M01(int32) } .method public hidebysig specialname static int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname static void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 C1::get_M01() .set void C1::set_M01(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig specialname static int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname static void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 C2::get_M01() .set void C2::set_M01(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = (PropertySymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1.I1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.Same(c1M01.GetMethod, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c2.FindImplementationForInterfaceMember(m01.SetMethod)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c4.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c4.FindImplementationForInterfaceMember(m01.SetMethod)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (PropertySymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.Same(c2M01.GetMethod, c5.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c2M01.SetMethod, c5.FindImplementationForInterfaceMember(m01.SetMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticProperty_11() { // Ignore invalid metadata (non-abstract static virtual method). scenario1(); scenario2(); scenario3(); void scenario1() { var ilSource = @" .class interface public auto ansi abstract I1 { .method private hidebysig specialname static virtual int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static virtual void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation2.VerifyEmitDiagnostics( // (4,18): error CS0539: 'C1.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01").WithLocation(4, 18) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c.FindImplementationForInterfaceMember(m01)); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); } } void scenario2() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method private hidebysig specialname static virtual void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source2 = @" public class C1 : I1 { static int I1.M01 { get; } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation2, sourceSymbolValidator: validate2, symbolValidator: validate2, verify: Verification.Skipped).VerifyDiagnostics(); void validate2(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.I1.M01 { get; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.I1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(cM01.SetMethod); Assert.Null(c.FindImplementationForInterfaceMember(m01Set)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation4.VerifyDiagnostics( // (4,29): error CS0550: 'C1.I1.M01.set' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("C1.I1.M01.set", "I1.M01").WithLocation(4, 29) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static int M01 { get; } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation5, sourceSymbolValidator: validate5, symbolValidator: validate5, verify: Verification.Skipped).VerifyDiagnostics(); void validate5(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } } var source6 = @" public class C1 : I1 { public static int M01 { set{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.get' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.get").WithLocation(2, 19) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); var source7 = @" public class C1 : I1 { static int I1.M01 { set{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.get' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.get").WithLocation(2, 19), // (4,18): error CS0551: Explicit interface implementation 'C1.I1.M01' is missing accessor 'I1.M01.get' // static int I1.M01 { set{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M01").WithArguments("C1.I1.M01", "I1.M01.get").WithLocation(4, 18), // (4,24): error CS0550: 'C1.I1.M01.set' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { set{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("C1.I1.M01.set", "I1.M01").WithLocation(4, 24) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); } void scenario3() { var ilSource = @" .class interface public auto ansi abstract I1 { .method private hidebysig specialname static virtual int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source2 = @" public class C1 : I1 { static int I1.M01 { set{} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation2, sourceSymbolValidator: validate2, symbolValidator: validate2, verify: Verification.Skipped).VerifyDiagnostics(); void validate2(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.I1.M01 { set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.I1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(cM01.GetMethod); Assert.Null(c.FindImplementationForInterfaceMember(m01Get)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation4.VerifyDiagnostics( // (4,24): error CS0550: 'C1.I1.M01.get' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C1.I1.M01.get", "I1.M01").WithLocation(4, 24) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.SetMethod, c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static int M01 { set{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation5, sourceSymbolValidator: validate5, symbolValidator: validate5, verify: Verification.Skipped).VerifyDiagnostics(); void validate5(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } var source6 = @" public class C1 : I1 { public static int M01 { get; } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.set' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.set").WithLocation(2, 19) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); var source7 = @" public class C1 : I1 { static int I1.M01 { get; } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.set' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.set").WithLocation(2, 19), // (4,18): error CS0551: Explicit interface implementation 'C1.I1.M01' is missing accessor 'I1.M01.set' // static int I1.M01 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M01").WithArguments("C1.I1.M01", "I1.M01.set").WithLocation(4, 18), // (4,24): error CS0550: 'C1.I1.M01.get' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C1.I1.M01.get", "I1.M01").WithLocation(4, 24) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig specialname static int32 I1.get_M01 () cil managed { .override method int32 I1::get_M01() IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static void I1.set_M01 ( int32 'value' ) cil managed { .override method void I1::set_M01(int32) IL_0000: ret } .property instance int32 I1.M01() { .get int32 I2::I1.get_M01() .set void I2::I1.set_M01(int32) } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.SetMethod)); var i2M01 = i2.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, i2M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, i2M01.SetMethod.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticProperty_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static int M01 { get; set; } } class C1 { public static int M01 { get; set; } } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Get = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.GetMethod); var c2M01Set = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.SetMethod); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Get.MethodKind); Assert.False(c2M01Get.HasRuntimeSpecialName); Assert.False(c2M01Get.HasSpecialName); Assert.Equal("System.Int32 C2.I1.get_M01()", c2M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c2M01Get.ExplicitInterfaceImplementations.Single()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Set.MethodKind); Assert.False(c2M01Set.HasRuntimeSpecialName); Assert.False(c2M01Set.HasSpecialName); Assert.Equal("void C2.I1.set_M01(System.Int32 value)", c2M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c2M01Set.ExplicitInterfaceImplementations.Single()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c2M01); var c1M01 = module.GlobalNamespace.GetMember<PropertySymbol>("C1.M01"); var c1M01Get = c1M01.GetMethod; var c1M01Set = c1M01.SetMethod; Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c1M01Get.MethodKind); Assert.False(c1M01Get.HasRuntimeSpecialName); Assert.True(c1M01Get.HasSpecialName); Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c1M01Set.MethodKind); Assert.False(c1M01Set.HasRuntimeSpecialName); Assert.True(c1M01Set.HasSpecialName); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); } else { Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.PropertyGet, c2M01Get.MethodKind); Assert.False(c2M01Get.HasRuntimeSpecialName); Assert.True(c2M01Get.HasSpecialName); Assert.Same(c2M01.GetMethod, c2M01Get); Assert.Empty(c2M01Get.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.PropertySet, c2M01Set.MethodKind); Assert.False(c2M01Set.HasRuntimeSpecialName); Assert.True(c2M01Set.HasSpecialName); Assert.Same(c2M01.SetMethod, c2M01Set); Assert.Empty(c2M01Set.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.get_M01", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C1.M01.get"" IL_0005: ret } "); verifier.VerifyIL("C2.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.set"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticProperty_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void modopt(I1) set_M01 ( int32 modopt(I1) 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void modopt(I1) I1::set_M01(int32 modopt(I1)) } } .class interface public auto ansi abstract I2 { .method public hidebysig specialname abstract virtual static int32 modopt(I2) get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 modopt(I2) 'value' ) cil managed { } .property int32 modopt(I2) M01() { .get int32 modopt(I2) I2::get_M01() .set void I2::set_M01(int32 modopt(I2)) } } "; var source1 = @" class C1 : I1 { public static int M01 { get; set; } } class C2 : I1 { static int I1.M01 { get; set; } } class C3 : I2 { static int I2.M01 { get; set; } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = (PropertySymbol)c1.FindImplementationForInterfaceMember(m01); var c1M01Get = c1M01.GetMethod; var c1M01Set = c1M01.SetMethod; Assert.Equal("System.Int32 C1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Equal(MethodKind.PropertyGet, c1M01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", c1M01Get.ToTestDisplayString()); Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Same(c1M01Get, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Equal(MethodKind.PropertySet, c1M01Set.MethodKind); Assert.Equal("void C1.M01.set", c1M01Set.ToTestDisplayString()); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Same(m01.GetMethod, c1M01Get.ExplicitInterfaceImplementations.Single()); c1M01Set = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Set.MethodKind); Assert.Equal("void modopt(I1) C1.I1.set_M01(System.Int32 modopt(I1) value)", c1M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c1M01Set.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); } else { Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); Assert.Same(c1M01Set, c1.FindImplementationForInterfaceMember(m01.SetMethod)); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Get = c2M01.GetMethod; var c2M01Set = c2M01.SetMethod; Assert.Equal("System.Int32 C2.I1.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c2M01Get.MethodKind); Assert.Equal("System.Int32 C2.I1.M01.get", c2M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c2M01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Get, c2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c2M01Set.MethodKind); Assert.Equal("void modopt(I1) C2.I1.M01.set", c2M01Set.ToTestDisplayString()); Assert.Equal("System.Int32 modopt(I1) value", c2M01Set.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.SetMethod, c2M01Set.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Set, c2.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(c2M01, c2.GetMembers().OfType<PropertySymbol>().Single()); Assert.Equal(2, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var c3 = module.GlobalNamespace.GetTypeMember("C3"); m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c3M01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); var c3M01Get = c3M01.GetMethod; var c3M01Set = c3M01.SetMethod; Assert.Equal("System.Int32 modopt(I2) C3.I2.M01 { get; set; }", c3M01.ToTestDisplayString()); Assert.True(c3M01.IsStatic); Assert.False(c3M01.IsAbstract); Assert.False(c3M01.IsVirtual); Assert.Same(m01, c3M01.ExplicitInterfaceImplementations.Single()); Assert.True(c3M01Get.IsStatic); Assert.False(c3M01Get.IsAbstract); Assert.False(c3M01Get.IsVirtual); Assert.False(c3M01Get.IsMetadataVirtual()); Assert.False(c3M01Get.IsMetadataFinal); Assert.False(c3M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c3M01Get.MethodKind); Assert.Equal("System.Int32 modopt(I2) C3.I2.M01.get", c3M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c3M01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(c3M01Get, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.True(c3M01Set.IsStatic); Assert.False(c3M01Set.IsAbstract); Assert.False(c3M01Set.IsVirtual); Assert.False(c3M01Set.IsMetadataVirtual()); Assert.False(c3M01Set.IsMetadataFinal); Assert.False(c3M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c3M01Set.MethodKind); Assert.Equal("void C3.I2.M01.set", c3M01Set.ToTestDisplayString()); Assert.Equal("System.Int32 modopt(I2) value", c3M01Set.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.SetMethod, c3M01Set.ExplicitInterfaceImplementations.Single()); Assert.Same(c3M01Set, c3.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(c3M01, c3.GetMembers().OfType<PropertySymbol>().Single()); Assert.Equal(2, c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); } verifier.VerifyIL("C1.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.set"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStatiProperty_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static int M01 { get; set; } abstract static int M02 { get; set; } } public class C1 { public static int M01 { get; set; } } public class C2 : C1, I1 { static int I1.M02 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<PropertySymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<PropertySymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<PropertySymbol>("M01"); Assert.Equal("System.Int32 C1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); var c1M01Get = c1M01.GetMethod; Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); var c1M01Set = c1M01.SetMethod; Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01Get = c3.FindImplementationForInterfaceMember(m01.GetMethod); Assert.Equal("System.Int32 C2.I1.get_M01()", c2M01Get.ToTestDisplayString()); var c2M01Set = c3.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal("void C2.I1.set_M01(System.Int32 value)", c2M01Set.ToTestDisplayString()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c3.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<PropertySymbol>().Single(); var c2M02 = c3.BaseType().GetMember<PropertySymbol>("I1.M02"); Assert.Equal("System.Int32 C2.I1.M02 { get; set; }", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c2M02.GetMethod, c3.FindImplementationForInterfaceMember(m02.GetMethod)); Assert.Same(c2M02.SetMethod, c3.FindImplementationForInterfaceMember(m02.SetMethod)); } } [Fact] public void ImplementAbstractStaticProperty_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1 : I1 { public static int M01 { get; set; } } public class C2 : C1 { new public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.get_M01", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C2.M01.get"" IL_0005: ret } "); verifier.VerifyIL("C3.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.set"" IL_0006: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c2M01 = c3.BaseType().GetMember<PropertySymbol>("M01"); var c2M01Get = c2M01.GetMethod; var c2M01Set = c2M01.SetMethod; Assert.Equal("System.Int32 C2.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.Empty(c2M01Get.ExplicitInterfaceImplementations); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); Assert.Empty(c2M01Set.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); // Forwarding methods for accessors aren't tied to a property Assert.Null(c3M01); var c3M01Get = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.GetMethod); Assert.Equal("System.Int32 C3.I1.get_M01()", c3M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c3M01Get.ExplicitInterfaceImplementations.Single()); var c3M01Set = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal("void C3.I1.set_M01(System.Int32 value)", c3M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c3M01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c2M01Get, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c2M01Set, c3.FindImplementationForInterfaceMember(m01.SetMethod)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_19(bool genericFirst) { // An "ambiguity" in implicit/explicit implementation declared in generic base class. var generic = @" public static T M01 { get; set; } "; var nonGeneric = @" static int I1.M01 { get; set; } "; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<PropertySymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1<T>.I1.M01 { get; set; }", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_20(bool genericFirst) { // Same as ImplementAbstractStaticProperty_19 only interface is generic too. var generic = @" static T I1<T>.M01 { get; set; } "; var nonGeneric = @" public static int M01 { get; set; } "; var source1 = @" public interface I1<T> { abstract static T M01 { get; set; } } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<PropertySymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("T C1<T>.I1<T>.M01 { get; set; }", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public event System.Action M01; } " + typeKeyword + @" C3 : I1 { static event System.Action M01; } " + typeKeyword + @" C4 : I1 { event System.Action I1.M01 { add{} remove{}} } " + typeKeyword + @" C5 : I1 { public static event System.Action<int> M01; } " + typeKeyword + @" C6 : I1 { static event System.Action<int> I1.M01 { add{} remove{}} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,28): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.M01 { add{} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 28), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'Action'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "System.Action").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,40): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action<int> I1.M01 { add{} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 40) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract event System.Action M01; } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static event System.Action M01; } " + typeKeyword + @" C3 : I1 { event System.Action M01; } " + typeKeyword + @" C4 : I1 { static event System.Action I1.M01 { add{} remove{} } } " + typeKeyword + @" C5 : I1 { public event System.Action<int> M01; } " + typeKeyword + @" C6 : I1 { event System.Action<int> I1.M01 { add{} remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,35): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 35), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'Action'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "System.Action").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,33): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action<int> I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 33) ); } [Fact] public void ImplementAbstractStaticEvent_03() { var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract static event System.Action M01; } interface I2 : I1 {} interface I3 : I1 { public virtual event System.Action M01 { add{} remove{} } } interface I4 : I1 { static event System.Action M01; } interface I5 : I1 { event System.Action I1.M01 { add{} remove{} } } interface I6 : I1 { static event System.Action I1.M01 { add{} remove{} } } interface I7 : I1 { abstract static event System.Action M01; } interface I8 : I1 { abstract static event System.Action I1.M01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (12,40): warning CS0108: 'I3.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // public virtual event System.Action M01 { add{} remove{} } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01", "I1.M01").WithLocation(12, 40), // (17,32): warning CS0108: 'I4.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // static event System.Action M01; Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01", "I1.M01").WithLocation(17, 32), // (22,28): error CS0539: 'I5.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01").WithLocation(22, 28), // (27,35): error CS0106: The modifier 'static' is not valid for this item // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 35), // (27,35): error CS0539: 'I6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01").WithLocation(27, 35), // (32,41): warning CS0108: 'I7.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // abstract static event System.Action M01; Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01", "I1.M01").WithLocation(32, 41), // (37,44): error CS0106: The modifier 'static' is not valid for this item // abstract static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 44), // (37,44): error CS0539: 'I8.M01' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static event System.Action I1.M01; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01").WithLocation(37, 44) ); foreach (var m01 in compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers()) { Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; abstract static event System.Action M02; } "; var source2 = typeKeyword + @" Test: I1 { static event System.Action I1.M01 { add{} remove => throw null; } public static event System.Action M02; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,35): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static event System.Action I1.M01 { add{} remove => throw null; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 35), // (5,39): warning CS0067: The event 'Test.M02' is never used // public static event System.Action M02; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "M02").WithArguments("Test.M02").WithLocation(5, 39) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (4,35): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static event System.Action I1.M01 { add{} remove => throw null; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 35), // (5,39): warning CS0067: The event 'Test.M02' is never used // public static event System.Action M02; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "M02").WithArguments("Test.M02").WithLocation(5, 39), // (10,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 41), // (11,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action M02; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } "; var source2 = typeKeyword + @" Test1: I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.remove' cannot implement interface member 'I1.M01.remove' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.remove", "I1.M01.remove", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.add' cannot implement interface member 'I1.M01.add' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.add", "I1.M01.add", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.remove' cannot implement interface member 'I1.M01.remove' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.remove", "I1.M01.remove", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.add' cannot implement interface member 'I1.M01.add' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.add", "I1.M01.add", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12), // (9,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } "; var source2 = typeKeyword + @" Test1: I1 { static event System.Action I1.M01 { add => throw null; remove => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static event System.Action I1.M01 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 35) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static event System.Action I1.M01 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 35), // (9,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C : I1 { public static event System.Action M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; var m01Remove = m01.RemoveMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.False(cM01Add.HasRuntimeSpecialName); Assert.True(cM01Add.HasSpecialName); Assert.Equal("void C.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.False(cM01Remove.HasRuntimeSpecialName); Assert.True(cM01Remove.HasSpecialName); Assert.Equal("void C.M01.remove", cM01Remove.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Add.ExplicitInterfaceImplementations); Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C : I1 { static event System.Action I1.M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; var m01Remove = m01.RemoveMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C.I1.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.False(cM01Add.HasRuntimeSpecialName); Assert.True(cM01Add.HasSpecialName); Assert.Equal("void C.I1.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.False(cM01Remove.HasRuntimeSpecialName); Assert.True(cM01Remove.HasSpecialName); Assert.Equal("void C.I1.M01.remove", cM01Remove.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static event System.Action M01; } public class C1 { public static event System.Action M01 { add => throw null; remove {} } } public class C2 : C1, I1 { static event System.Action I1.M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<EventSymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var cM01 = (EventSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C2.I1.M01", cM01.ToTestDisplayString()); Assert.Same(cM01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(cM01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, cM01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, cM01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig specialname static void I1.add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::add_M01(class [mscorlib]System.Action) IL_0000: ret } .method private hidebysig specialname static void I1.remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::remove_M01(class [mscorlib]System.Action) IL_0000: ret } .event [mscorlib]System.Action I1.M01 { .addon void C1::I1.add_M01(class [mscorlib]System.Action) .removeon void C1::I1.remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void C1::add_M01(class [mscorlib]System.Action) .removeon void C1::remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig specialname static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void C2::add_M01(class [mscorlib]System.Action) .removeon void C2::remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c1M01 = (EventSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C1.I1.M01", c1M01.ToTestDisplayString()); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c2.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c4.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c4.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (EventSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C2.M01", c2M01.ToTestDisplayString()); Assert.Same(c2M01.AddMethod, c5.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c2M01.RemoveMethod, c5.FindImplementationForInterfaceMember(m01.RemoveMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticEvent_11() { // Ignore invalid metadata (non-abstract static virtual method). scenario1(); scenario2(); scenario3(); void scenario1() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname static virtual void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static virtual void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation2.VerifyEmitDiagnostics( // (4,34): error CS0539: 'C1.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c.FindImplementationForInterfaceMember(m01)); Assert.Null(c.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c.FindImplementationForInterfaceMember(m01.RemoveMethod)); } } void scenario2() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname static virtual void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { add {} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation2.VerifyDiagnostics( // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C1.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.Equal("void C1.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.Equal("void C1.M01.remove", cM01Remove.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.RemoveMethod)); if (module is PEModuleSymbol) { Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01Add.ExplicitInterfaceImplementations); } Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation4.VerifyDiagnostics( // (4,46): error CS0550: 'C1.I1.M01.remove' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "remove").WithArguments("C1.I1.M01.remove", "I1.M01").WithLocation(4, 46) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static event System.Action M01 { add{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation5.VerifyDiagnostics( // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { add{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation5.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source6 = @" public class C1 : I1 { public static event System.Action M01 { remove{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.add' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.add").WithLocation(2, 19), // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source7 = @" public class C1 : I1 { static event System.Action I1.M01 { remove{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.add' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.add").WithLocation(2, 19), // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34), // (4,40): error CS0550: 'C1.I1.M01.remove' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "remove").WithArguments("C1.I1.M01.remove", "I1.M01").WithLocation(4, 40) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } void scenario3() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname static virtual void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { remove {} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation2.VerifyDiagnostics( // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var m01Remove = m01.RemoveMethod; Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C1.M01", cM01.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.Equal("void C1.M01.remove", cM01Remove.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.Equal("void C1.M01.add", cM01Add.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.AddMethod)); if (module is PEModuleSymbol) { Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Add.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation4.VerifyDiagnostics( // (4,40): error CS0550: 'C1.I1.M01.add' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "add").WithArguments("C1.I1.M01.add", "I1.M01").WithLocation(4, 40) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static event System.Action M01 { remove{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation5.VerifyDiagnostics( // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation5.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); var source6 = @" public class C1 : I1 { public static event System.Action M01 { add{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.remove' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.remove").WithLocation(2, 19), // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source7 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.remove' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.remove").WithLocation(2, 19), // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34), // (4,40): error CS0550: 'C1.I1.M01.add' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "add").WithArguments("C1.I1.M01.add", "I1.M01").WithLocation(4, 40) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig specialname static void I1.add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::add_M01(class [mscorlib]System.Action) IL_0000: ret } .method private hidebysig specialname static void I1.remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::remove_M01(class [mscorlib]System.Action) IL_0000: ret } .event [mscorlib]System.Action I1.M01 { .addon void I2::I1.add_M01(class [mscorlib]System.Action) .removeon void I2::I1.remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.RemoveMethod)); var i2M01 = i2.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, i2M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, i2M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticEvent_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static event System.Action M01; } class C1 { public static event System.Action M01 { add => throw null; remove{} } } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Add = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.AddMethod); var c2M01Remove = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Add.MethodKind); Assert.False(c2M01Add.HasRuntimeSpecialName); Assert.False(c2M01Add.HasSpecialName); Assert.Equal("void C2.I1.add_M01(System.Action value)", c2M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c2M01Add.ExplicitInterfaceImplementations.Single()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Remove.MethodKind); Assert.False(c2M01Remove.HasRuntimeSpecialName); Assert.False(c2M01Remove.HasSpecialName); Assert.Equal("void C2.I1.remove_M01(System.Action value)", c2M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c2M01Remove.ExplicitInterfaceImplementations.Single()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c2M01); var c1M01 = module.GlobalNamespace.GetMember<EventSymbol>("C1.M01"); var c1M01Add = c1M01.AddMethod; var c1M01Remove = c1M01.RemoveMethod; Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c1M01Add.MethodKind); Assert.False(c1M01Add.HasRuntimeSpecialName); Assert.True(c1M01Add.HasSpecialName); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c1M01Remove.MethodKind); Assert.False(c1M01Remove.HasRuntimeSpecialName); Assert.True(c1M01Remove.HasSpecialName); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); } else { Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Equal("event System.Action C1.M01", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.EventAdd, c2M01Add.MethodKind); Assert.False(c2M01Add.HasRuntimeSpecialName); Assert.True(c2M01Add.HasSpecialName); Assert.Same(c2M01.AddMethod, c2M01Add); Assert.Empty(c2M01Add.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.EventRemove, c2M01Remove.MethodKind); Assert.False(c2M01Remove.HasRuntimeSpecialName); Assert.True(c2M01Remove.HasSpecialName); Assert.Same(c2M01.RemoveMethod, c2M01Remove); Assert.Empty(c2M01Remove.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C2.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.remove"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticEvent_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action`1<int32 modopt(I1)> 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action`1<int32 modopt(I1)> 'value' ) cil managed { } .event class [mscorlib]System.Action`1<int32 modopt(I1)> M01 { .addon void I1::add_M01(class [mscorlib]System.Action`1<int32 modopt(I1)>) .removeon void I1::remove_M01(class [mscorlib]System.Action`1<int32 modopt(I1)>) } } .class interface public auto ansi abstract I2 { .method public hidebysig specialname abstract virtual static void add_M02 ( class [mscorlib]System.Action modopt(I1) 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void modopt(I2) remove_M02 ( class [mscorlib]System.Action 'value' ) cil managed { } .event class [mscorlib]System.Action M02 { .addon void I2::add_M02(class [mscorlib]System.Action modopt(I1)) .removeon void modopt(I2) I2::remove_M02(class [mscorlib]System.Action) } } "; var source1 = @" class C1 : I1 { public static event System.Action<int> M01 { add => throw null; remove{} } } class C2 : I1 { static event System.Action<int> I1.M01 { add => throw null; remove{} } } #pragma warning disable CS0067 // The event 'C3.M02' is never used class C3 : I2 { public static event System.Action M02; } class C4 : I2 { static event System.Action I2.M02 { add => throw null; remove{} } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); var c1M01Add = c1M01.AddMethod; var c1M01Remove = c1M01.RemoveMethod; Assert.Equal("event System.Action<System.Int32> C1.M01", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Equal(MethodKind.EventAdd, c1M01Add.MethodKind); Assert.Equal("void C1.M01.add", c1M01Add.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32> value", c1M01Add.Parameters.Single().ToTestDisplayString()); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c1M01Remove.MethodKind); Assert.Equal("void C1.M01.remove", c1M01Remove.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32> value", c1M01Remove.Parameters.Single().ToTestDisplayString()); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { c1M01Add = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Add.MethodKind); Assert.Equal("void C1.I1.add_M01(System.Action<System.Int32 modopt(I1)> value)", c1M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c1M01Add.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); c1M01Remove = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Remove.MethodKind); Assert.Equal("void C1.I1.remove_M01(System.Action<System.Int32 modopt(I1)> value)", c1M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c1M01Remove.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); // Forwarding methods aren't tied to an event Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01Add, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01Remove, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Add = c2M01.AddMethod; var c2M01Remove = c2M01.RemoveMethod; Assert.Equal("event System.Action<System.Int32 modopt(I1)> C2.I1.M01", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c2M01Add.MethodKind); Assert.Equal("void C2.I1.M01.add", c2M01Add.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32 modopt(I1)> value", c2M01Add.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.AddMethod, c2M01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Add, c2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c2M01Remove.MethodKind); Assert.Equal("void C2.I1.M01.remove", c2M01Remove.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32 modopt(I1)> value", c2M01Remove.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c2M01Remove.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Remove, c2.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(c2M01, c2.GetMembers().OfType<EventSymbol>().Single()); Assert.Equal(2, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m02 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c3M02 = c3.GetMembers().OfType<EventSymbol>().Single(); var c3M02Add = c3M02.AddMethod; var c3M02Remove = c3M02.RemoveMethod; Assert.Equal("event System.Action C3.M02", c3M02.ToTestDisplayString()); Assert.Empty(c3M02.ExplicitInterfaceImplementations); Assert.True(c3M02.IsStatic); Assert.False(c3M02.IsAbstract); Assert.False(c3M02.IsVirtual); Assert.Equal(MethodKind.EventAdd, c3M02Add.MethodKind); Assert.Equal("void C3.M02.add", c3M02Add.ToTestDisplayString()); Assert.Equal("System.Action value", c3M02Add.Parameters.Single().ToTestDisplayString()); Assert.Empty(c3M02Add.ExplicitInterfaceImplementations); Assert.True(c3M02Add.IsStatic); Assert.False(c3M02Add.IsAbstract); Assert.False(c3M02Add.IsVirtual); Assert.False(c3M02Add.IsMetadataVirtual()); Assert.False(c3M02Add.IsMetadataFinal); Assert.False(c3M02Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c3M02Remove.MethodKind); Assert.Equal("void C3.M02.remove", c3M02Remove.ToTestDisplayString()); Assert.Equal("System.Void", c3M02Remove.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Empty(c3M02Remove.ExplicitInterfaceImplementations); Assert.True(c3M02Remove.IsStatic); Assert.False(c3M02Remove.IsAbstract); Assert.False(c3M02Remove.IsVirtual); Assert.False(c3M02Remove.IsMetadataVirtual()); Assert.False(c3M02Remove.IsMetadataFinal); Assert.False(c3M02Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { c3M02Add = (MethodSymbol)c3.FindImplementationForInterfaceMember(m02.AddMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c3M02Add.MethodKind); Assert.Equal("void C3.I2.add_M02(System.Action modopt(I1) value)", c3M02Add.ToTestDisplayString()); Assert.Same(m02.AddMethod, c3M02Add.ExplicitInterfaceImplementations.Single()); Assert.True(c3M02Add.IsStatic); Assert.False(c3M02Add.IsAbstract); Assert.False(c3M02Add.IsVirtual); Assert.False(c3M02Add.IsMetadataVirtual()); Assert.False(c3M02Add.IsMetadataFinal); Assert.False(c3M02Add.IsMetadataNewSlot()); c3M02Remove = (MethodSymbol)c3.FindImplementationForInterfaceMember(m02.RemoveMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c3M02Remove.MethodKind); Assert.Equal("void modopt(I2) C3.I2.remove_M02(System.Action value)", c3M02Remove.ToTestDisplayString()); Assert.Same(m02.RemoveMethod, c3M02Remove.ExplicitInterfaceImplementations.Single()); Assert.True(c3M02Remove.IsStatic); Assert.False(c3M02Remove.IsAbstract); Assert.False(c3M02Remove.IsVirtual); Assert.False(c3M02Remove.IsMetadataVirtual()); Assert.False(c3M02Remove.IsMetadataFinal); Assert.False(c3M02Remove.IsMetadataNewSlot()); // Forwarding methods aren't tied to an event Assert.Null(c3.FindImplementationForInterfaceMember(m02)); } else { Assert.Same(c3M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c3M02Add, c3.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.Same(c3M02Remove, c3.FindImplementationForInterfaceMember(m02.RemoveMethod)); } var c4 = module.GlobalNamespace.GetTypeMember("C4"); var c4M02 = (EventSymbol)c4.FindImplementationForInterfaceMember(m02); var c4M02Add = c4M02.AddMethod; var c4M02Remove = c4M02.RemoveMethod; Assert.Equal("event System.Action C4.I2.M02", c4M02.ToTestDisplayString()); // Signatures of accessors are lacking custom modifiers due to https://github.com/dotnet/roslyn/issues/53390. Assert.True(c4M02.IsStatic); Assert.False(c4M02.IsAbstract); Assert.False(c4M02.IsVirtual); Assert.Same(m02, c4M02.ExplicitInterfaceImplementations.Single()); Assert.True(c4M02Add.IsStatic); Assert.False(c4M02Add.IsAbstract); Assert.False(c4M02Add.IsVirtual); Assert.False(c4M02Add.IsMetadataVirtual()); Assert.False(c4M02Add.IsMetadataFinal); Assert.False(c4M02Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c4M02Add.MethodKind); Assert.Equal("void C4.I2.M02.add", c4M02Add.ToTestDisplayString()); Assert.Equal("System.Action value", c4M02Add.Parameters.Single().ToTestDisplayString()); Assert.Equal("System.Void", c4M02Add.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Same(m02.AddMethod, c4M02Add.ExplicitInterfaceImplementations.Single()); Assert.Same(c4M02Add, c4.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.True(c4M02Remove.IsStatic); Assert.False(c4M02Remove.IsAbstract); Assert.False(c4M02Remove.IsVirtual); Assert.False(c4M02Remove.IsMetadataVirtual()); Assert.False(c4M02Remove.IsMetadataFinal); Assert.False(c4M02Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c4M02Remove.MethodKind); Assert.Equal("void C4.I2.M02.remove", c4M02Remove.ToTestDisplayString()); Assert.Equal("System.Action value", c4M02Remove.Parameters.Single().ToTestDisplayString()); Assert.Equal("System.Void", c4M02Remove.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Same(m02.RemoveMethod, c4M02Remove.ExplicitInterfaceImplementations.Single()); Assert.Same(c4M02Remove, c4.FindImplementationForInterfaceMember(m02.RemoveMethod)); Assert.Same(c4M02, c4.GetMembers().OfType<EventSymbol>().Single()); Assert.Equal(2, c4.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); } verifier.VerifyIL("C1.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C1.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.remove"" IL_0006: ret } "); verifier.VerifyIL("C3.I2.add_M02", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C3.M02.add"" IL_0006: ret } "); verifier.VerifyIL("C3.I2.remove_M02", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C3.M02.remove"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticEvent_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static event System.Action M01; abstract static event System.Action M02; } public class C1 { public static event System.Action M01 { add => throw null; remove{} } } public class C2 : C1, I1 { static event System.Action I1.M02 { add => throw null; remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<EventSymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<EventSymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<EventSymbol>("M01"); Assert.Equal("event System.Action C1.M01", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); var c1M01Add = c1M01.AddMethod; Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); var c1M01Remove = c1M01.RemoveMethod; Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01Add = c3.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal("void C2.I1.add_M01(System.Action value)", c2M01Add.ToTestDisplayString()); var c2M01Remove = c3.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal("void C2.I1.remove_M01(System.Action value)", c2M01Remove.ToTestDisplayString()); // Forwarding methods for accessors aren't tied to an event Assert.Null(c3.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<EventSymbol>().Single(); var c2M02 = c3.BaseType().GetMember<EventSymbol>("I1.M02"); Assert.Equal("event System.Action C2.I1.M02", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c2M02.AddMethod, c3.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.Same(c2M02.RemoveMethod, c3.FindImplementationForInterfaceMember(m02.RemoveMethod)); } } [Fact] public void ImplementAbstractStaticEvent_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static event System.Action M01; } public class C1 : I1 { public static event System.Action M01 { add{} remove => throw null; } } public class C2 : C1 { new public static event System.Action M01 { add{} remove => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C3.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.remove"" IL_0006: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<EventSymbol>("M01"); var c2M01Add = c2M01.AddMethod; var c2M01Remove = c2M01.RemoveMethod; Assert.Equal("event System.Action C2.M01", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.Empty(c2M01Add.ExplicitInterfaceImplementations); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); Assert.Empty(c2M01Remove.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (EventSymbol)c3.FindImplementationForInterfaceMember(m01); // Forwarding methods for accessors aren't tied to an event Assert.Null(c3M01); var c3M01Add = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal("void C3.I1.add_M01(System.Action value)", c3M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c3M01Add.ExplicitInterfaceImplementations.Single()); var c3M01Remove = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal("void C3.I1.remove_M01(System.Action value)", c3M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c3M01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c2M01Add, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c2M01Remove, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_19(bool genericFirst) { // An "ambiguity" in implicit/explicit implementation declared in generic base class. var generic = @" public static event System.Action<T> M01 { add{} remove{} } "; var nonGeneric = @" static event System.Action<int> I1.M01 { add{} remove{} } "; var source1 = @" public interface I1 { abstract static event System.Action<int> M01; } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<EventSymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action<System.Int32> C1<T>.I1.M01", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_20(bool genericFirst) { // Same as ImplementAbstractStaticEvent_19 only interface is generic too. var generic = @" static event System.Action<T> I1<T>.M01 { add{} remove{} } "; var nonGeneric = @" public static event System.Action<int> M01 { add{} remove{} } "; var source1 = @" public interface I1<T> { abstract static event System.Action<T> M01; } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<EventSymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action<T> C1<T>.I1<T>.M01", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } private static string ConversionOperatorName(string op) => op switch { "implicit" => WellKnownMemberNames.ImplicitConversionName, "explicit" => WellKnownMemberNames.ExplicitConversionName, _ => throw TestExceptionUtilities.UnexpectedValue(op) }; [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = ConversionOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public " + op + @" operator int(C2 x) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static " + op + @" operator int(C3 x) => throw null; } " + typeKeyword + @" C4 : I1<C4> { " + op + @" I1<C4>.operator int(C4 x) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static " + op + @" operator long(C5 x) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static " + op + @" I1<C6>.operator long(C6 x) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static int " + opName + @"(C7 x) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static int I1<C8>." + opName + @"(C8 x) => throw null; } public interface I2<T> where T : I2<T> { abstract static int " + opName + @"(T x); } " + typeKeyword + @" C9 : I2<C9> { public static " + op + @" operator int(C9 x) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static " + op + @" I2<C10>.operator int(C10 x) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.explicit operator int(C1)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>." + op + " operator int(C1)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.explicit operator int(C2)'. 'C2.explicit operator int(C2)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>." + op + " operator int(C2)", "C2." + op + " operator int(C2)").WithLocation(12, 10), // (14,30): error CS0558: User-defined operator 'C2.explicit operator int(C2)' must be declared static and public // public explicit operator int(C2 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("C2." + op + " operator int(C2)").WithLocation(14, 30), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.explicit operator int(C3)'. 'C3.explicit operator int(C3)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>." + op + " operator int(C3)", "C3." + op + " operator int(C3)").WithLocation(18, 10), // (20,30): error CS0558: User-defined operator 'C3.explicit operator int(C3)' must be declared static and public // static explicit operator int(C3 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("C3." + op + " operator int(C3)").WithLocation(20, 30), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.explicit operator int(C4)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>." + op + " operator int(C4)").WithLocation(24, 10), // (26,30): error CS8930: Explicit implementation of a user-defined operator 'C4.explicit operator int(C4)' must be declared static // explicit I1<C4>.operator int(C4 x) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, "int").WithArguments("C4." + op + " operator int(C4)").WithLocation(26, 30), // (26,30): error CS0539: 'C4.explicit operator int(C4)' in explicit interface declaration is not found among members of the interface that can be implemented // explicit I1<C4>.operator int(C4 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C4." + op + " operator int(C4)").WithLocation(26, 30), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.explicit operator int(C5)'. 'C5.explicit operator long(C5)' cannot implement 'I1<C5>.explicit operator int(C5)' because it does not have the matching return type of 'int'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>." + op + " operator int(C5)", "C5." + op + " operator long(C5)", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.explicit operator int(C6)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>." + op + " operator int(C6)").WithLocation(36, 10), // (38,37): error CS0539: 'C6.explicit operator long(C6)' in explicit interface declaration is not found among members of the interface that can be implemented // static explicit I1<C6>.operator long(C6 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "long").WithArguments("C6." + op + " operator long(C6)").WithLocation(38, 37), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.explicit operator int(C7)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>." + op + " operator int(C7)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.explicit operator int(C8)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>." + op + " operator int(C8)").WithLocation(48, 10), // (50,23): error CS0539: 'C8.op_Explicit(C8)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C8>.op_Explicit(C8 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8)").WithLocation(50, 23), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_Explicit(C9)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_Explicit(C10)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10)").WithLocation(65, 11), // (67,38): error CS0539: 'C10.explicit operator int(C10)' in explicit interface declaration is not found among members of the interface that can be implemented // static explicit I2<C10>.operator int(C10 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C10." + op + " operator int(C10)").WithLocation(67, 38) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_03([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } interface I2<T> : I1<T> where T : I1<T> {} interface I3<T> : I1<T> where T : I1<T> { " + op + @" operator int(T x) => default; } interface I4<T> : I1<T> where T : I1<T> { static " + op + @" operator int(T x) => default; } interface I5<T> : I1<T> where T : I1<T> { " + op + @" I1<T>.operator int(T x) => default; } interface I6<T> : I1<T> where T : I1<T> { static " + op + @" I1<T>.operator int(T x) => default; } interface I7<T> : I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public interface I11<T> where T : I11<T> { abstract static " + op + @" operator int(T x); } interface I8<T> : I11<T> where T : I8<T> { " + op + @" operator int(T x) => default; } interface I9<T> : I11<T> where T : I9<T> { static " + op + @" operator int(T x) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static " + op + @" operator int(T x); } interface I12<T> : I11<T> where T : I12<T> { static " + op + @" I11<T>.operator int(T x) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static " + op + @" I11<T>.operator int(T x); } interface I14<T> : I1<T> where T : I1<T> { abstract static " + op + @" I1<T>.operator int(T x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (12,23): error CS0556: User-defined conversion must convert to or from the enclosing type // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(12, 23), // (12,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(12, 23), // (17,30): error CS0556: User-defined conversion must convert to or from the enclosing type // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(17, 30), // (17,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(17, 30), // (22,29): error CS8930: Explicit implementation of a user-defined operator 'I5<T>.implicit operator int(T)' must be declared static // implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, "int").WithArguments("I5<T>." + op + " operator int(T)").WithLocation(22, 29), // (22,29): error CS0539: 'I5<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I5<T>." + op + " operator int(T)").WithLocation(22, 29), // (27,36): error CS0539: 'I6<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I6<T>." + op + " operator int(T)").WithLocation(27, 36), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "int").WithLocation(32, 39), // (42,23): error CS0556: User-defined conversion must convert to or from the enclosing type // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(42, 23), // (42,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(42, 23), // (47,30): error CS0556: User-defined conversion must convert to or from the enclosing type // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(47, 30), // (47,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(47, 30), // (57,37): error CS0539: 'I12<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I11<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I12<T>." + op + " operator int(T)").WithLocation(57, 37), // (62,46): error CS0106: The modifier 'abstract' is not valid for this item // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(62, 46), // (62,46): error CS0501: 'I13<T>.implicit operator int(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "int").WithArguments("I13<T>." + op + " operator int(T)").WithLocation(62, 46), // (62,46): error CS0539: 'I13<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I13<T>." + op + " operator int(T)").WithLocation(62, 46), // (67,45): error CS0106: The modifier 'abstract' is not valid for this item // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(67, 45), // (67,45): error CS0501: 'I14<T>.implicit operator int(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "int").WithArguments("I14<T>." + op + " operator int(T)").WithLocation(67, 45), // (67,45): error CS0539: 'I14<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I14<T>." + op + " operator int(T)").WithLocation(67, 45) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_04([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I2<T> where T : I2<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1 : I2<Test1> { static " + op + @" I2<Test1>.operator int(Test1 x) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static " + op + @" operator int(Test2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,21): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static explicit I2<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I2<Test1>.").WithArguments("static abstract members in interfaces").WithLocation(4, 21) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (4,21): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static explicit I2<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I2<Test1>.").WithArguments("static abstract members in interfaces").WithLocation(4, 21), // (14,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(14, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_05([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static " + op + @" operator int(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.explicit operator int(Test1)' cannot implement interface member 'I1<Test1>.explicit operator int(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1." + op + " operator int(Test1)", "I1<Test1>." + op + " operator int(Test1)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.explicit operator int(Test1)' cannot implement interface member 'I1<Test1>.explicit operator int(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1." + op + " operator int(Test1)", "I1<Test1>." + op + " operator int(Test1)", "Test1").WithLocation(2, 12), // (9,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(9, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_06([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1 : I1<Test1> { static " + op + @" I1<Test1>.operator int(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,40): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static explicit I1<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 40) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,40): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static explicit I1<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 40), // (9,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(9, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_07([CombinatorialValues("implicit", "explicit")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); abstract static " + op + @" operator long(T x); } " + typeKeyword + @" C : I1<C> { public static " + op + @" operator long(C x) => default; public static " + op + @" operator int(C x) => default; } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = i1.GetMembers().OfType<MethodSymbol>().First(); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("System.Int32 C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } var m02 = i1.GetMembers().OfType<MethodSymbol>().ElementAt(1); var cM02 = (MethodSymbol)c.FindImplementationForInterfaceMember(m02); Assert.True(cM02.IsStatic); Assert.False(cM02.IsAbstract); Assert.False(cM02.IsVirtual); Assert.False(cM02.IsMetadataVirtual()); Assert.False(cM02.IsMetadataFinal); Assert.False(cM02.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, cM02.MethodKind); Assert.False(cM02.HasRuntimeSpecialName); Assert.True(cM02.HasSpecialName); Assert.Equal("System.Int64 C." + opName + "(C x)", cM02.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m02, cM02.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM02.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_08([CombinatorialValues("implicit", "explicit")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" interface I1<T> where T : I1<T> { abstract static " + op + @" operator C(T x); abstract static " + op + @" operator int(T x); } " + typeKeyword + @" C : I1<C> { static " + op + @" I1<C>.operator int(C x) => int.MaxValue; static " + op + @" I1<C>.operator C(C x) => default; } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal("default", node.ToString()); Assert.Equal("C", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<ConversionOperatorDeclarationSyntax>()); Assert.Equal("C C.I1<C>." + opName + "(C x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<MethodSymbol>().First(); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("C C.I1<C>." + opName + "(C x)", cM01.ToTestDisplayString()); Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); var m02 = c.Interfaces().Single().GetMembers().OfType<MethodSymbol>().ElementAt(1); var cM02 = (MethodSymbol)c.FindImplementationForInterfaceMember(m02); Assert.True(cM02.IsStatic); Assert.False(cM02.IsAbstract); Assert.False(cM02.IsVirtual); Assert.False(cM02.IsMetadataVirtual()); Assert.False(cM02.IsMetadataFinal); Assert.False(cM02.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM02.MethodKind); Assert.False(cM02.HasRuntimeSpecialName); Assert.False(cM02.HasSpecialName); Assert.Equal("System.Int32 C.I1<C>." + opName + "(C x)", cM02.ToTestDisplayString()); Assert.Equal(m02, cM02.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_09([CombinatorialValues("implicit", "explicit")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = ConversionOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.I1<C2>." + opName + "(C2 x)", cM01.ToTestDisplayString()); Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_10([CombinatorialValues("implicit", "explicit")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 " + opName + @" ( !T x ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements class I1`1<class C1> { .method private hidebysig static int32 'I1<C1>." + opName + @"' ( class C1 x ) cil managed { .override method int32 class I1`1<class C1>::" + opName + @"(!0) IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig static specialname int32 " + opName + @" ( class C1 x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2053 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: nop IL_0007: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements class I1`1<class C1> { .method public hidebysig static specialname int32 " + opName + @" ( class C1 x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1<C1> { } public class C5 : C2, I1<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Equal(MethodKind.Conversion, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2." + opName + "(C1 x)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.Conversion, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_11([CombinatorialValues("implicit", "explicit")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname virtual static int32 " + opName + @" ( !T x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } } "; var source1 = @" public class C1 : I1<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1<C1> { static " + op + @" I1<C1>.operator int(C1 x) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation2.VerifyEmitDiagnostics( // (4,37): error CS0539: 'C1.implicit operator int(C1)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I1<C1>.operator int(C1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C1." + op + " operator int(C1)").WithLocation(4, 37) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("System.Int32 I1<C1>." + opName + "(C1 x)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_12([CombinatorialValues("implicit", "explicit")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 " + opName + @" ( !T x ) cil managed { } } .class interface public auto ansi abstract I2`1<(class I1`1<!T>) T> implements class I1`1<!T> { .method private hidebysig static int32 'I1<!T>." + opName + @"' ( !T x ) cil managed { .override method int32 class I1`1<!T>::" + opName + @"(!0) IL_0000: ldc.i4.0 IL_0001: ret } } "; var source1 = @" public class C1 : I2<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1<C1>.explicit operator int(C1)' // public class C1 : I2<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C1>").WithArguments("C1", "I1<C1>." + op + " operator int(C1)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_13([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static " + op + @" operator C1<T>(T x); } public partial class C1<T> { public static " + op + @" operator C1<T>(T x) => default; } public class C2 : C1<C2>, I1<C2> { } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var i1 = c2.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.False(c2M01.HasSpecialName); Assert.Equal("C1<C2> C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.False(c1M01.HasRuntimeSpecialName); Assert.True(c1M01.HasSpecialName); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Conversion, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.True(c2M01.HasSpecialName); Assert.Equal("C1<C2> C1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1<C2>." + opName + "(C2)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""C1<C2> C1<C2>." + opName + @"(C2)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_14([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static " + op + @" operator int(C1 x) => default; } class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("System.Int32 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("System.Int32 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.Equal("System.Int32 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("System.Int32 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int C1." + opName + @"(C1)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_15([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static " + op + @" operator C1<T>(T x); abstract static " + op + @" operator T(int x); } public partial class C1<T> { public static " + op + @" operator C1<T>(T x) => default; } public class C2 : C1<C2>, I1<C2> { static " + op + @" I1<C2>.operator C2(int x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = ConversionOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().First(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C1<C2> C1<C2>." + opName + "(C2 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<C2> C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Equal(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().ElementAt(1); var c2M02 = c3.BaseType().GetMembers("I1<C2>." + opName).OfType<MethodSymbol>().First(); Assert.Equal("C2 C2.I1<C2>." + opName + "(System.Int32 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_18([CombinatorialValues("implicit", "explicit")] string op, bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static " + op + @" operator U(C1<T, U> x) => default; "; var nonGeneric = @" public static " + op + @" operator int(C1<T, U> x) => default; "; var source1 = @" public interface I1<T, U> where T : I1<T, U> { abstract static " + op + @" operator U(T x); } public class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>." + opName + "(C1<T, U> x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>." + opName + "(C1<T, U> x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_20([CombinatorialValues("implicit", "explicit")] string op, bool genericFirst) { // Same as ImplementAbstractStaticConversionOperator_18 only implementation is explicit in source. var generic = @" static " + op + @" I1<C1<T, U>, U>.operator U(C1<T, U> x) => default; "; var nonGeneric = @" public static " + op + @" operator int(C1<T, U> x) => default; "; var source1 = @" public interface I1<T, U> where T : I1<T, U> { abstract static " + op + @" operator U(T x); } public class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateCompilation("", targetFramework: _supportingFramework).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: _supportingFramework, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>.I1<C1<T, U>, U>." + opName + "(C1<T, U> x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class C1 : I1<C1> { static " + op + @" I1<C1>.operator int(C1 x) => default; } class C2 : I1<C2> { private static " + op + @" I1<C2>.operator int(C2 x) => default; } class C3 : I1<C3> { protected static " + op + @" I1<C3>.operator int(C3 x) => default; } class C4 : I1<C4> { internal static " + op + @" I1<C4>.operator int(C4 x) => default; } class C5 : I1<C5> { protected internal static " + op + @" I1<C5>.operator int(C5 x) => default; } class C6 : I1<C6> { private protected static " + op + @" I1<C6>.operator int(C6 x) => default; } class C7 : I1<C7> { public static " + op + @" I1<C7>.operator int(C7 x) => default; } class C9 : I1<C9> { async static " + op + @" I1<C9>.operator int(C9 x) => default; } class C10 : I1<C10> { unsafe static " + op + @" I1<C10>.operator int(C10 x) => default; } class C11 : I1<C11> { static readonly " + op + @" I1<C11>.operator int(C11 x) => default; } class C12 : I1<C12> { extern static " + op + @" I1<C12>.operator int(C12 x); } class C13 : I1<C13> { abstract static " + op + @" I1<C13>.operator int(C13 x) => default; } class C14 : I1<C14> { virtual static " + op + @" I1<C14>.operator int(C14 x) => default; } class C15 : I1<C15> { sealed static " + op + @" I1<C15>.operator int(C15 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.WRN_ExternMethodNoImplementation).Verify( // (16,45): error CS0106: The modifier 'private' is not valid for this item // private static explicit I1<C2>.operator int(C2 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("private").WithLocation(16, 45), // (22,47): error CS0106: The modifier 'protected' is not valid for this item // protected static explicit I1<C3>.operator int(C3 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("protected").WithLocation(22, 47), // (28,46): error CS0106: The modifier 'internal' is not valid for this item // internal static explicit I1<C4>.operator int(C4 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("internal").WithLocation(28, 46), // (34,56): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static explicit I1<C5>.operator int(C5 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("protected internal").WithLocation(34, 56), // (40,55): error CS0106: The modifier 'private protected' is not valid for this item // private protected static explicit I1<C6>.operator int(C6 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("private protected").WithLocation(40, 55), // (46,44): error CS0106: The modifier 'public' is not valid for this item // public static explicit I1<C7>.operator int(C7 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("public").WithLocation(46, 44), // (52,43): error CS0106: The modifier 'async' is not valid for this item // async static explicit I1<C9>.operator int(C9 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("async").WithLocation(52, 43), // (64,47): error CS0106: The modifier 'readonly' is not valid for this item // static readonly explicit I1<C11>.operator int(C11 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("readonly").WithLocation(64, 47), // (76,47): error CS0106: The modifier 'abstract' is not valid for this item // abstract static explicit I1<C13>.operator int(C13 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(76, 47), // (82,46): error CS0106: The modifier 'virtual' is not valid for this item // virtual static explicit I1<C14>.operator int(C14 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("virtual").WithLocation(82, 46), // (88,45): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit I1<C15>.operator int(C15 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(88, 45) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : struct, I1<T> { abstract static " + op + @" operator int(T x); } class C1 { static " + op + @" I1<int>.operator int(int x) => default; } class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (9,21): error CS0540: 'C1.I1<int>.implicit operator int(int)': containing type does not implement interface 'I1<int>' // static implicit I1<int>.operator int(int x) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<int>").WithArguments("C1.I1<int>." + op + " operator int(int)", "I1<int>").WithLocation(9, 21), // (9,21): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion from 'int' to 'I1<int>'. // static implicit I1<int>.operator int(int x) => default; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "I1<int>").WithArguments("I1<T>", "I1<int>", "T", "int").WithLocation(9, 21), // (12,7): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // class C2 : I1<C2> Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 7), // (14,21): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static implicit I1<C2>.operator int(C2 x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 21) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { string cast = (op == "explicit" ? "(int)" : ""); var source1 = @" interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); static int M02(I1<T> x) { return " + cast + @"x; } int M03(I1<T> y) { return " + cast + @"y; } } class Test<T> where T : I1<T> { static int MT1(I1<T> a) { return " + cast + @"a; } static void MT2() { _ = (System.Linq.Expressions.Expression<System.Func<T, int>>)((T b) => " + cast + @"b); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (8,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)x; Diagnostic(error, cast + "x").WithArguments("I1<T>", "int").WithLocation(8, 16), // (13,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)y; Diagnostic(error, cast + "y").WithArguments("I1<T>", "int").WithLocation(13, 16), // (21,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)a; Diagnostic(error, cast + "a").WithArguments("I1<T>", "int").WithLocation(21, 16), // (26,80): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Func<T, int>>)((T b) => (int)b); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, cast + "b").WithLocation(26, 80) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1 { abstract static implicit operator bool(I1 x); static void M02((int, C<I1>) x) { _ = x " + op + @" x; } void M03((int, C<I1>) y) { _ = y " + op + @" y; } } class Test { static void MT1((int, C<I1>) a) { _ = a " + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b " + op + @" b).ToString()); } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (4,39): error CS0552: 'I1.implicit operator bool(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator bool(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "bool").WithArguments("I1.implicit operator bool(I1)").WithLocation(4, 39), // (9,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = x == x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x " + op + " x").WithArguments("I1", "bool").WithLocation(9, 13), // (14,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = y == y; Diagnostic(ErrorCode.ERR_NoImplicitConv, "y " + op + " y").WithArguments("I1", "bool").WithLocation(14, 13), // (22,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = a == a; Diagnostic(ErrorCode.ERR_NoImplicitConv, "a " + op + " a").WithArguments("I1", "bool").WithLocation(22, 13), // (27,98): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(27, 98) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_03([CombinatorialValues("implicit", "explicit")] string op) { string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class Test { static int M02<T, U>(T x) where T : U where U : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int? M03<T, U>(T y) where T : U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"y; } static int? M04<T, U>(T? y) where T : struct, U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"y; } static int? M05<T, U>() where T : struct, U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"(T?)new T(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 23 (0x17) .maxstack 1 .locals init (int? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: newobj ""int?..ctor(int)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (T? V_0, int? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""int?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""int I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""int?..ctor(int)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 27 (0x1b) .maxstack 1 .locals init (int? V_0) IL_0000: nop IL_0001: call ""T System.Activator.CreateInstance<T>()"" IL_0006: constrained. ""T"" IL_000c: call ""int I1<T>." + metadataName + @"(T)"" IL_0011: newobj ""int?..ctor(int)"" IL_0016: stloc.0 IL_0017: br.s IL_0019 IL_0019: ldloc.0 IL_001a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""int I1<T>." + metadataName + @"(T)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""int I1<T>." + metadataName + @"(T)"" IL_000c: newobj ""int?..ctor(int)"" IL_0011: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (T? V_0, int? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""int?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""int I1<T>." + metadataName + @"(T)"" IL_0027: newobj ""int?..ctor(int)"" IL_002c: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 22 (0x16) .maxstack 1 IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: constrained. ""T"" IL_000b: call ""int I1<T>." + metadataName + @"(T)"" IL_0010: newobj ""int?..ctor(int)"" IL_0015: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().First(); Assert.Equal("return " + (needCast ? "(int)" : "") + @"x;", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return " + (needCast ? "(int)" : "") + @"x;') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 I1<T>." + metadataName + @"(T x)) (OperationKind.Conversion, Type: System.Int32" + (needCast ? "" : ", IsImplicit") + @") (Syntax: '" + (needCast ? "(int)" : "") + @"x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 I1<T>." + metadataName + @"(T x)) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool (T x); } class Test { static void M02<T, U>((int, C<T>) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_Implicit(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.0 IL_0032: pop IL_0033: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_Implicit(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.1 IL_0032: pop IL_0033: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_Implicit(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.0 IL_0031: pop IL_0032: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_Implicit(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.1 IL_0031: pop IL_0032: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_04([CombinatorialValues("implicit", "explicit")] string op) { bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = @" class Test { static int M02<T>(T x) where T : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,16): error CS8919: Target runtime doesn't support static abstract members in interfaces. // return (int)x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, (needCast ? "(int)" : "") + "x").WithLocation(6, 16) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(12, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool(T x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (21,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static implicit operator bool(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "bool").WithLocation(21, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_06([CombinatorialValues("implicit", "explicit")] string op) { bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = @" class Test { static int M02<T>(T x) where T : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,16): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // return x; Diagnostic(ErrorCode.ERR_FeatureInPreview, (needCast ? "(int)" : "") + "x").WithArguments("static abstract members in interfaces").WithLocation(6, 16) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(12, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool(T x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: _supportingFramework); compilation3.VerifyDiagnostics( // (21,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator bool(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "bool").WithArguments("abstract", "9.0", "preview").WithLocation(21, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_07([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_03 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } class Test { static T M02<T, U>(int x) where T : U where U : I1<T> { return " + (needCast ? "(T)" : "") + @"x; } static T? M03<T, U>(int y) where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"y; } static T? M04<T, U>(int? y) where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"y; } static T? M05<T, U>() where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"(T?)0; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(int)", @" { // Code size 23 (0x17) .maxstack 1 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: newobj ""T?..ctor(T)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (int? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool int?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly int int?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(int)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 23 (0x17) .maxstack 1 .locals init (T? V_0) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: newobj ""T?..ctor(T)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: newobj ""T?..ctor(T)"" IL_0011: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (int? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool int?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly int int?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""T I1<T>." + metadataName + @"(int)"" IL_0027: newobj ""T?..ctor(T)"" IL_002c: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: newobj ""T?..ctor(T)"" IL_0011: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().First(); Assert.Equal("return " + (needCast ? "(T)" : "") + @"x;", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return " + (needCast ? "(T)" : "") + @"x;') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: T I1<T>." + metadataName + @"(System.Int32 x)) (OperationKind.Conversion, Type: T" + (needCast ? "" : ", IsImplicit") + @") (Syntax: '" + (needCast ? "(T)" : "") + @"x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: T I1<T>." + metadataName + @"(System.Int32 x)) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_08([CombinatorialValues("implicit", "explicit")] string op) { // Don't look in interfaces of the effective base string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class C1<T> : I1<C1<T>> { static " + op + @" I1<C1<T>>.operator int(C1<T> x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int M03<T>(C1<T> y) where T : I1<C1<T>> { return " + (needCast ? "(int)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (16,16): error CS0030: Cannot convert type 'T' to 'int' // return (int)x; Diagnostic(error, (needCast ? "(int)" : "") + "x").WithArguments("T", "int").WithLocation(16, 16), // (21,16): error CS0030: Cannot convert type 'C1<T>' to 'int' // return (int)y; Diagnostic(error, (needCast ? "(int)" : "") + "y").WithArguments("C1<T>", "int").WithLocation(21, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_09([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_08 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } class C1<T> : I1<C1<T>> { static " + op + @" I1<C1<T>>.operator C1<T>(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1<T> { return " + (needCast ? "(T)" : "") + @"x; } static C1<T> M03<T>(int y) where T : I1<C1<T>> { return " + (needCast ? "(C1<T>)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (16,16): error CS0030: Cannot convert type 'int' to 'T' // return (T)x; Diagnostic(error, (needCast ? "(T)" : "") + "x").WithArguments("int", "T").WithLocation(16, 16), // (21,16): error CS0030: Cannot convert type 'int' to 'C1<T>' // return (C1<T>)y; Diagnostic(error, (needCast ? "(C1<T>)" : "") + "y").WithArguments("int", "C1<T>").WithLocation(21, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_10([CombinatorialValues("implicit", "explicit")] string op) { // Look in derived interfaces string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public interface I2<T> : I1<T> where T : I1<T> {} class Test { static int M02<T, U>(T x) where T : U where U : I2<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_11([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_10 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } public interface I2<T> : I1<T> where T : I1<T> {} class Test { static T M02<T, U>(int x) where T : U where U : I2<T> { return " + (needCast ? "(T)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_12([CombinatorialValues("implicit", "explicit")] string op) { // Ignore duplicate candidates string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T, U> where T : I1<T, U> where U : I1<T, U> { abstract static " + op + @" operator U(T x); } class Test { static U M02<T, U>(T x) where T : I1<T, U> where U : I1<T, U> { return " + (needCast ? "(U)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (U V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""U I1<T, U>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_13([CombinatorialValues("implicit", "explicit")] string op) { // Look in effective base string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public class C1<T> { public static " + op + @" operator int(C1<T> x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: call ""int C1<T>." + metadataName + @"(C1<T>)"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Fact] public void ConsumeAbstractConversionOperator_14() { // Same as ConsumeAbstractConversionOperator_13 only direction of conversion is flipped var source1 = @" public class C1<T> { public static explicit operator C1<T>(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1<T> { return (T)x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""C1<T> C1<T>.op_Explicit(int)"" IL_0007: unbox.any ""T"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_15([CombinatorialValues("implicit", "explicit")] string op) { // If there is a non-trivial class constraint, interfaces are not looked at. string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C1 : I1<C1> { public static " + op + @" operator int(C1 x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1, I1<C1> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: call ""int C1." + metadataName + @"(C1)"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Fact] public void ConsumeAbstractConversionOperator_16() { // Same as ConsumeAbstractConversionOperator_15 only direction of conversion is flipped var source1 = @" public interface I1<T> where T : I1<T> { abstract static explicit operator T(int x); } public class C1 : I1<C1> { public static explicit operator C1(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1, I1<C1> { return (T)x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""C1 C1.op_Explicit(int)"" IL_0007: unbox.any ""T"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_17([CombinatorialValues("implicit", "explicit")] string op) { // If there is a non-trivial class constraint, interfaces are not looked at. bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C1 { } class Test { static int M02<T, U>(T x) where T : U where U : C1, I1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int M03<T, U>(T y) where T : U where U : I1<T> { return " + (needCast ? "(int)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (15,16): error CS0030: Cannot convert type 'T' to 'int' // return (int)x; Diagnostic((op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv), (needCast ? "(int)" : "") + "x").WithArguments("T", "int").WithLocation(15, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_18([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_17 only direction of conversion is flipped bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } public class C1 { } class Test { static T M02<T, U>(int x) where T : U where U : C1, I1<T> { return " + (needCast ? "(T)" : "") + @"x; } static T M03<T, U>(int y) where T : U where U : I1<T> { return " + (needCast ? "(T)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation1.VerifyDiagnostics( // (15,16): error CS0030: Cannot convert type 'int' to 'T' // return (T)x; Diagnostic((op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv), (needCast ? "(T)" : "") + "x").WithArguments("int", "T").WithLocation(15, 16) ); } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_01() { var source1 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } public class Derived : Base<int>, Interface<int, int> { } class YetAnother : Interface<int, int> { public static void Method(int i) { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var b = module.GlobalNamespace.GetTypeMember("Base"); var bI = b.Interfaces().Single(); var biMethods = bI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", biMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", biMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", biMethods[2].OriginalDefinition.ToTestDisplayString()); var bM1 = b.FindImplementationForInterfaceMember(biMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", bM1.ToTestDisplayString()); var bM2 = b.FindImplementationForInterfaceMember(biMethods[1]); Assert.Equal("void Base<T>.Method(T i)", bM2.ToTestDisplayString()); Assert.Same(bM2, b.FindImplementationForInterfaceMember(biMethods[2])); var bM1Impl = ((MethodSymbol)bM1).ExplicitInterfaceImplementations; var bM2Impl = ((MethodSymbol)bM2).ExplicitInterfaceImplementations; if (module is PEModuleSymbol) { Assert.Equal(biMethods[0], bM1Impl.Single()); Assert.Equal(2, bM2Impl.Length); Assert.Equal(biMethods[1], bM2Impl[0]); Assert.Equal(biMethods[2], bM2Impl[1]); } else { Assert.Empty(bM1Impl); Assert.Empty(bM2Impl); } var d = module.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Same(bM1, dM1.OriginalDefinition); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Same(bM2, dM2.OriginalDefinition); Assert.Same(bM2, d.FindImplementationForInterfaceMember(diMethods[2]).OriginalDefinition); } } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_02() { var source0 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation0.VerifyDiagnostics(); var source1 = @" public class Derived : Base<int>, Interface<int, int> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { compilation0.EmitToImageReference() }); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var d = module.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", dM1.OriginalDefinition.ToTestDisplayString()); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Equal("void Base<T>.Method(T i)", dM2.OriginalDefinition.ToTestDisplayString()); Assert.Same(dM2, d.FindImplementationForInterfaceMember(diMethods[2])); var dM1Impl = ((MethodSymbol)dM1).ExplicitInterfaceImplementations; var dM2Impl = ((MethodSymbol)dM2).ExplicitInterfaceImplementations; Assert.Equal(diMethods[0], dM1Impl.Single()); Assert.Equal(2, dM2Impl.Length); Assert.Equal(diMethods[1], dM2Impl[0]); Assert.Equal(diMethods[2], dM2Impl[1]); } } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_03() { var source0 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { CreateEmptyCompilation("").ToMetadataReference() }); compilation0.VerifyDiagnostics(); var source1 = @" public class Derived : Base<int>, Interface<int, int> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework, references: new[] { compilation0.ToMetadataReference() }); var d = compilation1.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.IsType<RetargetingNamedTypeSymbol>(dB.OriginalDefinition); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", dM1.OriginalDefinition.ToTestDisplayString()); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Equal("void Base<T>.Method(T i)", dM2.OriginalDefinition.ToTestDisplayString()); Assert.Equal(dM2, d.FindImplementationForInterfaceMember(diMethods[2])); var dM1Impl = ((MethodSymbol)dM1).ExplicitInterfaceImplementations; var dM2Impl = ((MethodSymbol)dM2).ExplicitInterfaceImplementations; Assert.Empty(dM1Impl); Assert.Empty(dM2Impl); } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_04() { var source2 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } class Other : Interface<int, int> { static void Interface<int, int>.Method(int i) { } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation2.VerifyDiagnostics( // (9,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(9, 15), // (9,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(9, 15), // (11,37): warning CS0473: Explicit interface implementation 'Other.Interface<int, int>.Method(int)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // static void Interface<int, int>.Method(int i) { } Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Other.Interface<int, int>.Method(int)").WithLocation(11, 37) ); } [Fact] public void UnmanagedCallersOnly_01() { var source2 = @" using System.Runtime.InteropServices; public interface I1 { [UnmanagedCallersOnly] abstract static void M1(); [UnmanagedCallersOnly] abstract static int operator +(I1 x); [UnmanagedCallersOnly] abstract static int operator +(I1 x, I1 y); } public interface I2<T> where T : I2<T> { [UnmanagedCallersOnly] abstract static implicit operator int(T i); [UnmanagedCallersOnly] abstract static explicit operator T(int i); } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation2.VerifyDiagnostics( // (6,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static void M1(); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(6, 6), // (7,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static int operator +(I1 x); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 6), // (8,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static int operator +(I1 x, I1 y); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(8, 6), // (13,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static implicit operator int(T i); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(13, 6), // (14,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static explicit operator T(int i); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(14, 6) ); } [Fact] [WorkItem(54113, "https://github.com/dotnet/roslyn/issues/54113")] public void UnmanagedCallersOnly_02() { var ilSource = @" .class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72 69 74 65 64 00 ) .field public class [mscorlib]System.Type[] CallConvs .field public string EntryPoint .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void M1 () cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static int32 op_UnaryPlus ( class I1 x ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static int32 op_Addition ( class I1 x, class I1 y ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } } .class interface public auto ansi abstract I2`1<(class I2`1<!T>) T> { .method public hidebysig specialname abstract virtual static int32 op_Implicit ( !T i ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static !T op_Explicit ( int32 i ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } } "; var source1 = @" class Test { static void M02<T>(T x, T y) where T : I1 { T.M1(); _ = +x; _ = x + y; } static int M03<T>(T x) where T : I2<T> { _ = (T)x; return x; } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); // Conversions aren't flagged due to https://github.com/dotnet/roslyn/issues/54113. compilation1.VerifyDiagnostics( // (6,11): error CS0570: 'I1.M1()' is not supported by the language // T.M1(); Diagnostic(ErrorCode.ERR_BindToBogus, "M1").WithArguments("I1.M1()").WithLocation(6, 11), // (7,13): error CS0570: 'I1.operator +(I1)' is not supported by the language // _ = +x; Diagnostic(ErrorCode.ERR_BindToBogus, "+x").WithArguments("I1.operator +(I1)").WithLocation(7, 13), // (8,13): error CS0570: 'I1.operator +(I1, I1)' is not supported by the language // _ = x + y; Diagnostic(ErrorCode.ERR_BindToBogus, "x + y").WithArguments("I1.operator +(I1, I1)").WithLocation(8, 13) ); } [Fact] public void UnmanagedCallersOnly_03() { var source2 = @" using System.Runtime.InteropServices; public interface I1<T> where T : I1<T> { abstract static void M1(); abstract static int operator +(T x); abstract static int operator +(T x, T y); abstract static implicit operator int(T i); abstract static explicit operator T(int i); } class C : I1<C> { [UnmanagedCallersOnly] public static void M1() {} [UnmanagedCallersOnly] public static int operator +(C x) => 0; [UnmanagedCallersOnly] public static int operator +(C x, C y) => 0; [UnmanagedCallersOnly] public static implicit operator int(C i) => 0; [UnmanagedCallersOnly] public static explicit operator C(int i) => null; } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation2.VerifyDiagnostics( // (15,47): error CS8932: 'UnmanagedCallersOnly' method 'C.M1()' cannot implement interface member 'I1<C>.M1()' in type 'C' // [UnmanagedCallersOnly] public static void M1() {} Diagnostic(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, "M1").WithArguments("C.M1()", "I1<C>.M1()", "C").WithLocation(15, 47), // (16,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static int operator +(C x) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(16, 6), // (17,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static int operator +(C x, C y) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(17, 6), // (18,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static implicit operator int(C i) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(18, 6), // (19,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static explicit operator C(int i) => null; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(19, 6) ); } [Fact] public void UnmanagedCallersOnly_04() { var source2 = @" using System.Runtime.InteropServices; public interface I1<T> where T : I1<T> { abstract static void M1(); abstract static int operator +(T x); abstract static int operator +(T x, T y); abstract static implicit operator int(T i); abstract static explicit operator T(int i); } class C : I1<C> { [UnmanagedCallersOnly] static void I1<C>.M1() {} [UnmanagedCallersOnly] static int I1<C>.operator +(C x) => 0; [UnmanagedCallersOnly] static int I1<C>.operator +(C x, C y) => 0; [UnmanagedCallersOnly] static implicit I1<C>.operator int(C i) => 0; [UnmanagedCallersOnly] static explicit I1<C>.operator C(int i) => null; } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: _supportingFramework); compilation2.VerifyDiagnostics( // (15,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static void I1<C>.M1() {} Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(15, 6), // (16,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static int I1<C>.operator +(C x) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(16, 6), // (17,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static int I1<C>.operator +(C x, C y) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(17, 6), // (18,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static implicit I1<C>.operator int(C i) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(18, 6), // (19,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static explicit I1<C>.operator C(int i) => null; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(19, 6) ); } } }
1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/Core/Portable/SpecialMember.cs
// 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. namespace Microsoft.CodeAnalysis { // members of special types internal enum SpecialMember { System_String__CtorSZArrayChar, System_String__ConcatStringString, System_String__ConcatStringStringString, System_String__ConcatStringStringStringString, System_String__ConcatStringArray, System_String__ConcatObject, System_String__ConcatObjectObject, System_String__ConcatObjectObjectObject, System_String__ConcatObjectArray, System_String__op_Equality, System_String__op_Inequality, System_String__Length, System_String__Chars, System_String__Format, System_String__Substring, System_Double__IsNaN, System_Single__IsNaN, System_Delegate__Combine, System_Delegate__Remove, System_Delegate__op_Equality, System_Delegate__op_Inequality, System_Decimal__Zero, System_Decimal__MinusOne, System_Decimal__One, System_Decimal__CtorInt32, System_Decimal__CtorUInt32, System_Decimal__CtorInt64, System_Decimal__CtorUInt64, System_Decimal__CtorSingle, System_Decimal__CtorDouble, System_Decimal__CtorInt32Int32Int32BooleanByte, System_Decimal__op_Addition, System_Decimal__op_Subtraction, System_Decimal__op_Multiply, System_Decimal__op_Division, System_Decimal__op_Modulus, System_Decimal__op_UnaryNegation, System_Decimal__op_Increment, System_Decimal__op_Decrement, System_Decimal__NegateDecimal, System_Decimal__RemainderDecimalDecimal, System_Decimal__AddDecimalDecimal, System_Decimal__SubtractDecimalDecimal, System_Decimal__MultiplyDecimalDecimal, System_Decimal__DivideDecimalDecimal, System_Decimal__ModuloDecimalDecimal, System_Decimal__CompareDecimalDecimal, System_Decimal__op_Equality, System_Decimal__op_Inequality, System_Decimal__op_GreaterThan, System_Decimal__op_GreaterThanOrEqual, System_Decimal__op_LessThan, System_Decimal__op_LessThanOrEqual, System_Decimal__op_Implicit_FromByte, System_Decimal__op_Implicit_FromChar, System_Decimal__op_Implicit_FromInt16, System_Decimal__op_Implicit_FromInt32, System_Decimal__op_Implicit_FromInt64, System_Decimal__op_Implicit_FromSByte, System_Decimal__op_Implicit_FromUInt16, System_Decimal__op_Implicit_FromUInt32, System_Decimal__op_Implicit_FromUInt64, System_Decimal__op_Explicit_ToByte, System_Decimal__op_Explicit_ToUInt16, System_Decimal__op_Explicit_ToSByte, System_Decimal__op_Explicit_ToInt16, System_Decimal__op_Explicit_ToSingle, System_Decimal__op_Explicit_ToDouble, System_Decimal__op_Explicit_ToChar, System_Decimal__op_Explicit_ToUInt64, System_Decimal__op_Explicit_ToInt32, System_Decimal__op_Explicit_ToUInt32, System_Decimal__op_Explicit_ToInt64, System_Decimal__op_Explicit_FromDouble, System_Decimal__op_Explicit_FromSingle, System_DateTime__MinValue, System_DateTime__CtorInt64, System_DateTime__CompareDateTimeDateTime, System_DateTime__op_Equality, System_DateTime__op_Inequality, System_DateTime__op_GreaterThan, System_DateTime__op_GreaterThanOrEqual, System_DateTime__op_LessThan, System_DateTime__op_LessThanOrEqual, System_Collections_IEnumerable__GetEnumerator, System_Collections_IEnumerator__Current, System_Collections_IEnumerator__get_Current, System_Collections_IEnumerator__MoveNext, System_Collections_IEnumerator__Reset, System_Collections_Generic_IEnumerable_T__GetEnumerator, System_Collections_Generic_IEnumerator_T__Current, System_Collections_Generic_IEnumerator_T__get_Current, System_IDisposable__Dispose, System_Array__Length, System_Array__LongLength, System_Array__GetLowerBound, System_Array__GetUpperBound, System_Object__GetHashCode, System_Object__Equals, System_Object__EqualsObjectObject, System_Object__ToString, System_Object__ReferenceEquals, System_IntPtr__op_Explicit_ToPointer, System_IntPtr__op_Explicit_ToInt32, System_IntPtr__op_Explicit_ToInt64, System_IntPtr__op_Explicit_FromPointer, System_IntPtr__op_Explicit_FromInt32, System_IntPtr__op_Explicit_FromInt64, System_UIntPtr__op_Explicit_ToPointer, System_UIntPtr__op_Explicit_ToUInt32, System_UIntPtr__op_Explicit_ToUInt64, System_UIntPtr__op_Explicit_FromPointer, System_UIntPtr__op_Explicit_FromUInt32, System_UIntPtr__op_Explicit_FromUInt64, System_Nullable_T_GetValueOrDefault, System_Nullable_T_get_Value, System_Nullable_T_get_HasValue, System_Nullable_T__ctor, System_Nullable_T__op_Implicit_FromT, System_Nullable_T__op_Explicit_ToT, System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces, System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention, System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses, System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor, Count } }
// 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. namespace Microsoft.CodeAnalysis { // members of special types internal enum SpecialMember { System_String__CtorSZArrayChar, System_String__ConcatStringString, System_String__ConcatStringStringString, System_String__ConcatStringStringStringString, System_String__ConcatStringArray, System_String__ConcatObject, System_String__ConcatObjectObject, System_String__ConcatObjectObjectObject, System_String__ConcatObjectArray, System_String__op_Equality, System_String__op_Inequality, System_String__Length, System_String__Chars, System_String__Format, System_String__Substring, System_Double__IsNaN, System_Single__IsNaN, System_Delegate__Combine, System_Delegate__Remove, System_Delegate__op_Equality, System_Delegate__op_Inequality, System_Decimal__Zero, System_Decimal__MinusOne, System_Decimal__One, System_Decimal__CtorInt32, System_Decimal__CtorUInt32, System_Decimal__CtorInt64, System_Decimal__CtorUInt64, System_Decimal__CtorSingle, System_Decimal__CtorDouble, System_Decimal__CtorInt32Int32Int32BooleanByte, System_Decimal__op_Addition, System_Decimal__op_Subtraction, System_Decimal__op_Multiply, System_Decimal__op_Division, System_Decimal__op_Modulus, System_Decimal__op_UnaryNegation, System_Decimal__op_Increment, System_Decimal__op_Decrement, System_Decimal__NegateDecimal, System_Decimal__RemainderDecimalDecimal, System_Decimal__AddDecimalDecimal, System_Decimal__SubtractDecimalDecimal, System_Decimal__MultiplyDecimalDecimal, System_Decimal__DivideDecimalDecimal, System_Decimal__ModuloDecimalDecimal, System_Decimal__CompareDecimalDecimal, System_Decimal__op_Equality, System_Decimal__op_Inequality, System_Decimal__op_GreaterThan, System_Decimal__op_GreaterThanOrEqual, System_Decimal__op_LessThan, System_Decimal__op_LessThanOrEqual, System_Decimal__op_Implicit_FromByte, System_Decimal__op_Implicit_FromChar, System_Decimal__op_Implicit_FromInt16, System_Decimal__op_Implicit_FromInt32, System_Decimal__op_Implicit_FromInt64, System_Decimal__op_Implicit_FromSByte, System_Decimal__op_Implicit_FromUInt16, System_Decimal__op_Implicit_FromUInt32, System_Decimal__op_Implicit_FromUInt64, System_Decimal__op_Explicit_ToByte, System_Decimal__op_Explicit_ToUInt16, System_Decimal__op_Explicit_ToSByte, System_Decimal__op_Explicit_ToInt16, System_Decimal__op_Explicit_ToSingle, System_Decimal__op_Explicit_ToDouble, System_Decimal__op_Explicit_ToChar, System_Decimal__op_Explicit_ToUInt64, System_Decimal__op_Explicit_ToInt32, System_Decimal__op_Explicit_ToUInt32, System_Decimal__op_Explicit_ToInt64, System_Decimal__op_Explicit_FromDouble, System_Decimal__op_Explicit_FromSingle, System_DateTime__MinValue, System_DateTime__CtorInt64, System_DateTime__CompareDateTimeDateTime, System_DateTime__op_Equality, System_DateTime__op_Inequality, System_DateTime__op_GreaterThan, System_DateTime__op_GreaterThanOrEqual, System_DateTime__op_LessThan, System_DateTime__op_LessThanOrEqual, System_Collections_IEnumerable__GetEnumerator, System_Collections_IEnumerator__Current, System_Collections_IEnumerator__get_Current, System_Collections_IEnumerator__MoveNext, System_Collections_IEnumerator__Reset, System_Collections_Generic_IEnumerable_T__GetEnumerator, System_Collections_Generic_IEnumerator_T__Current, System_Collections_Generic_IEnumerator_T__get_Current, System_IDisposable__Dispose, System_Array__Length, System_Array__LongLength, System_Array__GetLowerBound, System_Array__GetUpperBound, System_Object__GetHashCode, System_Object__Equals, System_Object__EqualsObjectObject, System_Object__ToString, System_Object__ReferenceEquals, System_IntPtr__op_Explicit_ToPointer, System_IntPtr__op_Explicit_ToInt32, System_IntPtr__op_Explicit_ToInt64, System_IntPtr__op_Explicit_FromPointer, System_IntPtr__op_Explicit_FromInt32, System_IntPtr__op_Explicit_FromInt64, System_UIntPtr__op_Explicit_ToPointer, System_UIntPtr__op_Explicit_ToUInt32, System_UIntPtr__op_Explicit_ToUInt64, System_UIntPtr__op_Explicit_FromPointer, System_UIntPtr__op_Explicit_FromUInt32, System_UIntPtr__op_Explicit_FromUInt64, System_Nullable_T_GetValueOrDefault, System_Nullable_T_get_Value, System_Nullable_T_get_HasValue, System_Nullable_T__ctor, System_Nullable_T__op_Implicit_FromT, System_Nullable_T__op_Explicit_ToT, System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces, System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention, System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses, System_Runtime_CompilerServices_RuntimeFeature__VirtualStaticsInInterfaces, System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor, Count } }
1